]> git.nihav.org Git - nihav.git/blob - nihav-core/src/codecs/mod.rs
1482a61f67ae5ca1ea64a1ea95e8d556aece90ee
[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 /// Frame skipping mode for decoders.
138 #[derive(Clone,Copy,PartialEq,Debug)]
139 pub enum FrameSkipMode {
140 /// Decode all frames.
141 None,
142 /// Decode all key frames.
143 KeyframesOnly,
144 /// Decode only intra frames.
145 IntraOnly,
146 }
147
148 impl Default for FrameSkipMode {
149 fn default() -> Self {
150 FrameSkipMode::None
151 }
152 }
153
154 impl 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
167 impl 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
177 /// A list specifying general encoding errors.
178 #[derive(Debug,Clone,Copy,PartialEq)]
179 #[allow(dead_code)]
180 pub 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.
198 pub type EncoderResult<T> = Result<T, EncoderError>;
199
200 impl From<ByteIOError> for EncoderError {
201 fn from(_: ByteIOError) -> Self { EncoderError::Bug }
202 }
203
204 impl From<AllocatorError> for EncoderError {
205 fn from(_: AllocatorError) -> Self { EncoderError::AllocError }
206 }
207
208 /// Encoding parameter flag to force constant bitrate mode.
209 pub const ENC_MODE_CBR: u64 = 1 << 0;
210 /// Encoding parameter flag to force constant framerate mode.
211 pub const ENC_MODE_CFR: u64 = 1 << 1;
212
213 /// Encoder supports constant bitrate mode.
214 pub const ENC_CAPS_CBR: u64 = 1 << 0;
215 /// Encoder supports skip frames.
216 pub const ENC_CAPS_SKIPFRAME: u64 = 1 << 1;
217 /// Encoder supports mid-stream parameters change.
218 pub const ENC_CAPS_PARAMCHANGE: u64 = 1 << 2;
219
220 /// Encoding parameters.
221 #[derive(Clone,Copy,PartialEq)]
222 pub 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 bits 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
239 impl 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)?;
275 /// while let Ok(enc_pkt) = encoder.get_packet()? {
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
289 pub trait NAEncoder: NAOptionHandler {
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>;
310 /// Queries encoder capabilities.
311 ///
312 /// See `ENC_CAPS_*` for examples.
313 fn get_capabilities(&self) -> u64;
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)]
326 pub 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 ///
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.
336 #[derive(Default)]
337 pub struct RegisteredEncoders {
338 encs: Vec<EncoderInfo>,
339 }
340
341 impl 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
365 /// Trait for packetisers (objects that form full packets from raw stream data).
366 pub 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);
388 /// Tells how much data is left in the internal buffer.
389 fn bytes_left(&self) -> usize;
390 }
391
392 /// Decoder information used during creating a packetiser for requested codec.
393 #[derive(Clone,Copy)]
394 pub 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)]
405 pub struct RegisteredPacketisers {
406 packs: Vec<PacketiserInfo>,
407 }
408
409 impl 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