04d480a81db0d02766ebed9014ff503bb67f6c85
[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 pub use std::str::FromStr;
8
9 /// A list specifying general decoding errors.
10 #[derive(Debug,Clone,Copy,PartialEq)]
11 #[allow(dead_code)]
12 pub enum DecoderError {
13 /// No frame was provided.
14 NoFrame,
15 /// Allocation failed.
16 AllocError,
17 /// Operation requires repeating.
18 TryAgain,
19 /// Invalid input data was provided.
20 InvalidData,
21 /// Checksum verification failed.
22 ChecksumError,
23 /// Provided input turned out to be incomplete.
24 ShortData,
25 /// Decoder could not decode provided frame because it references some missing previous frame.
26 MissingReference,
27 /// Feature is not implemented.
28 NotImplemented,
29 /// Some bug in decoder. It should not happen yet it might.
30 Bug,
31 }
32
33 /// A specialised `Result` type for decoding operations.
34 pub type DecoderResult<T> = Result<T, DecoderError>;
35
36 impl From<ByteIOError> for DecoderError {
37 fn from(_: ByteIOError) -> Self { DecoderError::ShortData }
38 }
39
40 impl From<BitReaderError> for DecoderError {
41 fn from(e: BitReaderError) -> Self {
42 match e {
43 BitReaderError::BitstreamEnd => DecoderError::ShortData,
44 _ => DecoderError::InvalidData,
45 }
46 }
47 }
48
49 impl From<CodebookError> for DecoderError {
50 fn from(_: CodebookError) -> Self { DecoderError::InvalidData }
51 }
52
53 impl From<AllocatorError> for DecoderError {
54 fn from(_: AllocatorError) -> Self { DecoderError::AllocError }
55 }
56
57 /// Auxiliary structure for storing data used by decoder but also controlled by the caller.
58 pub struct NADecoderSupport {
59 /// Frame buffer pool for 8-bit or packed video frames.
60 pub pool_u8: NAVideoBufferPool<u8>,
61 /// Frame buffer pool for 16-bit video frames.
62 pub pool_u16: NAVideoBufferPool<u16>,
63 /// Frame buffer pool for 32-bit video frames.
64 pub pool_u32: NAVideoBufferPool<u32>,
65 }
66
67 impl NADecoderSupport {
68 /// Constructs a new instance of `NADecoderSupport`.
69 pub fn new() -> Self {
70 Self {
71 pool_u8: NAVideoBufferPool::new(0),
72 pool_u16: NAVideoBufferPool::new(0),
73 pool_u32: NAVideoBufferPool::new(0),
74 }
75 }
76 }
77
78 impl Default for NADecoderSupport {
79 fn default() -> Self { Self::new() }
80 }
81
82 /// Decoder trait.
83 pub trait NADecoder: NAOptionHandler {
84 /// Initialises the decoder.
85 ///
86 /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer.
87 ///
88 /// [`NADecoderSupport`]: ./struct.NADecoderSupport.html
89 fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()>;
90 /// Decodes a single frame.
91 fn decode(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef>;
92 /// Tells decoder to clear internal state (e.g. after error or seeking).
93 fn flush(&mut self);
94 }
95
96 /// Decoder information used during creating a decoder for requested codec.
97 #[derive(Clone,Copy)]
98 pub struct DecoderInfo {
99 /// Short decoder name.
100 pub name: &'static str,
101 /// The function that creates a decoder instance.
102 pub get_decoder: fn () -> Box<dyn NADecoder + Send>,
103 }
104
105 /// Structure for registering known decoders.
106 ///
107 /// It is supposed to be filled using `register_all_decoders()` from some decoders crate and then it can be used to create decoders for the requested codecs.
108 #[derive(Default)]
109 pub struct RegisteredDecoders {
110 decs: Vec<DecoderInfo>,
111 }
112
113 impl RegisteredDecoders {
114 /// Constructs a new instance of `RegisteredDecoders`.
115 pub fn new() -> Self {
116 Self { decs: Vec::new() }
117 }
118 /// Adds another decoder to the registry.
119 pub fn add_decoder(&mut self, dec: DecoderInfo) {
120 self.decs.push(dec);
121 }
122 /// Searches for the decoder for the provided name and returns a function for creating it on success.
123 pub fn find_decoder(&self, name: &str) -> Option<fn () -> Box<dyn NADecoder + Send>> {
124 for &dec in self.decs.iter() {
125 if dec.name == name {
126 return Some(dec.get_decoder);
127 }
128 }
129 None
130 }
131 /// Provides an iterator over currently registered decoders.
132 pub fn iter(&self) -> std::slice::Iter<DecoderInfo> {
133 self.decs.iter()
134 }
135 }
136
137 /// Multithreaded decoder trait.
138 pub trait NADecoderMT: NAOptionHandler {
139 /// Initialises the decoder.
140 ///
141 /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer.
142 ///
143 /// [`NADecoderSupport`]: ./struct.NADecoderSupport.html
144 fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef, nthreads: usize) -> DecoderResult<()>;
145 /// Checks if a new frame can be queued for encoding.
146 fn can_take_input(&mut self) -> bool;
147 /// Queues a frame for decoding.
148 ///
149 /// Returns flag signalling whether the frame was queued or an error if it occured during the preparation stage.
150 ///
151 /// Parameter `id` is used to distinguish pictures as the output may be an error code with no timestamp available.
152 fn queue_pkt(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket, id: u32) -> DecoderResult<bool>;
153 /// Checks if some frames are already decoded and waiting to be retrieved.
154 fn has_output(&mut self) -> bool;
155 /// Waits for a frame to be decoded.
156 ///
157 /// In case there are no decoded frames yet, `None` is returned.
158 /// Otherwise, a decoding result and the input picture ID are returned.
159 fn get_frame(&mut self) -> (DecoderResult<NAFrameRef>, u32);
160 /// Tells decoder to clear internal state (e.g. after error or seeking).
161 fn flush(&mut self);
162 }
163
164 /// Decoder information used during creating a multi-threaded decoder for requested codec.
165 #[derive(Clone,Copy)]
166 pub struct MTDecoderInfo {
167 /// Short decoder name.
168 pub name: &'static str,
169 /// The function that creates a multi-threaded decoder instance.
170 pub get_decoder: fn () -> Box<dyn NADecoderMT + Send>,
171 }
172
173 /// Structure for registering known multi-threaded decoders.
174 ///
175 /// It is supposed to be filled using `register_all_mt_decoders()` from some decoders crate and then it can be used to create multi-threaded decoders for the requested codecs.
176 #[derive(Default)]
177 pub struct RegisteredMTDecoders {
178 decs: Vec<MTDecoderInfo>,
179 }
180
181 impl RegisteredMTDecoders {
182 /// Constructs a new instance of `RegisteredMTDecoders`.
183 pub fn new() -> Self {
184 Self { decs: Vec::new() }
185 }
186 /// Adds another decoder to the registry.
187 pub fn add_decoder(&mut self, dec: MTDecoderInfo) {
188 self.decs.push(dec);
189 }
190 /// Searches for the decoder for the provided name and returns a function for creating it on success.
191 pub fn find_decoder(&self, name: &str) -> Option<fn () -> Box<dyn NADecoderMT + Send>> {
192 for &dec in self.decs.iter() {
193 if dec.name == name {
194 return Some(dec.get_decoder);
195 }
196 }
197 None
198 }
199 /// Provides an iterator over currently registered decoders.
200 pub fn iter(&self) -> std::slice::Iter<MTDecoderInfo> {
201 self.decs.iter()
202 }
203 }
204
205 /// Frame skipping mode for decoders.
206 #[derive(Clone,Copy,PartialEq,Debug)]
207 pub enum FrameSkipMode {
208 /// Decode all frames.
209 None,
210 /// Decode all key frames.
211 KeyframesOnly,
212 /// Decode only intra frames.
213 IntraOnly,
214 }
215
216 impl Default for FrameSkipMode {
217 fn default() -> Self {
218 FrameSkipMode::None
219 }
220 }
221
222 impl FromStr for FrameSkipMode {
223 type Err = DecoderError;
224
225 fn from_str(s: &str) -> Result<Self, Self::Err> {
226 match s {
227 FRAME_SKIP_OPTION_VAL_NONE => Ok(FrameSkipMode::None),
228 FRAME_SKIP_OPTION_VAL_KEYFRAME => Ok(FrameSkipMode::KeyframesOnly),
229 FRAME_SKIP_OPTION_VAL_INTRA => Ok(FrameSkipMode::IntraOnly),
230 _ => Err(DecoderError::InvalidData),
231 }
232 }
233 }
234
235 impl ToString for FrameSkipMode {
236 fn to_string(&self) -> String {
237 match *self {
238 FrameSkipMode::None => FRAME_SKIP_OPTION_VAL_NONE.to_string(),
239 FrameSkipMode::KeyframesOnly => FRAME_SKIP_OPTION_VAL_KEYFRAME.to_string(),
240 FrameSkipMode::IntraOnly => FRAME_SKIP_OPTION_VAL_INTRA.to_string(),
241 }
242 }
243 }
244
245 /// A list specifying general encoding errors.
246 #[derive(Debug,Clone,Copy,PartialEq)]
247 #[allow(dead_code)]
248 pub enum EncoderError {
249 /// No frame was provided.
250 NoFrame,
251 /// Allocation failed.
252 AllocError,
253 /// Operation requires repeating.
254 TryAgain,
255 /// Input format is not supported by codec.
256 FormatError,
257 /// Invalid input parameters were provided.
258 InvalidParameters,
259 /// Feature is not implemented.
260 NotImplemented,
261 /// Some bug in encoder. It should not happen yet it might.
262 Bug,
263 }
264
265 /// A specialised `Result` type for decoding operations.
266 pub type EncoderResult<T> = Result<T, EncoderError>;
267
268 impl From<ByteIOError> for EncoderError {
269 fn from(_: ByteIOError) -> Self { EncoderError::Bug }
270 }
271
272 impl From<AllocatorError> for EncoderError {
273 fn from(_: AllocatorError) -> Self { EncoderError::AllocError }
274 }
275
276 /// Encoding parameter flag to force constant bitrate mode.
277 pub const ENC_MODE_CBR: u64 = 1 << 0;
278 /// Encoding parameter flag to force constant framerate mode.
279 pub const ENC_MODE_CFR: u64 = 1 << 1;
280
281 /// Encoder supports constant bitrate mode.
282 pub const ENC_CAPS_CBR: u64 = 1 << 0;
283 /// Encoder supports skip frames.
284 pub const ENC_CAPS_SKIPFRAME: u64 = 1 << 1;
285 /// Encoder supports mid-stream parameters change.
286 pub const ENC_CAPS_PARAMCHANGE: u64 = 1 << 2;
287
288 /// Encoding parameters.
289 #[derive(Clone,Copy,PartialEq)]
290 pub struct EncodeParameters {
291 /// Input format.
292 pub format: NACodecTypeInfo,
293 /// Time base numerator. Ignored for audio.
294 pub tb_num: u32,
295 /// Time base denominator. Ignored for audio.
296 pub tb_den: u32,
297 /// Bitrate in bits per second.
298 pub bitrate: u32,
299 /// A collection of various boolean encoder settings like CBR mode.
300 ///
301 /// See `ENC_MODE_*` constants for available options.
302 pub flags: u64,
303 /// Encoding quality.
304 pub quality: u8,
305 }
306
307 impl Default for EncodeParameters {
308 fn default() -> EncodeParameters {
309 EncodeParameters {
310 format: NACodecTypeInfo::None,
311 tb_num: 0,
312 tb_den: 0,
313 bitrate: 0,
314 flags: 0,
315 quality: 0,
316 }
317 }
318 }
319
320 /// Encoder trait.
321 ///
322 /// Overall encoding is more complex than decoding.
323 /// There are at least two issues that should be addressed: input format and the need for lookahead.
324 ///
325 /// Some formats (like MPEG-1 ones) have fixed picture dimensions and framerate, or sampling rate.
326 /// Some formats accept only pictures with dimensions being multiple of eight or sixteen.
327 /// Some audio formats work only with monaural sound.
328 /// 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.
329 /// That is why `NAEncoder` has [`negotiate_format`] function that performs such check and returns what encoder can handle.
330 ///
331 /// 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.
332 /// That is why encoder has two functions, one for queueing frames for encoding and one for obtaining encoded packets when they are available.
333 /// 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.
334 ///
335 /// Overall encoding loop should look like this:
336 /// ```ignore
337 /// let encoder = ...; // create encoder
338 /// let enc_params = encoder.negotiate_format(input_enc_params)?; // negotiate format
339 /// let output_stream = encoder.init(stream_no, enc_params)?;
340 /// while let Some(frame) = queue.get_frame() {
341 /// // convert to the format encoder expects if required
342 /// encoder.encode(frame)?;
343 /// while let Ok(enc_pkt) = encoder.get_packet()? {
344 /// // send encoded packet to a muxer for example
345 /// }
346 /// }
347 /// // retrieve the rest of encoded packets
348 /// encoder.flush()?;
349 /// while let Ok(enc_pkt) = encoder.get_packet()? {
350 /// // send encoded packet to a muxer for example
351 /// }
352 /// ```
353 ///
354 /// [`negotiate_format`]: ./trait.NAEncoder.html#tymethod.negotiate_format
355 /// [`encode`]: ./trait.NAEncoder.html#tymethod.encode
356 /// [`get_packet`]: ./trait.NAEncoder.html#tymethod.get_packet
357 pub trait NAEncoder: NAOptionHandler {
358 /// Tries to negotiate input format.
359 ///
360 /// This function takes input encoding parameters and returns adjusted encoding parameters if input ones make sense.
361 /// If input parameters are empty then the default parameters are returned.
362 ///
363 /// # Example
364 /// ```ignore
365 /// let enc_params = [ EncodeParameters {...}, ..., EncodeParameters::default() ];
366 /// let mut target_params = EncodeParameters::default();
367 /// for params in enc_params.iter() {
368 /// if let Ok(dparams) = encoder.negotiate_format(params) {
369 /// target_params = dparams;
370 /// break;
371 /// }
372 /// }
373 /// // since negotiate_format(EncodeParameters::default()) will return a valid format, target_params should be valid here
374 /// let stream = encoder.init(stream_id, target_params)?;
375 /// // convert input into format defined in target_params, feed to the encoder, ...
376 /// ```
377 fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters>;
378 /// Queries encoder capabilities.
379 ///
380 /// See `ENC_CAPS_*` for examples.
381 fn get_capabilities(&self) -> u64;
382 /// Initialises the encoder.
383 fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef>;
384 /// Takes a single frame for encoding.
385 fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()>;
386 /// Returns encoded packet if available.
387 fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>>;
388 /// Tells encoder to encode all data it currently has.
389 fn flush(&mut self) -> EncoderResult<()>;
390 }
391
392 /// Encoder information used during creating an encoder for requested codec.
393 #[derive(Clone,Copy)]
394 pub struct EncoderInfo {
395 /// Short encoder name.
396 pub name: &'static str,
397 /// The function that creates an encoder instance.
398 pub get_encoder: fn () -> Box<dyn NAEncoder + Send>,
399 }
400
401 /// Structure for registering known encoders.
402 ///
403 /// It is supposed to be filled using `register_all_decoders()` from some encoders crate and then it can be used to create encoders for the requested codecs.
404 #[derive(Default)]
405 pub struct RegisteredEncoders {
406 encs: Vec<EncoderInfo>,
407 }
408
409 impl RegisteredEncoders {
410 /// Constructs a new instance of `RegisteredEncoders`.
411 pub fn new() -> Self {
412 Self { encs: Vec::new() }
413 }
414 /// Adds another encoder to the registry.
415 pub fn add_encoder(&mut self, enc: EncoderInfo) {
416 self.encs.push(enc);
417 }
418 /// Searches for the encoder for the provided name and returns a function for creating it on success.
419 pub fn find_encoder(&self, name: &str) -> Option<fn () -> Box<dyn NAEncoder + Send>> {
420 for &enc in self.encs.iter() {
421 if enc.name == name {
422 return Some(enc.get_encoder);
423 }
424 }
425 None
426 }
427 /// Provides an iterator over currently registered encoders.
428 pub fn iter(&self) -> std::slice::Iter<EncoderInfo> {
429 self.encs.iter()
430 }
431 }
432
433 /// Trait for packetisers (objects that form full packets from raw stream data).
434 pub trait NAPacketiser {
435 /// Queues new raw stream data for parsing.
436 ///
437 /// Returns false is the internal buffer grows too large.
438 fn add_data(&mut self, src: &[u8]) -> bool;
439 /// Tries to retrieve stream information from the data.
440 ///
441 /// Returns [`NAStream`] reference on success (with stream ID set to `id`), [`ShortData`] when there is not enough data to parse the headers and other errors in case there was an error parsing the data.
442 ///
443 /// [`NAStream`]: ../frame/struct.NAStream.html
444 /// [`ShortData`]: ./enum.DecoderError.html#variant.ShortData
445 fn parse_stream(&mut self, id: u32) -> DecoderResult<NAStreamRef>;
446 /// Tries to discard junk data until the first possible packet header.
447 ///
448 /// Returns the number of bytes skipped.
449 fn skip_junk(&mut self) -> DecoderResult<usize>;
450 /// Tries to form full packet from the already queued data.
451 ///
452 /// The function should be called repeatedly until it returns nothing or an error.
453 fn get_packet(&mut self, stream: NAStreamRef) -> DecoderResult<Option<NAPacket>>;
454 /// Resets the internal buffer.
455 fn reset(&mut self);
456 /// Tells how much data is left in the internal buffer.
457 fn bytes_left(&self) -> usize;
458 }
459
460 /// Decoder information used during creating a packetiser for requested codec.
461 #[derive(Clone,Copy)]
462 pub struct PacketiserInfo {
463 /// Short packetiser name.
464 pub name: &'static str,
465 /// The function that creates a packetiser instance.
466 pub get_packetiser: fn () -> Box<dyn NAPacketiser + Send>,
467 }
468
469 /// Structure for registering known packetisers.
470 ///
471 /// It is supposed to be filled using `register_all_packetisers()` from some decoders crate and then it can be used to create packetisers for the requested codecs.
472 #[derive(Default)]
473 pub struct RegisteredPacketisers {
474 packs: Vec<PacketiserInfo>,
475 }
476
477 impl RegisteredPacketisers {
478 /// Constructs a new instance of `RegisteredPacketisers`.
479 pub fn new() -> Self {
480 Self { packs: Vec::new() }
481 }
482 /// Adds another packetiser to the registry.
483 pub fn add_packetiser(&mut self, pack: PacketiserInfo) {
484 self.packs.push(pack);
485 }
486 /// Searches for the packetiser for the provided name and returns a function for creating it on success.
487 pub fn find_packetiser(&self, name: &str) -> Option<fn () -> Box<dyn NAPacketiser + Send>> {
488 for &pack in self.packs.iter() {
489 if pack.name == name {
490 return Some(pack.get_packetiser);
491 }
492 }
493 None
494 }
495 /// Provides an iterator over currently registered packetiser.
496 pub fn iter(&self) -> std::slice::Iter<PacketiserInfo> {
497 self.packs.iter()
498 }
499 }
500