]>
Commit | Line | Data |
---|---|---|
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: NAOptionHandler { | |
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 | impl From<AllocatorError> for EncoderError { | |
162 | fn from(_: AllocatorError) -> Self { EncoderError::AllocError } | |
163 | } | |
164 | ||
165 | /// Encoding parameter flag to force constant bitrate mode. | |
166 | pub const ENC_MODE_CBR: u64 = 1 << 0; | |
167 | /// Encoding parameter flag to force constant framerate mode. | |
168 | pub const ENC_MODE_CFR: u64 = 1 << 1; | |
169 | ||
170 | /// Encoding parameters. | |
171 | #[derive(Clone,Copy,PartialEq)] | |
172 | pub struct EncodeParameters { | |
173 | /// Input format. | |
174 | pub format: NACodecTypeInfo, | |
175 | /// Time base numerator. Ignored for audio. | |
176 | pub tb_num: u32, | |
177 | /// Time base denominator. Ignored for audio. | |
178 | pub tb_den: u32, | |
179 | /// Bitrate in kilobits per second. | |
180 | pub bitrate: u32, | |
181 | /// A collection of various boolean encoder settings like CBR mode. | |
182 | /// | |
183 | /// See `ENC_MODE_*` constants for available options. | |
184 | pub flags: u64, | |
185 | /// Encoding quality. | |
186 | pub quality: u8, | |
187 | } | |
188 | ||
189 | impl Default for EncodeParameters { | |
190 | fn default() -> EncodeParameters { | |
191 | EncodeParameters { | |
192 | format: NACodecTypeInfo::None, | |
193 | tb_num: 0, | |
194 | tb_den: 0, | |
195 | bitrate: 0, | |
196 | flags: 0, | |
197 | quality: 0, | |
198 | } | |
199 | } | |
200 | } | |
201 | ||
202 | /// Encoder trait. | |
203 | /// | |
204 | /// Overall encoding is more complex than decoding. | |
205 | /// There are at least two issues that should be addressed: input format and the need for lookahead. | |
206 | /// | |
207 | /// Some formats (like MPEG-1 ones) have fixed picture dimensions and framerate, or sampling rate. | |
208 | /// Some formats accept only pictures with dimensions being multiple of eight or sixteen. | |
209 | /// Some audio formats work only with monaural sound. | |
210 | /// 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. | |
211 | /// That is why `NAEncoder` has [`negotiate_format`] function that performs such check and returns what encoder can handle. | |
212 | /// | |
213 | /// 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. | |
214 | /// That is why encoder has two functions, one for queueing frames for encoding and one for obtaining encoded packets when they are available. | |
215 | /// 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. | |
216 | /// | |
217 | /// Overall encoding loop should look like this: | |
218 | /// ```ignore | |
219 | /// let encoder = ...; // create encoder | |
220 | /// let enc_params = encoder.negotiate_format(input_enc_params)?; // negotiate format | |
221 | /// let output_stream = encoder.init(stream_no, enc_params)?; | |
222 | /// while let Some(frame) = queue.get_frame() { | |
223 | /// // convert to the format encoder expects if required | |
224 | /// encoder.encode(frame)?; | |
225 | /// while let Some(enc_pkt) = encoder.get_packet()? { | |
226 | /// // send encoded packet to a muxer for example | |
227 | /// } | |
228 | /// } | |
229 | /// // retrieve the rest of encoded packets | |
230 | /// encoder.flush()?; | |
231 | /// while let Ok(enc_pkt) = encoder.get_packet()? { | |
232 | /// // send encoded packet to a muxer for example | |
233 | /// } | |
234 | /// ``` | |
235 | /// | |
236 | /// [`negotiate_format`]: ./trait.NAEncoder.html#tymethod.negotiate_format | |
237 | /// [`encode`]: ./trait.NAEncoder.html#tymethod.encode | |
238 | /// [`get_packet`]: ./trait.NAEncoder.html#tymethod.get_packet | |
239 | pub trait NAEncoder: NAOptionHandler { | |
240 | /// Tries to negotiate input format. | |
241 | /// | |
242 | /// This function takes input encoding parameters and returns adjusted encoding parameters if input ones make sense. | |
243 | /// If input parameters are empty then the default parameters are returned. | |
244 | /// | |
245 | /// # Example | |
246 | /// ```ignore | |
247 | /// let enc_params = [ EncodeParameters {...}, ..., EncodeParameters::default() ]; | |
248 | /// let mut target_params = EncodeParameters::default(); | |
249 | /// for params in enc_params.iter() { | |
250 | /// if let Ok(dparams) = encoder.negotiate_format(params) { | |
251 | /// target_params = dparams; | |
252 | /// break; | |
253 | /// } | |
254 | /// } | |
255 | /// // since negotiate_format(EncodeParameters::default()) will return a valid format, target_params should be valid here | |
256 | /// let stream = encoder.init(stream_id, target_params)?; | |
257 | /// // convert input into format defined in target_params, feed to the encoder, ... | |
258 | /// ``` | |
259 | fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters>; | |
260 | /// Initialises the encoder. | |
261 | fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef>; | |
262 | /// Takes a single frame for encoding. | |
263 | fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()>; | |
264 | /// Returns encoded packet if available. | |
265 | fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>>; | |
266 | /// Tells encoder to encode all data it currently has. | |
267 | fn flush(&mut self) -> EncoderResult<()>; | |
268 | } | |
269 | ||
270 | /// Encoder information used during creating an encoder for requested codec. | |
271 | #[derive(Clone,Copy)] | |
272 | pub struct EncoderInfo { | |
273 | /// Short encoder name. | |
274 | pub name: &'static str, | |
275 | /// The function that creates an encoder instance. | |
276 | pub get_encoder: fn () -> Box<dyn NAEncoder + Send>, | |
277 | } | |
278 | ||
279 | /// Structure for registering known encoders. | |
280 | /// | |
281 | /// 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. | |
282 | #[derive(Default)] | |
283 | pub struct RegisteredEncoders { | |
284 | encs: Vec<EncoderInfo>, | |
285 | } | |
286 | ||
287 | impl RegisteredEncoders { | |
288 | /// Constructs a new instance of `RegisteredEncoders`. | |
289 | pub fn new() -> Self { | |
290 | Self { encs: Vec::new() } | |
291 | } | |
292 | /// Adds another encoder to the registry. | |
293 | pub fn add_encoder(&mut self, enc: EncoderInfo) { | |
294 | self.encs.push(enc); | |
295 | } | |
296 | /// Searches for the encoder for the provided name and returns a function for creating it on success. | |
297 | pub fn find_encoder(&self, name: &str) -> Option<fn () -> Box<dyn NAEncoder + Send>> { | |
298 | for &enc in self.encs.iter() { | |
299 | if enc.name == name { | |
300 | return Some(enc.get_encoder); | |
301 | } | |
302 | } | |
303 | None | |
304 | } | |
305 | /// Provides an iterator over currently registered encoders. | |
306 | pub fn iter(&self) -> std::slice::Iter<EncoderInfo> { | |
307 | self.encs.iter() | |
308 | } | |
309 | } | |
310 |