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