fix clippy warnings
[nihav.git] / nihav-core / src / codecs / mod.rs
index 43abbfd12ebd92209d7553ed9e327f678f9935ae..37857d98d1f3cc7d4779bc628171b2c8ec68747a 100644 (file)
@@ -4,6 +4,7 @@ use crate::io::byteio::ByteIOError;
 use crate::io::bitreader::BitReaderError;
 use crate::io::codebook::CodebookError;
 pub use crate::options::*;
+pub use std::str::FromStr;
 
 /// A list specifying general decoding errors.
 #[derive(Debug,Clone,Copy,PartialEq)]
@@ -17,6 +18,8 @@ pub enum DecoderError {
     TryAgain,
     /// Invalid input data was provided.
     InvalidData,
+    /// Checksum verification failed.
+    ChecksumError,
     /// Provided input turned out to be incomplete.
     ShortData,
     /// Decoder could not decode provided frame because it references some missing previous frame.
@@ -101,7 +104,7 @@ pub struct DecoderInfo {
 
 /// Structure for registering known decoders.
 ///
-/// 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.
+/// 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.
 #[derive(Default)]
 pub struct RegisteredDecoders {
     decs:   Vec<DecoderInfo>,
@@ -131,6 +134,109 @@ impl RegisteredDecoders {
     }
 }
 
+/// Multithreaded decoder trait.
+pub trait NADecoderMT: NAOptionHandler {
+    /// Initialises the decoder.
+    ///
+    /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer.
+    ///
+    /// [`NADecoderSupport`]: ./struct.NADecoderSupport.html
+    fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef, nthreads: usize) -> DecoderResult<()>;
+    /// Checks if a new frame can be queued for encoding.
+    fn can_take_input(&mut self) -> bool;
+    /// Queues a frame for decoding.
+    ///
+    /// Returns flag signalling whether the frame was queued or an error if it occured during the preparation stage.
+    ///
+    /// Parameter `id` is used to distinguish pictures as the output may be an error code with no timestamp available.
+    fn queue_pkt(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket, id: u32) -> DecoderResult<bool>;
+    /// Checks if some frames are already decoded and waiting to be retrieved.
+    fn has_output(&mut self) -> bool;
+    /// Waits for a frame to be decoded.
+    ///
+    /// In case there are no decoded frames yet, `None` is returned.
+    /// Otherwise, a decoding result and the input picture ID are returned.
+    fn get_frame(&mut self) -> (DecoderResult<NAFrameRef>, u32);
+    /// Tells decoder to clear internal state (e.g. after error or seeking).
+    fn flush(&mut self);
+}
+
+/// Decoder information used during creating a multi-threaded decoder for requested codec.
+#[derive(Clone,Copy)]
+pub struct MTDecoderInfo {
+    /// Short decoder name.
+    pub name: &'static str,
+    /// The function that creates a multi-threaded decoder instance.
+    pub get_decoder: fn () -> Box<dyn NADecoderMT + Send>,
+}
+
+/// Structure for registering known multi-threaded decoders.
+///
+/// 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.
+#[derive(Default)]
+pub struct RegisteredMTDecoders {
+    decs:   Vec<MTDecoderInfo>,
+}
+
+impl RegisteredMTDecoders {
+    /// Constructs a new instance of `RegisteredMTDecoders`.
+    pub fn new() -> Self {
+        Self { decs: Vec::new() }
+    }
+    /// Adds another decoder to the registry.
+    pub fn add_decoder(&mut self, dec: MTDecoderInfo) {
+        self.decs.push(dec);
+    }
+    /// Searches for the decoder for the provided name and returns a function for creating it on success.
+    pub fn find_decoder(&self, name: &str) -> Option<fn () -> Box<dyn NADecoderMT + Send>> {
+        for &dec in self.decs.iter() {
+            if dec.name == name {
+                return Some(dec.get_decoder);
+            }
+        }
+        None
+    }
+    /// Provides an iterator over currently registered decoders.
+    pub fn iter(&self) -> std::slice::Iter<MTDecoderInfo> {
+        self.decs.iter()
+    }
+}
+
+/// Frame skipping mode for decoders.
+#[derive(Clone,Copy,PartialEq,Debug,Default)]
+pub enum FrameSkipMode {
+    /// Decode all frames.
+    #[default]
+    None,
+    /// Decode all key frames.
+    KeyframesOnly,
+    /// Decode only intra frames.
+    IntraOnly,
+}
+
+impl FromStr for FrameSkipMode {
+    type Err = DecoderError;
+
+    fn from_str(s: &str) -> Result<Self, Self::Err> {
+        match s {
+            FRAME_SKIP_OPTION_VAL_NONE      => Ok(FrameSkipMode::None),
+            FRAME_SKIP_OPTION_VAL_KEYFRAME  => Ok(FrameSkipMode::KeyframesOnly),
+            FRAME_SKIP_OPTION_VAL_INTRA     => Ok(FrameSkipMode::IntraOnly),
+            _ => Err(DecoderError::InvalidData),
+        }
+    }
+}
+
+impl ToString for FrameSkipMode {
+    fn to_string(&self) -> String {
+        match *self {
+            FrameSkipMode::None             => FRAME_SKIP_OPTION_VAL_NONE.to_string(),
+            FrameSkipMode::KeyframesOnly    => FRAME_SKIP_OPTION_VAL_KEYFRAME.to_string(),
+            FrameSkipMode::IntraOnly        => FRAME_SKIP_OPTION_VAL_INTRA.to_string(),
+        }
+    }
+}
+
 /// A list specifying general encoding errors.
 #[derive(Debug,Clone,Copy,PartialEq)]
 #[allow(dead_code)]
@@ -167,6 +273,13 @@ pub const ENC_MODE_CBR: u64 = 1 << 0;
 /// Encoding parameter flag to force constant framerate mode.
 pub const ENC_MODE_CFR: u64 = 1 << 1;
 
+/// Encoder supports constant bitrate mode.
+pub const ENC_CAPS_CBR: u64 = 1 << 0;
+/// Encoder supports skip frames.
+pub const ENC_CAPS_SKIPFRAME: u64 = 1 << 1;
+/// Encoder supports mid-stream parameters change.
+pub const ENC_CAPS_PARAMCHANGE: u64 = 1 << 2;
+
 /// Encoding parameters.
 #[derive(Clone,Copy,PartialEq)]
 pub struct EncodeParameters {
@@ -176,7 +289,7 @@ pub struct EncodeParameters {
     pub tb_num:     u32,
     /// Time base denominator. Ignored for audio.
     pub tb_den:     u32,
-    /// Bitrate in kilobits per second.
+    /// Bitrate in bits per second.
     pub bitrate:    u32,
     /// A collection of various boolean encoder settings like CBR mode.
     ///
@@ -222,7 +335,7 @@ impl Default for EncodeParameters {
 /// while let Some(frame) = queue.get_frame() {
 ///     // convert to the format encoder expects if required
 ///     encoder.encode(frame)?;
-///     while let Some(enc_pkt) = encoder.get_packet()? {
+///     while let Ok(enc_pkt) = encoder.get_packet()? {
 ///         // send encoded packet to a muxer for example
 ///     }
 /// }
@@ -257,6 +370,10 @@ pub trait NAEncoder: NAOptionHandler {
     /// // convert input into format defined in target_params, feed to the encoder, ...
     /// ```
     fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters>;
+    /// Queries encoder capabilities.
+    ///
+    /// See `ENC_CAPS_*` for examples.
+    fn get_capabilities(&self) -> u64;
     /// Initialises the encoder.
     fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef>;
     /// Takes a single frame for encoding.
@@ -278,7 +395,7 @@ pub struct EncoderInfo {
 
 /// Structure for registering known encoders.
 ///
-/// 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.
+/// 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.
 #[derive(Default)]
 pub struct RegisteredEncoders {
     encs:   Vec<EncoderInfo>,
@@ -308,3 +425,71 @@ impl RegisteredEncoders {
     }
 }
 
+/// Trait for packetisers (objects that form full packets from raw stream data).
+pub trait NAPacketiser {
+    /// Queues new raw stream data for parsing.
+    ///
+    /// Returns false is the internal buffer grows too large.
+    fn add_data(&mut self, src: &[u8]) -> bool;
+    /// Tries to retrieve stream information from the data.
+    ///
+    /// 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.
+    ///
+    /// [`NAStream`]: ../frame/struct.NAStream.html
+    /// [`ShortData`]: ./enum.DecoderError.html#variant.ShortData
+    fn parse_stream(&mut self, id: u32) -> DecoderResult<NAStreamRef>;
+    /// Tries to discard junk data until the first possible packet header.
+    ///
+    /// Returns the number of bytes skipped.
+    fn skip_junk(&mut self) -> DecoderResult<usize>;
+    /// Tries to form full packet from the already queued data.
+    ///
+    /// The function should be called repeatedly until it returns nothing or an error.
+    fn get_packet(&mut self, stream: NAStreamRef) -> DecoderResult<Option<NAPacket>>;
+    /// Resets the internal buffer.
+    fn reset(&mut self);
+    /// Tells how much data is left in the internal buffer.
+    fn bytes_left(&self) -> usize;
+}
+
+/// Decoder information used during creating a packetiser for requested codec.
+#[derive(Clone,Copy)]
+pub struct PacketiserInfo {
+    /// Short packetiser name.
+    pub name: &'static str,
+    /// The function that creates a packetiser instance.
+    pub get_packetiser: fn () -> Box<dyn NAPacketiser + Send>,
+}
+
+/// Structure for registering known packetisers.
+///
+/// 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.
+#[derive(Default)]
+pub struct RegisteredPacketisers {
+    packs:  Vec<PacketiserInfo>,
+}
+
+impl RegisteredPacketisers {
+    /// Constructs a new instance of `RegisteredPacketisers`.
+    pub fn new() -> Self {
+        Self { packs: Vec::new() }
+    }
+    /// Adds another packetiser to the registry.
+    pub fn add_packetiser(&mut self, pack: PacketiserInfo) {
+        self.packs.push(pack);
+    }
+    /// Searches for the packetiser for the provided name and returns a function for creating it on success.
+    pub fn find_packetiser(&self, name: &str) -> Option<fn () -> Box<dyn NAPacketiser + Send>> {
+        for &pack in self.packs.iter() {
+            if pack.name == name {
+                return Some(pack.get_packetiser);
+            }
+        }
+        None
+    }
+    /// Provides an iterator over currently registered packetiser.
+    pub fn iter(&self) -> std::slice::Iter<PacketiserInfo> {
+        self.packs.iter()
+    }
+}
+