]>
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 | ||
7 | /// A list specifying general decoding errors. | |
8 | #[derive(Debug,Clone,Copy,PartialEq)] | |
9 | #[allow(dead_code)] | |
10 | pub enum DecoderError { | |
11 | /// No frame was provided. | |
12 | NoFrame, | |
13 | /// Allocation failed. | |
14 | AllocError, | |
15 | /// Operation requires repeating. | |
16 | TryAgain, | |
17 | /// Invalid input data was provided. | |
18 | InvalidData, | |
19 | /// Provided input turned out to be incomplete. | |
20 | ShortData, | |
21 | /// Decoder could not decode provided frame because it references some missing previous frame. | |
22 | MissingReference, | |
23 | /// Feature is not implemented. | |
24 | NotImplemented, | |
25 | /// Some bug in decoder. It should not happen yet it might. | |
26 | Bug, | |
27 | } | |
28 | ||
29 | /// A specialised `Result` type for decoding operations. | |
30 | pub type DecoderResult<T> = Result<T, DecoderError>; | |
31 | ||
32 | impl From<ByteIOError> for DecoderError { | |
33 | fn from(_: ByteIOError) -> Self { DecoderError::ShortData } | |
34 | } | |
35 | ||
36 | impl From<BitReaderError> for DecoderError { | |
37 | fn from(e: BitReaderError) -> Self { | |
38 | match e { | |
39 | BitReaderError::BitstreamEnd => DecoderError::ShortData, | |
40 | _ => DecoderError::InvalidData, | |
41 | } | |
42 | } | |
43 | } | |
44 | ||
45 | impl From<CodebookError> for DecoderError { | |
46 | fn from(_: CodebookError) -> Self { DecoderError::InvalidData } | |
47 | } | |
48 | ||
49 | impl From<AllocatorError> for DecoderError { | |
50 | fn from(_: AllocatorError) -> Self { DecoderError::AllocError } | |
51 | } | |
52 | ||
53 | /// Auxiliary structure for storing data used by decoder but also controlled by the caller. | |
54 | pub struct NADecoderSupport { | |
55 | /// Frame buffer pool for 8-bit or packed video frames. | |
56 | pub pool_u8: NAVideoBufferPool<u8>, | |
57 | /// Frame buffer pool for 16-bit video frames. | |
58 | pub pool_u16: NAVideoBufferPool<u16>, | |
59 | /// Frame buffer pool for 32-bit video frames. | |
60 | pub pool_u32: NAVideoBufferPool<u32>, | |
61 | } | |
62 | ||
63 | impl NADecoderSupport { | |
64 | /// Constructs a new instance of `NADecoderSupport`. | |
65 | pub fn new() -> Self { | |
66 | Self { | |
67 | pool_u8: NAVideoBufferPool::new(0), | |
68 | pool_u16: NAVideoBufferPool::new(0), | |
69 | pool_u32: NAVideoBufferPool::new(0), | |
70 | } | |
71 | } | |
72 | } | |
73 | ||
74 | impl Default for NADecoderSupport { | |
75 | fn default() -> Self { Self::new() } | |
76 | } | |
77 | ||
78 | /// Decoder trait. | |
79 | pub trait NADecoder { | |
80 | /// Initialises the decoder. | |
81 | /// | |
82 | /// It takes [`NADecoderSupport`] allocated by the caller and `NACodecInfoRef` provided by demuxer. | |
83 | /// | |
84 | /// [`NADecoderSupport`]: ./struct.NADecoderSupport.html | |
85 | fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()>; | |
86 | /// Decodes a single frame. | |
87 | fn decode(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef>; | |
88 | /// Tells decoder to clear internal state (e.g. after error or seeking). | |
89 | fn flush(&mut self); | |
90 | } | |
91 | ||
92 | /// Decoder information used during creating a decoder for requested codec. | |
93 | #[derive(Clone,Copy)] | |
94 | pub struct DecoderInfo { | |
95 | /// Short decoder name. | |
96 | pub name: &'static str, | |
97 | /// The function that creates a decoder instance. | |
98 | pub get_decoder: fn () -> Box<dyn NADecoder + Send>, | |
99 | } | |
100 | ||
101 | /// Structure for registering known decoders. | |
102 | /// | |
103 | /// 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. | |
104 | #[derive(Default)] | |
105 | pub struct RegisteredDecoders { | |
106 | decs: Vec<DecoderInfo>, | |
107 | } | |
108 | ||
109 | impl RegisteredDecoders { | |
110 | /// Constructs a new instance of `RegisteredDecoders`. | |
111 | pub fn new() -> Self { | |
112 | Self { decs: Vec::new() } | |
113 | } | |
114 | /// Adds another decoder to the registry. | |
115 | pub fn add_decoder(&mut self, dec: DecoderInfo) { | |
116 | self.decs.push(dec); | |
117 | } | |
118 | /// Searches for the decoder for the provided name and returns a function for creating it on success. | |
119 | pub fn find_decoder(&self, name: &str) -> Option<fn () -> Box<dyn NADecoder + Send>> { | |
120 | for &dec in self.decs.iter() { | |
121 | if dec.name == name { | |
122 | return Some(dec.get_decoder); | |
123 | } | |
124 | } | |
125 | None | |
126 | } | |
127 | /// Provides an iterator over currently registered decoders. | |
128 | pub fn iter(&self) -> std::slice::Iter<DecoderInfo> { | |
129 | self.decs.iter() | |
130 | } | |
131 | } | |
132 | ||
133 | /// A list specifying general encoding errors. | |
134 | #[derive(Debug,Clone,Copy,PartialEq)] | |
135 | #[allow(dead_code)] | |
136 | pub enum EncoderError { | |
137 | /// No frame was provided. | |
138 | NoFrame, | |
139 | /// Allocation failed. | |
140 | AllocError, | |
141 | /// Operation requires repeating. | |
142 | TryAgain, | |
143 | /// Input format is not supported by codec. | |
144 | FormatError, | |
145 | /// Invalid input parameters were provided. | |
146 | InvalidParameters, | |
147 | /// Feature is not implemented. | |
148 | NotImplemented, | |
149 | /// Some bug in encoder. It should not happen yet it might. | |
150 | Bug, | |
151 | } | |
152 | ||
153 | /// A specialised `Result` type for decoding operations. | |
154 | pub type EncoderResult<T> = Result<T, EncoderError>; | |
155 | ||
156 | impl From<ByteIOError> for EncoderError { | |
157 | fn from(_: ByteIOError) -> Self { EncoderError::Bug } | |
158 | } | |
159 | ||
160 | /// Encoding parameter flag to force constant bitrate mode. | |
161 | pub const ENC_MODE_CBR: u64 = 1 << 0; | |
162 | /// Encoding parameter flag to force constant framerate mode. | |
163 | pub const ENC_MODE_CFR: u64 = 1 << 1; | |
164 | ||
165 | /// Encoding parameters. | |
166 | #[derive(Clone,Copy,PartialEq)] | |
167 | pub struct EncodeParameters { | |
168 | /// Input format. | |
169 | pub format: NACodecTypeInfo, | |
170 | /// Time base numerator. Ignored for audio. | |
171 | pub tb_num: u32, | |
172 | /// Time base denominator. Ignored for audio. | |
173 | pub tb_den: u32, | |
174 | /// Bitrate in kilobits per second. | |
175 | pub bitrate: u32, | |
176 | /// A collection of various boolean encoder settings like CBR mode. | |
177 | /// | |
178 | /// See `ENC_MODE_*` constants for available options. | |
179 | pub flags: u64, | |
180 | /// Encoding quality. | |
181 | pub quality: u8, | |
182 | } | |
183 | ||
184 | impl Default for EncodeParameters { | |
185 | fn default() -> EncodeParameters { | |
186 | EncodeParameters { | |
187 | format: NACodecTypeInfo::None, | |
188 | tb_num: 0, | |
189 | tb_den: 0, | |
190 | bitrate: 0, | |
191 | flags: 0, | |
192 | quality: 0, | |
193 | } | |
194 | } | |
195 | } | |
196 | ||
197 | /// Encoder trait. | |
198 | /// | |
199 | /// Overall encoding is more complex than decoding. | |
200 | /// There are at least two issues that should be addressed: input format and the need for lookahead. | |
201 | /// | |
202 | /// Some formats (like MPEG-1 ones) have fixed picture dimensions and framerate, or sampling rate. | |
203 | /// Some formats accept only pictures with dimensions being multiple of eight or sixteen. | |
204 | /// Some audio formats work only with monaural sound. | |
205 | /// 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. | |
206 | /// That is why `NAEncoder` has [`negotiate_format`] function that performs such check and returns what encoder can handle. | |
207 | /// | |
208 | /// 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. | |
209 | /// That is why encoder has two functions, one for queueing frames for encoding and one for obtaining encoded packets when they are available. | |
210 | /// 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. | |
211 | /// | |
212 | /// Overall encoding loop should look like this: | |
213 | /// ```ignore | |
214 | /// let encoder = ...; // create encoder | |
215 | /// let enc_params = encoder.negotiate_format(input_enc_params)?; // negotiate format | |
216 | /// let output_stream = encoder.init(stream_no, enc_params)?; | |
217 | /// while let Some(frame) = queue.get_frame() { | |
218 | /// // convert to the format encoder expects if required | |
219 | /// encoder.encode(frame)?; | |
220 | /// while let Some(enc_pkt) = encoder.get_packet()? { | |
221 | /// // send encoded packet to a muxer for example | |
222 | /// } | |
223 | /// } | |
224 | /// // retrieve the rest of encoded packets | |
225 | /// encoder.flush()?; | |
226 | /// while let Ok(enc_pkt) = encoder.get_packet()? { | |
227 | /// // send encoded packet to a muxer for example | |
228 | /// } | |
229 | /// ``` | |
230 | /// | |
231 | /// [`negotiate_format`]: ./trait.NAEncoder.html#tymethod.negotiate_format | |
232 | /// [`encode`]: ./trait.NAEncoder.html#tymethod.encode | |
233 | /// [`get_packet`]: ./trait.NAEncoder.html#tymethod.get_packet | |
234 | pub trait NAEncoder { | |
235 | /// Tries to negotiate input format. | |
236 | /// | |
237 | /// This function takes input encoding parameters and returns adjusted encoding parameters if input ones make sense. | |
238 | /// If input parameters are empty then the default parameters are returned. | |
239 | /// | |
240 | /// # Example | |
241 | /// ```ignore | |
242 | /// let enc_params = [ EncodeParameters {...}, ..., EncodeParameters::default() ]; | |
243 | /// let mut target_params = EncodeParameters::default(); | |
244 | /// for params in enc_params.iter() { | |
245 | /// if let Ok(dparams) = encoder.negotiate_format(params) { | |
246 | /// target_params = dparams; | |
247 | /// break; | |
248 | /// } | |
249 | /// } | |
250 | /// // since negotiate_format(EncodeParameters::default()) will return a valid format, target_params should be valid here | |
251 | /// let stream = encoder.init(stream_id, target_params)?; | |
252 | /// // convert input into format defined in target_params, feed to the encoder, ... | |
253 | /// ``` | |
254 | fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters>; | |
255 | /// Initialises the encoder. | |
256 | fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef>; | |
257 | /// Takes a single frame for encoding. | |
258 | fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()>; | |
259 | /// Returns encoded packet if available. | |
260 | fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>>; | |
261 | /// Tells encoder to encode all data it currently has. | |
262 | fn flush(&mut self) -> EncoderResult<()>; | |
263 | } | |
264 | ||
265 | /// Encoder information used during creating an encoder for requested codec. | |
266 | #[derive(Clone,Copy)] | |
267 | pub struct EncoderInfo { | |
268 | /// Short encoder name. | |
269 | pub name: &'static str, | |
270 | /// The function that creates an encoder instance. | |
271 | pub get_encoder: fn () -> Box<dyn NAEncoder + Send>, | |
272 | } | |
273 | ||
274 | /// Structure for registering known encoders. | |
275 | /// | |
276 | /// 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. | |
277 | #[derive(Default)] | |
278 | pub struct RegisteredEncoders { | |
279 | encs: Vec<EncoderInfo>, | |
280 | } | |
281 | ||
282 | impl RegisteredEncoders { | |
283 | /// Constructs a new instance of `RegisteredEncoders`. | |
284 | pub fn new() -> Self { | |
285 | Self { encs: Vec::new() } | |
286 | } | |
287 | /// Adds another encoder to the registry. | |
288 | pub fn add_encoder(&mut self, enc: EncoderInfo) { | |
289 | self.encs.push(enc); | |
290 | } | |
291 | /// Searches for the encoder for the provided name and returns a function for creating it on success. | |
292 | pub fn find_encoder(&self, name: &str) -> Option<fn () -> Box<dyn NAEncoder + Send>> { | |
293 | for &enc in self.encs.iter() { | |
294 | if enc.name == name { | |
295 | return Some(enc.get_encoder); | |
296 | } | |
297 | } | |
298 | None | |
299 | } | |
300 | /// Provides an iterator over currently registered encoders. | |
301 | pub fn iter(&self) -> std::slice::Iter<EncoderInfo> { | |
302 | self.encs.iter() | |
303 | } | |
304 | } | |
305 |