]>
Commit | Line | Data |
---|---|---|
7673d49a | 1 | //! Packets and decoded frames functionality. |
22cb00db | 2 | use std::cmp::max; |
a5ba48ac | 3 | //use std::collections::HashMap; |
83e603fa | 4 | use std::fmt; |
8057a7fd | 5 | pub use std::sync::Arc; |
4e8b4f31 | 6 | pub use crate::formats::*; |
1a967e6b | 7 | pub use crate::refs::*; |
94dbb551 | 8 | |
7673d49a | 9 | /// Audio stream information. |
5869fd63 | 10 | #[allow(dead_code)] |
66116504 | 11 | #[derive(Clone,Copy,PartialEq)] |
5869fd63 | 12 | pub struct NAAudioInfo { |
7673d49a | 13 | /// Sample rate. |
df159213 | 14 | pub sample_rate: u32, |
7673d49a | 15 | /// Number of channels. |
df159213 | 16 | pub channels: u8, |
7673d49a | 17 | /// Audio sample format. |
df159213 | 18 | pub format: NASoniton, |
7673d49a | 19 | /// Length of one audio block in samples. |
df159213 | 20 | pub block_len: usize, |
5869fd63 KS |
21 | } |
22 | ||
23 | impl NAAudioInfo { | |
7673d49a | 24 | /// Constructs a new `NAAudioInfo` instance. |
5869fd63 KS |
25 | pub fn new(sr: u32, ch: u8, fmt: NASoniton, bl: usize) -> Self { |
26 | NAAudioInfo { sample_rate: sr, channels: ch, format: fmt, block_len: bl } | |
27 | } | |
7673d49a | 28 | /// Returns audio sample rate. |
66116504 | 29 | pub fn get_sample_rate(&self) -> u32 { self.sample_rate } |
7673d49a | 30 | /// Returns the number of channels. |
66116504 | 31 | pub fn get_channels(&self) -> u8 { self.channels } |
7673d49a | 32 | /// Returns sample format. |
66116504 | 33 | pub fn get_format(&self) -> NASoniton { self.format } |
7673d49a | 34 | /// Returns one audio block duration in samples. |
66116504 | 35 | pub fn get_block_len(&self) -> usize { self.block_len } |
5869fd63 KS |
36 | } |
37 | ||
83e603fa KS |
38 | impl fmt::Display for NAAudioInfo { |
39 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
40 | write!(f, "{} Hz, {} ch", self.sample_rate, self.channels) | |
41 | } | |
42 | } | |
43 | ||
7673d49a | 44 | /// Video stream information. |
5869fd63 | 45 | #[allow(dead_code)] |
66116504 | 46 | #[derive(Clone,Copy,PartialEq)] |
5869fd63 | 47 | pub struct NAVideoInfo { |
7673d49a | 48 | /// Picture width. |
bf507799 | 49 | pub width: usize, |
7673d49a | 50 | /// Picture height. |
bf507799 | 51 | pub height: usize, |
7673d49a | 52 | /// Picture is stored downside up. |
bf507799 | 53 | pub flipped: bool, |
7673d49a | 54 | /// Picture pixel format. |
bf507799 | 55 | pub format: NAPixelFormaton, |
5869fd63 KS |
56 | } |
57 | ||
58 | impl NAVideoInfo { | |
7673d49a | 59 | /// Constructs a new `NAVideoInfo` instance. |
66116504 | 60 | pub fn new(w: usize, h: usize, flip: bool, fmt: NAPixelFormaton) -> Self { |
5869fd63 KS |
61 | NAVideoInfo { width: w, height: h, flipped: flip, format: fmt } |
62 | } | |
7673d49a | 63 | /// Returns picture width. |
66116504 | 64 | pub fn get_width(&self) -> usize { self.width as usize } |
7673d49a | 65 | /// Returns picture height. |
66116504 | 66 | pub fn get_height(&self) -> usize { self.height as usize } |
7673d49a | 67 | /// Returns picture orientation. |
66116504 | 68 | pub fn is_flipped(&self) -> bool { self.flipped } |
7673d49a | 69 | /// Returns picture pixel format. |
66116504 | 70 | pub fn get_format(&self) -> NAPixelFormaton { self.format } |
7673d49a | 71 | /// Sets new picture width. |
dd1b60e1 | 72 | pub fn set_width(&mut self, w: usize) { self.width = w; } |
7673d49a | 73 | /// Sets new picture height. |
dd1b60e1 | 74 | pub fn set_height(&mut self, h: usize) { self.height = h; } |
5869fd63 KS |
75 | } |
76 | ||
83e603fa KS |
77 | impl fmt::Display for NAVideoInfo { |
78 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
79 | write!(f, "{}x{}", self.width, self.height) | |
80 | } | |
81 | } | |
82 | ||
7673d49a | 83 | /// A list of possible stream information types. |
66116504 | 84 | #[derive(Clone,Copy,PartialEq)] |
5869fd63 | 85 | pub enum NACodecTypeInfo { |
7673d49a | 86 | /// No codec present. |
5869fd63 | 87 | None, |
7673d49a | 88 | /// Audio codec information. |
5869fd63 | 89 | Audio(NAAudioInfo), |
7673d49a | 90 | /// Video codec information. |
5869fd63 KS |
91 | Video(NAVideoInfo), |
92 | } | |
93 | ||
22cb00db | 94 | impl NACodecTypeInfo { |
7673d49a | 95 | /// Returns video stream information. |
22cb00db KS |
96 | pub fn get_video_info(&self) -> Option<NAVideoInfo> { |
97 | match *self { | |
98 | NACodecTypeInfo::Video(vinfo) => Some(vinfo), | |
99 | _ => None, | |
100 | } | |
101 | } | |
7673d49a | 102 | /// Returns audio stream information. |
22cb00db KS |
103 | pub fn get_audio_info(&self) -> Option<NAAudioInfo> { |
104 | match *self { | |
105 | NACodecTypeInfo::Audio(ainfo) => Some(ainfo), | |
106 | _ => None, | |
107 | } | |
108 | } | |
7673d49a | 109 | /// Reports whether the current stream is video stream. |
5076115b KS |
110 | pub fn is_video(&self) -> bool { |
111 | match *self { | |
112 | NACodecTypeInfo::Video(_) => true, | |
113 | _ => false, | |
114 | } | |
115 | } | |
7673d49a | 116 | /// Reports whether the current stream is audio stream. |
5076115b KS |
117 | pub fn is_audio(&self) -> bool { |
118 | match *self { | |
119 | NACodecTypeInfo::Audio(_) => true, | |
120 | _ => false, | |
121 | } | |
122 | } | |
22cb00db KS |
123 | } |
124 | ||
83e603fa KS |
125 | impl fmt::Display for NACodecTypeInfo { |
126 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
127 | let ret = match *self { | |
e243ceb4 | 128 | NACodecTypeInfo::None => "".to_string(), |
83e603fa KS |
129 | NACodecTypeInfo::Audio(fmt) => format!("{}", fmt), |
130 | NACodecTypeInfo::Video(fmt) => format!("{}", fmt), | |
131 | }; | |
132 | write!(f, "{}", ret) | |
133 | } | |
134 | } | |
135 | ||
7673d49a KS |
136 | /// Decoded video frame. |
137 | /// | |
138 | /// NihAV frames are stored in native type (8/16/32-bit elements) inside a single buffer. | |
139 | /// In case of image with several components those components are stored sequentially and can be accessed in the buffer starting at corresponding component offset. | |
22cb00db KS |
140 | #[derive(Clone)] |
141 | pub struct NAVideoBuffer<T> { | |
6c8e5c40 | 142 | info: NAVideoInfo, |
1a967e6b | 143 | data: NABufferRef<Vec<T>>, |
6c8e5c40 KS |
144 | offs: Vec<usize>, |
145 | strides: Vec<usize>, | |
22cb00db KS |
146 | } |
147 | ||
148 | impl<T: Clone> NAVideoBuffer<T> { | |
7673d49a | 149 | /// Returns the component offset (0 for all unavailable offsets). |
22cb00db KS |
150 | pub fn get_offset(&self, idx: usize) -> usize { |
151 | if idx >= self.offs.len() { 0 } | |
152 | else { self.offs[idx] } | |
153 | } | |
7673d49a | 154 | /// Returns picture info. |
22cb00db | 155 | pub fn get_info(&self) -> NAVideoInfo { self.info } |
7673d49a | 156 | /// Returns an immutable reference to the data. |
1a967e6b | 157 | pub fn get_data(&self) -> &Vec<T> { self.data.as_ref() } |
7673d49a | 158 | /// Returns a mutable reference to the data. |
1a967e6b | 159 | pub fn get_data_mut(&mut self) -> Option<&mut Vec<T>> { self.data.as_mut() } |
7673d49a | 160 | /// Returns the number of components in picture format. |
b914ee01 | 161 | pub fn get_num_components(&self) -> usize { self.offs.len() } |
7673d49a | 162 | /// Creates a copy of current `NAVideoBuffer`. |
22cb00db | 163 | pub fn copy_buffer(&mut self) -> Self { |
1a967e6b KS |
164 | let mut data: Vec<T> = Vec::with_capacity(self.data.len()); |
165 | data.clone_from(self.data.as_ref()); | |
22cb00db KS |
166 | let mut offs: Vec<usize> = Vec::with_capacity(self.offs.len()); |
167 | offs.clone_from(&self.offs); | |
6c8e5c40 KS |
168 | let mut strides: Vec<usize> = Vec::with_capacity(self.strides.len()); |
169 | strides.clone_from(&self.strides); | |
e243ceb4 | 170 | NAVideoBuffer { info: self.info, data: NABufferRef::new(data), offs, strides } |
22cb00db | 171 | } |
7673d49a | 172 | /// Returns stride (distance between subsequent lines) for the requested component. |
22cb00db | 173 | pub fn get_stride(&self, idx: usize) -> usize { |
6c8e5c40 KS |
174 | if idx >= self.strides.len() { return 0; } |
175 | self.strides[idx] | |
22cb00db | 176 | } |
7673d49a | 177 | /// Returns requested component dimensions. |
22cb00db KS |
178 | pub fn get_dimensions(&self, idx: usize) -> (usize, usize) { |
179 | get_plane_size(&self.info, idx) | |
180 | } | |
7673d49a | 181 | /// Converts current instance into buffer reference. |
3fc28ece KS |
182 | pub fn into_ref(self) -> NABufferRef<Self> { |
183 | NABufferRef::new(self) | |
184 | } | |
fcc25d82 KS |
185 | |
186 | fn print_contents(&self, datatype: &str) { | |
187 | println!("{} video buffer size {}", datatype, self.data.len()); | |
188 | println!(" format {}", self.info); | |
189 | print!(" offsets:"); | |
190 | for off in self.offs.iter() { | |
191 | print!(" {}", *off); | |
192 | } | |
193 | println!(); | |
194 | print!(" strides:"); | |
195 | for stride in self.strides.iter() { | |
196 | print!(" {}", *stride); | |
197 | } | |
198 | println!(); | |
199 | } | |
22cb00db KS |
200 | } |
201 | ||
7673d49a | 202 | /// A specialised type for reference-counted `NAVideoBuffer`. |
3fc28ece KS |
203 | pub type NAVideoBufferRef<T> = NABufferRef<NAVideoBuffer<T>>; |
204 | ||
7673d49a KS |
205 | /// Decoded audio frame. |
206 | /// | |
207 | /// NihAV frames are stored in native type (8/16/32-bit elements) inside a single buffer. | |
208 | /// In case of planar audio samples for each channel are stored sequentially and can be accessed in the buffer starting at corresponding channel offset. | |
22cb00db KS |
209 | #[derive(Clone)] |
210 | pub struct NAAudioBuffer<T> { | |
211 | info: NAAudioInfo, | |
1a967e6b | 212 | data: NABufferRef<Vec<T>>, |
22cb00db | 213 | offs: Vec<usize>, |
01e2d496 | 214 | stride: usize, |
98c6f2f0 | 215 | step: usize, |
22cb00db | 216 | chmap: NAChannelMap, |
5076115b | 217 | len: usize, |
22cb00db KS |
218 | } |
219 | ||
220 | impl<T: Clone> NAAudioBuffer<T> { | |
7673d49a | 221 | /// Returns the start position of requested channel data. |
22cb00db KS |
222 | pub fn get_offset(&self, idx: usize) -> usize { |
223 | if idx >= self.offs.len() { 0 } | |
224 | else { self.offs[idx] } | |
225 | } | |
7673d49a | 226 | /// Returns the distance between the start of one channel and the next one. |
01e2d496 | 227 | pub fn get_stride(&self) -> usize { self.stride } |
98c6f2f0 KS |
228 | /// Returns the distance between the samples in one channel. |
229 | pub fn get_step(&self) -> usize { self.step } | |
7673d49a | 230 | /// Returns audio format information. |
22cb00db | 231 | pub fn get_info(&self) -> NAAudioInfo { self.info } |
7673d49a | 232 | /// Returns channel map. |
8ee4352b | 233 | pub fn get_chmap(&self) -> &NAChannelMap { &self.chmap } |
7673d49a | 234 | /// Returns an immutable reference to the data. |
1a967e6b | 235 | pub fn get_data(&self) -> &Vec<T> { self.data.as_ref() } |
7673d49a | 236 | /// Returns a mutable reference to the data. |
1a967e6b | 237 | pub fn get_data_mut(&mut self) -> Option<&mut Vec<T>> { self.data.as_mut() } |
7673d49a | 238 | /// Clones current `NAAudioBuffer` into a new one. |
22cb00db | 239 | pub fn copy_buffer(&mut self) -> Self { |
1a967e6b KS |
240 | let mut data: Vec<T> = Vec::with_capacity(self.data.len()); |
241 | data.clone_from(self.data.as_ref()); | |
22cb00db KS |
242 | let mut offs: Vec<usize> = Vec::with_capacity(self.offs.len()); |
243 | offs.clone_from(&self.offs); | |
98c6f2f0 | 244 | NAAudioBuffer { info: self.info, data: NABufferRef::new(data), offs, chmap: self.get_chmap().clone(), len: self.len, stride: self.stride, step: self.step } |
22cb00db | 245 | } |
7673d49a | 246 | /// Return the length of frame in samples. |
5076115b | 247 | pub fn get_length(&self) -> usize { self.len } |
fcc25d82 KS |
248 | |
249 | fn print_contents(&self, datatype: &str) { | |
250 | println!("Audio buffer with {} data, stride {}, step {}", datatype, self.stride, self.step); | |
251 | println!(" format {}", self.info); | |
252 | println!(" channel map {}", self.chmap); | |
253 | print!(" offsets:"); | |
254 | for off in self.offs.iter() { | |
255 | print!(" {}", *off); | |
256 | } | |
257 | println!(); | |
258 | } | |
22cb00db KS |
259 | } |
260 | ||
87a1ebc3 | 261 | impl NAAudioBuffer<u8> { |
7673d49a | 262 | /// Constructs a new `NAAudioBuffer` instance. |
1a967e6b KS |
263 | pub fn new_from_buf(info: NAAudioInfo, data: NABufferRef<Vec<u8>>, chmap: NAChannelMap) -> Self { |
264 | let len = data.len(); | |
98c6f2f0 | 265 | NAAudioBuffer { info, data, chmap, offs: Vec::new(), len, stride: 0, step: 0 } |
87a1ebc3 KS |
266 | } |
267 | } | |
268 | ||
7673d49a | 269 | /// A list of possible decoded frame types. |
22cb00db KS |
270 | #[derive(Clone)] |
271 | pub enum NABufferType { | |
7673d49a | 272 | /// 8-bit video buffer. |
3fc28ece | 273 | Video (NAVideoBufferRef<u8>), |
7673d49a | 274 | /// 16-bit video buffer (i.e. every component or packed pixel fits into 16 bits). |
3fc28ece | 275 | Video16 (NAVideoBufferRef<u16>), |
7673d49a | 276 | /// 32-bit video buffer (i.e. every component or packed pixel fits into 32 bits). |
3fc28ece | 277 | Video32 (NAVideoBufferRef<u32>), |
7673d49a | 278 | /// Packed video buffer. |
3fc28ece | 279 | VideoPacked(NAVideoBufferRef<u8>), |
7673d49a | 280 | /// Audio buffer with 8-bit unsigned integer audio. |
22cb00db | 281 | AudioU8 (NAAudioBuffer<u8>), |
7673d49a | 282 | /// Audio buffer with 16-bit signed integer audio. |
22cb00db | 283 | AudioI16 (NAAudioBuffer<i16>), |
7673d49a | 284 | /// Audio buffer with 32-bit signed integer audio. |
87a1ebc3 | 285 | AudioI32 (NAAudioBuffer<i32>), |
7673d49a | 286 | /// Audio buffer with 32-bit floating point audio. |
22cb00db | 287 | AudioF32 (NAAudioBuffer<f32>), |
7673d49a | 288 | /// Packed audio buffer. |
22cb00db | 289 | AudioPacked(NAAudioBuffer<u8>), |
7673d49a | 290 | /// Buffer with generic data (e.g. subtitles). |
1a967e6b | 291 | Data (NABufferRef<Vec<u8>>), |
7673d49a | 292 | /// No data present. |
22cb00db KS |
293 | None, |
294 | } | |
295 | ||
296 | impl NABufferType { | |
7673d49a | 297 | /// Returns the offset to the requested component or channel. |
22cb00db KS |
298 | pub fn get_offset(&self, idx: usize) -> usize { |
299 | match *self { | |
300 | NABufferType::Video(ref vb) => vb.get_offset(idx), | |
301 | NABufferType::Video16(ref vb) => vb.get_offset(idx), | |
3bba1c4a | 302 | NABufferType::Video32(ref vb) => vb.get_offset(idx), |
22cb00db KS |
303 | NABufferType::VideoPacked(ref vb) => vb.get_offset(idx), |
304 | NABufferType::AudioU8(ref ab) => ab.get_offset(idx), | |
305 | NABufferType::AudioI16(ref ab) => ab.get_offset(idx), | |
fdf4b070 | 306 | NABufferType::AudioI32(ref ab) => ab.get_offset(idx), |
22cb00db KS |
307 | NABufferType::AudioF32(ref ab) => ab.get_offset(idx), |
308 | NABufferType::AudioPacked(ref ab) => ab.get_offset(idx), | |
309 | _ => 0, | |
310 | } | |
311 | } | |
7673d49a | 312 | /// Returns information for video frames. |
3bba1c4a KS |
313 | pub fn get_video_info(&self) -> Option<NAVideoInfo> { |
314 | match *self { | |
315 | NABufferType::Video(ref vb) => Some(vb.get_info()), | |
316 | NABufferType::Video16(ref vb) => Some(vb.get_info()), | |
317 | NABufferType::Video32(ref vb) => Some(vb.get_info()), | |
318 | NABufferType::VideoPacked(ref vb) => Some(vb.get_info()), | |
319 | _ => None, | |
320 | } | |
321 | } | |
7673d49a | 322 | /// Returns reference to 8-bit (or packed) video buffer. |
3fc28ece | 323 | pub fn get_vbuf(&self) -> Option<NAVideoBufferRef<u8>> { |
22cb00db KS |
324 | match *self { |
325 | NABufferType::Video(ref vb) => Some(vb.clone()), | |
87a1ebc3 KS |
326 | NABufferType::VideoPacked(ref vb) => Some(vb.clone()), |
327 | _ => None, | |
328 | } | |
329 | } | |
7673d49a | 330 | /// Returns reference to 16-bit video buffer. |
3fc28ece | 331 | pub fn get_vbuf16(&self) -> Option<NAVideoBufferRef<u16>> { |
87a1ebc3 KS |
332 | match *self { |
333 | NABufferType::Video16(ref vb) => Some(vb.clone()), | |
334 | _ => None, | |
335 | } | |
336 | } | |
7673d49a | 337 | /// Returns reference to 32-bit video buffer. |
3fc28ece | 338 | pub fn get_vbuf32(&self) -> Option<NAVideoBufferRef<u32>> { |
3bba1c4a KS |
339 | match *self { |
340 | NABufferType::Video32(ref vb) => Some(vb.clone()), | |
341 | _ => None, | |
342 | } | |
343 | } | |
7673d49a | 344 | /// Returns information for audio frames. |
049474a0 KS |
345 | pub fn get_audio_info(&self) -> Option<NAAudioInfo> { |
346 | match *self { | |
347 | NABufferType::AudioU8(ref ab) => Some(ab.get_info()), | |
348 | NABufferType::AudioI16(ref ab) => Some(ab.get_info()), | |
349 | NABufferType::AudioI32(ref ab) => Some(ab.get_info()), | |
350 | NABufferType::AudioF32(ref ab) => Some(ab.get_info()), | |
351 | NABufferType::AudioPacked(ref ab) => Some(ab.get_info()), | |
352 | _ => None, | |
353 | } | |
354 | } | |
7673d49a | 355 | /// Returns audio channel map. |
049474a0 KS |
356 | pub fn get_chmap(&self) -> Option<&NAChannelMap> { |
357 | match *self { | |
358 | NABufferType::AudioU8(ref ab) => Some(ab.get_chmap()), | |
359 | NABufferType::AudioI16(ref ab) => Some(ab.get_chmap()), | |
360 | NABufferType::AudioI32(ref ab) => Some(ab.get_chmap()), | |
361 | NABufferType::AudioF32(ref ab) => Some(ab.get_chmap()), | |
362 | NABufferType::AudioPacked(ref ab) => Some(ab.get_chmap()), | |
363 | _ => None, | |
364 | } | |
365 | } | |
7673d49a | 366 | /// Returns audio frame duration in samples. |
049474a0 KS |
367 | pub fn get_audio_length(&self) -> usize { |
368 | match *self { | |
369 | NABufferType::AudioU8(ref ab) => ab.get_length(), | |
370 | NABufferType::AudioI16(ref ab) => ab.get_length(), | |
371 | NABufferType::AudioI32(ref ab) => ab.get_length(), | |
372 | NABufferType::AudioF32(ref ab) => ab.get_length(), | |
373 | NABufferType::AudioPacked(ref ab) => ab.get_length(), | |
374 | _ => 0, | |
375 | } | |
376 | } | |
7673d49a | 377 | /// Returns the distance between starts of two channels. |
049474a0 KS |
378 | pub fn get_audio_stride(&self) -> usize { |
379 | match *self { | |
380 | NABufferType::AudioU8(ref ab) => ab.get_stride(), | |
381 | NABufferType::AudioI16(ref ab) => ab.get_stride(), | |
382 | NABufferType::AudioI32(ref ab) => ab.get_stride(), | |
383 | NABufferType::AudioF32(ref ab) => ab.get_stride(), | |
384 | NABufferType::AudioPacked(ref ab) => ab.get_stride(), | |
385 | _ => 0, | |
386 | } | |
387 | } | |
98c6f2f0 KS |
388 | /// Returns the distance between two samples in one channel. |
389 | pub fn get_audio_step(&self) -> usize { | |
390 | match *self { | |
391 | NABufferType::AudioU8(ref ab) => ab.get_step(), | |
392 | NABufferType::AudioI16(ref ab) => ab.get_step(), | |
393 | NABufferType::AudioI32(ref ab) => ab.get_step(), | |
394 | NABufferType::AudioF32(ref ab) => ab.get_step(), | |
395 | NABufferType::AudioPacked(ref ab) => ab.get_step(), | |
396 | _ => 0, | |
397 | } | |
398 | } | |
7673d49a | 399 | /// Returns reference to 8-bit (or packed) audio buffer. |
6e09a92e | 400 | pub fn get_abuf_u8(&self) -> Option<NAAudioBuffer<u8>> { |
87a1ebc3 KS |
401 | match *self { |
402 | NABufferType::AudioU8(ref ab) => Some(ab.clone()), | |
403 | NABufferType::AudioPacked(ref ab) => Some(ab.clone()), | |
404 | _ => None, | |
405 | } | |
406 | } | |
7673d49a | 407 | /// Returns reference to 16-bit audio buffer. |
6e09a92e | 408 | pub fn get_abuf_i16(&self) -> Option<NAAudioBuffer<i16>> { |
87a1ebc3 KS |
409 | match *self { |
410 | NABufferType::AudioI16(ref ab) => Some(ab.clone()), | |
411 | _ => None, | |
412 | } | |
413 | } | |
7673d49a | 414 | /// Returns reference to 32-bit integer audio buffer. |
6e09a92e | 415 | pub fn get_abuf_i32(&self) -> Option<NAAudioBuffer<i32>> { |
87a1ebc3 KS |
416 | match *self { |
417 | NABufferType::AudioI32(ref ab) => Some(ab.clone()), | |
418 | _ => None, | |
419 | } | |
420 | } | |
7673d49a | 421 | /// Returns reference to 32-bit floating point audio buffer. |
6e09a92e | 422 | pub fn get_abuf_f32(&self) -> Option<NAAudioBuffer<f32>> { |
87a1ebc3 KS |
423 | match *self { |
424 | NABufferType::AudioF32(ref ab) => Some(ab.clone()), | |
22cb00db KS |
425 | _ => None, |
426 | } | |
427 | } | |
fcc25d82 KS |
428 | /// Prints internal buffer layout. |
429 | pub fn print_buffer_metadata(&self) { | |
430 | match *self { | |
431 | NABufferType::Video(ref buf) => buf.print_contents("8-bit"), | |
432 | NABufferType::Video16(ref buf) => buf.print_contents("16-bit"), | |
433 | NABufferType::Video32(ref buf) => buf.print_contents("32-bit"), | |
434 | NABufferType::VideoPacked(ref buf) => buf.print_contents("packed"), | |
435 | NABufferType::AudioU8(ref buf) => buf.print_contents("8-bit unsigned integer"), | |
436 | NABufferType::AudioI16(ref buf) => buf.print_contents("16-bit integer"), | |
437 | NABufferType::AudioI32(ref buf) => buf.print_contents("32-bit integer"), | |
438 | NABufferType::AudioF32(ref buf) => buf.print_contents("32-bit float"), | |
439 | NABufferType::AudioPacked(ref buf) => buf.print_contents("packed"), | |
440 | NABufferType::Data(ref buf) => { println!("Data buffer, len = {}", buf.len()); }, | |
441 | NABufferType::None => { println!("No buffer"); }, | |
442 | }; | |
443 | } | |
22cb00db KS |
444 | } |
445 | ||
cd830591 | 446 | const NA_SIMPLE_VFRAME_COMPONENTS: usize = 4; |
7673d49a | 447 | /// Simplified decoded frame data. |
cd830591 | 448 | pub struct NASimpleVideoFrame<'a, T: Copy> { |
7673d49a | 449 | /// Widths of each picture component. |
cd830591 | 450 | pub width: [usize; NA_SIMPLE_VFRAME_COMPONENTS], |
7673d49a | 451 | /// Heights of each picture component. |
cd830591 | 452 | pub height: [usize; NA_SIMPLE_VFRAME_COMPONENTS], |
7673d49a | 453 | /// Orientation (upside-down or downside-up) flag. |
cd830591 | 454 | pub flip: bool, |
7673d49a | 455 | /// Strides for each component. |
cd830591 | 456 | pub stride: [usize; NA_SIMPLE_VFRAME_COMPONENTS], |
7673d49a | 457 | /// Start of each component. |
cd830591 | 458 | pub offset: [usize; NA_SIMPLE_VFRAME_COMPONENTS], |
7673d49a | 459 | /// Number of components. |
cd830591 | 460 | pub components: usize, |
7673d49a | 461 | /// Pointer to the picture pixel data. |
dc45d8ce | 462 | pub data: &'a mut [T], |
cd830591 KS |
463 | } |
464 | ||
465 | impl<'a, T:Copy> NASimpleVideoFrame<'a, T> { | |
7673d49a | 466 | /// Constructs a new instance of `NASimpleVideoFrame` from `NAVideoBuffer`. |
cd830591 KS |
467 | pub fn from_video_buf(vbuf: &'a mut NAVideoBuffer<T>) -> Option<Self> { |
468 | let vinfo = vbuf.get_info(); | |
469 | let components = vinfo.format.components as usize; | |
470 | if components > NA_SIMPLE_VFRAME_COMPONENTS { | |
471 | return None; | |
472 | } | |
473 | let mut w: [usize; NA_SIMPLE_VFRAME_COMPONENTS] = [0; NA_SIMPLE_VFRAME_COMPONENTS]; | |
474 | let mut h: [usize; NA_SIMPLE_VFRAME_COMPONENTS] = [0; NA_SIMPLE_VFRAME_COMPONENTS]; | |
475 | let mut s: [usize; NA_SIMPLE_VFRAME_COMPONENTS] = [0; NA_SIMPLE_VFRAME_COMPONENTS]; | |
476 | let mut o: [usize; NA_SIMPLE_VFRAME_COMPONENTS] = [0; NA_SIMPLE_VFRAME_COMPONENTS]; | |
477 | for comp in 0..components { | |
478 | let (width, height) = vbuf.get_dimensions(comp); | |
479 | w[comp] = width; | |
480 | h[comp] = height; | |
481 | s[comp] = vbuf.get_stride(comp); | |
482 | o[comp] = vbuf.get_offset(comp); | |
483 | } | |
484 | let flip = vinfo.flipped; | |
485 | Some(NASimpleVideoFrame { | |
486 | width: w, | |
487 | height: h, | |
488 | flip, | |
489 | stride: s, | |
490 | offset: o, | |
491 | components, | |
dc45d8ce | 492 | data: vbuf.data.as_mut_slice(), |
cd830591 KS |
493 | }) |
494 | } | |
495 | } | |
496 | ||
7673d49a | 497 | /// A list of possible frame allocator errors. |
22cb00db KS |
498 | #[derive(Debug,Clone,Copy,PartialEq)] |
499 | pub enum AllocatorError { | |
7673d49a | 500 | /// Requested picture dimensions are too large. |
22cb00db | 501 | TooLargeDimensions, |
7673d49a | 502 | /// Invalid input format. |
22cb00db KS |
503 | FormatError, |
504 | } | |
505 | ||
7673d49a KS |
506 | /// Constructs a new video buffer with requested format. |
507 | /// | |
508 | /// `align` is power of two alignment for image. E.g. the value of 5 means that frame dimensions will be padded to be multiple of 32. | |
22cb00db KS |
509 | pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result<NABufferType, AllocatorError> { |
510 | let fmt = &vinfo.format; | |
511 | let mut new_size: usize = 0; | |
6c8e5c40 KS |
512 | let mut offs: Vec<usize> = Vec::new(); |
513 | let mut strides: Vec<usize> = Vec::new(); | |
22cb00db KS |
514 | |
515 | for i in 0..fmt.get_num_comp() { | |
516 | if fmt.get_chromaton(i) == None { return Err(AllocatorError::FormatError); } | |
517 | } | |
518 | ||
519 | let align_mod = ((1 << align) as usize) - 1; | |
520 | let width = ((vinfo.width as usize) + align_mod) & !align_mod; | |
521 | let height = ((vinfo.height as usize) + align_mod) & !align_mod; | |
522 | let mut max_depth = 0; | |
523 | let mut all_packed = true; | |
3bba1c4a | 524 | let mut all_bytealigned = true; |
22cb00db | 525 | for i in 0..fmt.get_num_comp() { |
6c8e5c40 | 526 | let ochr = fmt.get_chromaton(i); |
e243ceb4 | 527 | if ochr.is_none() { continue; } |
6c8e5c40 | 528 | let chr = ochr.unwrap(); |
22cb00db KS |
529 | if !chr.is_packed() { |
530 | all_packed = false; | |
3bba1c4a KS |
531 | } else if ((chr.get_shift() + chr.get_depth()) & 7) != 0 { |
532 | all_bytealigned = false; | |
22cb00db KS |
533 | } |
534 | max_depth = max(max_depth, chr.get_depth()); | |
535 | } | |
3bba1c4a KS |
536 | let unfit_elem_size = match fmt.get_elem_size() { |
537 | 2 | 4 => false, | |
538 | _ => true, | |
539 | }; | |
22cb00db KS |
540 | |
541 | //todo semi-packed like NV12 | |
bc6aac3d KS |
542 | if fmt.is_paletted() { |
543 | //todo various-sized palettes? | |
6c8e5c40 KS |
544 | let stride = vinfo.get_format().get_chromaton(0).unwrap().get_linesize(width); |
545 | let pic_sz = stride.checked_mul(height); | |
bc6aac3d KS |
546 | if pic_sz == None { return Err(AllocatorError::TooLargeDimensions); } |
547 | let pal_size = 256 * (fmt.get_elem_size() as usize); | |
548 | let new_size = pic_sz.unwrap().checked_add(pal_size); | |
549 | if new_size == None { return Err(AllocatorError::TooLargeDimensions); } | |
550 | offs.push(0); | |
6c8e5c40 KS |
551 | offs.push(stride * height); |
552 | strides.push(stride); | |
e243ceb4 KS |
553 | let data: Vec<u8> = vec![0; new_size.unwrap()]; |
554 | let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; | |
3fc28ece | 555 | Ok(NABufferType::Video(buf.into_ref())) |
bc6aac3d | 556 | } else if !all_packed { |
22cb00db | 557 | for i in 0..fmt.get_num_comp() { |
6c8e5c40 | 558 | let ochr = fmt.get_chromaton(i); |
e243ceb4 | 559 | if ochr.is_none() { continue; } |
6c8e5c40 | 560 | let chr = ochr.unwrap(); |
74afc7de | 561 | offs.push(new_size as usize); |
6c8e5c40 | 562 | let stride = chr.get_linesize(width); |
22cb00db | 563 | let cur_h = chr.get_height(height); |
6c8e5c40 | 564 | let cur_sz = stride.checked_mul(cur_h); |
22cb00db KS |
565 | if cur_sz == None { return Err(AllocatorError::TooLargeDimensions); } |
566 | let new_sz = new_size.checked_add(cur_sz.unwrap()); | |
567 | if new_sz == None { return Err(AllocatorError::TooLargeDimensions); } | |
568 | new_size = new_sz.unwrap(); | |
6c8e5c40 | 569 | strides.push(stride); |
22cb00db KS |
570 | } |
571 | if max_depth <= 8 { | |
e243ceb4 KS |
572 | let data: Vec<u8> = vec![0; new_size]; |
573 | let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; | |
3fc28ece | 574 | Ok(NABufferType::Video(buf.into_ref())) |
3bba1c4a | 575 | } else if max_depth <= 16 { |
e243ceb4 KS |
576 | let data: Vec<u16> = vec![0; new_size]; |
577 | let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; | |
3fc28ece | 578 | Ok(NABufferType::Video16(buf.into_ref())) |
3bba1c4a | 579 | } else { |
e243ceb4 KS |
580 | let data: Vec<u32> = vec![0; new_size]; |
581 | let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; | |
3fc28ece | 582 | Ok(NABufferType::Video32(buf.into_ref())) |
22cb00db | 583 | } |
3bba1c4a | 584 | } else if all_bytealigned || unfit_elem_size { |
22cb00db KS |
585 | let elem_sz = fmt.get_elem_size(); |
586 | let line_sz = width.checked_mul(elem_sz as usize); | |
587 | if line_sz == None { return Err(AllocatorError::TooLargeDimensions); } | |
588 | let new_sz = line_sz.unwrap().checked_mul(height); | |
589 | if new_sz == None { return Err(AllocatorError::TooLargeDimensions); } | |
590 | new_size = new_sz.unwrap(); | |
e243ceb4 | 591 | let data: Vec<u8> = vec![0; new_size]; |
6c8e5c40 | 592 | strides.push(line_sz.unwrap()); |
e243ceb4 | 593 | let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; |
3fc28ece | 594 | Ok(NABufferType::VideoPacked(buf.into_ref())) |
3bba1c4a KS |
595 | } else { |
596 | let elem_sz = fmt.get_elem_size(); | |
597 | let new_sz = width.checked_mul(height); | |
598 | if new_sz == None { return Err(AllocatorError::TooLargeDimensions); } | |
599 | new_size = new_sz.unwrap(); | |
600 | match elem_sz { | |
601 | 2 => { | |
e243ceb4 | 602 | let data: Vec<u16> = vec![0; new_size]; |
3bba1c4a | 603 | strides.push(width); |
e243ceb4 | 604 | let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; |
3fc28ece | 605 | Ok(NABufferType::Video16(buf.into_ref())) |
3bba1c4a KS |
606 | }, |
607 | 4 => { | |
e243ceb4 | 608 | let data: Vec<u32> = vec![0; new_size]; |
3bba1c4a | 609 | strides.push(width); |
e243ceb4 | 610 | let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; |
3fc28ece | 611 | Ok(NABufferType::Video32(buf.into_ref())) |
3bba1c4a KS |
612 | }, |
613 | _ => unreachable!(), | |
614 | } | |
22cb00db KS |
615 | } |
616 | } | |
617 | ||
7673d49a | 618 | /// Constructs a new audio buffer for the requested format and length. |
e243ceb4 | 619 | #[allow(clippy::collapsible_if)] |
22cb00db KS |
620 | pub fn alloc_audio_buffer(ainfo: NAAudioInfo, nsamples: usize, chmap: NAChannelMap) -> Result<NABufferType, AllocatorError> { |
621 | let mut offs: Vec<usize> = Vec::new(); | |
98c6f2f0 | 622 | if ainfo.format.is_planar() || ((ainfo.format.get_bits() % 8) == 0) { |
22cb00db KS |
623 | let len = nsamples.checked_mul(ainfo.channels as usize); |
624 | if len == None { return Err(AllocatorError::TooLargeDimensions); } | |
625 | let length = len.unwrap(); | |
98c6f2f0 KS |
626 | let stride; |
627 | let step; | |
628 | if ainfo.format.is_planar() { | |
629 | stride = nsamples; | |
630 | step = 1; | |
631 | for i in 0..ainfo.channels { | |
632 | offs.push((i as usize) * stride); | |
633 | } | |
634 | } else { | |
635 | stride = 1; | |
636 | step = ainfo.channels as usize; | |
637 | for i in 0..ainfo.channels { | |
638 | offs.push(i as usize); | |
639 | } | |
22cb00db KS |
640 | } |
641 | if ainfo.format.is_float() { | |
642 | if ainfo.format.get_bits() == 32 { | |
e243ceb4 | 643 | let data: Vec<f32> = vec![0.0; length]; |
98c6f2f0 | 644 | let buf: NAAudioBuffer<f32> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples, stride, step }; |
22cb00db KS |
645 | Ok(NABufferType::AudioF32(buf)) |
646 | } else { | |
647 | Err(AllocatorError::TooLargeDimensions) | |
648 | } | |
649 | } else { | |
650 | if ainfo.format.get_bits() == 8 && !ainfo.format.is_signed() { | |
e243ceb4 | 651 | let data: Vec<u8> = vec![0; length]; |
98c6f2f0 | 652 | let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples, stride, step }; |
22cb00db KS |
653 | Ok(NABufferType::AudioU8(buf)) |
654 | } else if ainfo.format.get_bits() == 16 && ainfo.format.is_signed() { | |
e243ceb4 | 655 | let data: Vec<i16> = vec![0; length]; |
98c6f2f0 | 656 | let buf: NAAudioBuffer<i16> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples, stride, step }; |
22cb00db KS |
657 | Ok(NABufferType::AudioI16(buf)) |
658 | } else { | |
659 | Err(AllocatorError::TooLargeDimensions) | |
660 | } | |
661 | } | |
662 | } else { | |
663 | let len = nsamples.checked_mul(ainfo.channels as usize); | |
664 | if len == None { return Err(AllocatorError::TooLargeDimensions); } | |
665 | let length = ainfo.format.get_audio_size(len.unwrap() as u64); | |
e243ceb4 | 666 | let data: Vec<u8> = vec![0; length]; |
98c6f2f0 | 667 | let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples, stride: 0, step: 0 }; |
1a151e53 | 668 | Ok(NABufferType::AudioPacked(buf)) |
22cb00db KS |
669 | } |
670 | } | |
671 | ||
7673d49a | 672 | /// Constructs a new buffer for generic data. |
22cb00db | 673 | pub fn alloc_data_buffer(size: usize) -> Result<NABufferType, AllocatorError> { |
e243ceb4 | 674 | let data: Vec<u8> = vec![0; size]; |
1a967e6b | 675 | let buf: NABufferRef<Vec<u8>> = NABufferRef::new(data); |
22cb00db KS |
676 | Ok(NABufferType::Data(buf)) |
677 | } | |
678 | ||
7673d49a | 679 | /// Creates a clone of current buffer. |
22cb00db KS |
680 | pub fn copy_buffer(buf: NABufferType) -> NABufferType { |
681 | buf.clone() | |
682 | } | |
683 | ||
7673d49a KS |
684 | /// Video frame pool. |
685 | /// | |
686 | /// This structure allows codec to effectively reuse old frames instead of allocating and de-allocating frames every time. | |
687 | /// Caller can also reserve some frames for its own purposes e.g. display queue. | |
01613464 KS |
688 | pub struct NAVideoBufferPool<T:Copy> { |
689 | pool: Vec<NAVideoBufferRef<T>>, | |
1a967e6b | 690 | max_len: usize, |
01613464 | 691 | add_len: usize, |
1a967e6b KS |
692 | } |
693 | ||
01613464 | 694 | impl<T:Copy> NAVideoBufferPool<T> { |
7673d49a | 695 | /// Constructs a new `NAVideoBufferPool` instance. |
1a967e6b KS |
696 | pub fn new(max_len: usize) -> Self { |
697 | Self { | |
698 | pool: Vec::with_capacity(max_len), | |
699 | max_len, | |
01613464 | 700 | add_len: 0, |
1a967e6b KS |
701 | } |
702 | } | |
7673d49a | 703 | /// Sets the number of buffers reserved for the user. |
01613464 KS |
704 | pub fn set_dec_bufs(&mut self, add_len: usize) { |
705 | self.add_len = add_len; | |
706 | } | |
7673d49a | 707 | /// Returns an unused buffer from the pool. |
01613464 KS |
708 | pub fn get_free(&mut self) -> Option<NAVideoBufferRef<T>> { |
709 | for e in self.pool.iter() { | |
710 | if e.get_num_refs() == 1 { | |
711 | return Some(e.clone()); | |
712 | } | |
713 | } | |
714 | None | |
715 | } | |
7673d49a | 716 | /// Clones provided frame data into a free pool frame. |
01613464 | 717 | pub fn get_copy(&mut self, rbuf: &NAVideoBufferRef<T>) -> Option<NAVideoBufferRef<T>> { |
e243ceb4 | 718 | let mut dbuf = self.get_free()?; |
01613464 KS |
719 | dbuf.data.copy_from_slice(&rbuf.data); |
720 | Some(dbuf) | |
721 | } | |
7673d49a | 722 | /// Clears the pool from all frames. |
01613464 KS |
723 | pub fn reset(&mut self) { |
724 | self.pool.truncate(0); | |
725 | } | |
726 | } | |
727 | ||
728 | impl NAVideoBufferPool<u8> { | |
7673d49a KS |
729 | /// Allocates the target amount of video frames using [`alloc_video_buffer`]. |
730 | /// | |
731 | /// [`alloc_video_buffer`]: ./fn.alloc_video_buffer.html | |
1a967e6b | 732 | pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> { |
01613464 | 733 | let nbufs = self.max_len + self.add_len - self.pool.len(); |
1a967e6b | 734 | for _ in 0..nbufs { |
e243ceb4 | 735 | let vbuf = alloc_video_buffer(vinfo, align)?; |
01613464 KS |
736 | if let NABufferType::Video(buf) = vbuf { |
737 | self.pool.push(buf); | |
738 | } else if let NABufferType::VideoPacked(buf) = vbuf { | |
739 | self.pool.push(buf); | |
740 | } else { | |
741 | return Err(AllocatorError::FormatError); | |
742 | } | |
1a967e6b KS |
743 | } |
744 | Ok(()) | |
745 | } | |
01613464 KS |
746 | } |
747 | ||
748 | impl NAVideoBufferPool<u16> { | |
7673d49a KS |
749 | /// Allocates the target amount of video frames using [`alloc_video_buffer`]. |
750 | /// | |
751 | /// [`alloc_video_buffer`]: ./fn.alloc_video_buffer.html | |
01613464 KS |
752 | pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> { |
753 | let nbufs = self.max_len + self.add_len - self.pool.len(); | |
1a967e6b | 754 | for _ in 0..nbufs { |
e243ceb4 | 755 | let vbuf = alloc_video_buffer(vinfo, align)?; |
01613464 KS |
756 | if let NABufferType::Video16(buf) = vbuf { |
757 | self.pool.push(buf); | |
758 | } else { | |
759 | return Err(AllocatorError::FormatError); | |
760 | } | |
1a967e6b KS |
761 | } |
762 | Ok(()) | |
763 | } | |
01613464 KS |
764 | } |
765 | ||
766 | impl NAVideoBufferPool<u32> { | |
7673d49a KS |
767 | /// Allocates the target amount of video frames using [`alloc_video_buffer`]. |
768 | /// | |
769 | /// [`alloc_video_buffer`]: ./fn.alloc_video_buffer.html | |
01613464 KS |
770 | pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> { |
771 | let nbufs = self.max_len + self.add_len - self.pool.len(); | |
772 | for _ in 0..nbufs { | |
e243ceb4 | 773 | let vbuf = alloc_video_buffer(vinfo, align)?; |
01613464 KS |
774 | if let NABufferType::Video32(buf) = vbuf { |
775 | self.pool.push(buf); | |
776 | } else { | |
777 | return Err(AllocatorError::FormatError); | |
1a967e6b KS |
778 | } |
779 | } | |
01613464 | 780 | Ok(()) |
1a967e6b KS |
781 | } |
782 | } | |
783 | ||
7673d49a | 784 | /// Information about codec contained in a stream. |
5869fd63 | 785 | #[allow(dead_code)] |
8869d452 KS |
786 | #[derive(Clone)] |
787 | pub struct NACodecInfo { | |
ccae5343 | 788 | name: &'static str, |
5869fd63 | 789 | properties: NACodecTypeInfo, |
2422d969 | 790 | extradata: Option<Arc<Vec<u8>>>, |
5869fd63 KS |
791 | } |
792 | ||
7673d49a | 793 | /// A specialised type for reference-counted `NACodecInfo`. |
2422d969 KS |
794 | pub type NACodecInfoRef = Arc<NACodecInfo>; |
795 | ||
8869d452 | 796 | impl NACodecInfo { |
7673d49a | 797 | /// Constructs a new instance of `NACodecInfo`. |
ccae5343 | 798 | pub fn new(name: &'static str, p: NACodecTypeInfo, edata: Option<Vec<u8>>) -> Self { |
8869d452 KS |
799 | let extradata = match edata { |
800 | None => None, | |
2422d969 | 801 | Some(vec) => Some(Arc::new(vec)), |
8869d452 | 802 | }; |
e243ceb4 | 803 | NACodecInfo { name, properties: p, extradata } |
8869d452 | 804 | } |
7673d49a | 805 | /// Constructs a new reference-counted instance of `NACodecInfo`. |
2422d969 | 806 | pub fn new_ref(name: &'static str, p: NACodecTypeInfo, edata: Option<Arc<Vec<u8>>>) -> Self { |
e243ceb4 | 807 | NACodecInfo { name, properties: p, extradata: edata } |
66116504 | 808 | } |
7673d49a | 809 | /// Converts current instance into a reference-counted one. |
2422d969 | 810 | pub fn into_ref(self) -> NACodecInfoRef { Arc::new(self) } |
7673d49a | 811 | /// Returns codec information. |
8869d452 | 812 | pub fn get_properties(&self) -> NACodecTypeInfo { self.properties } |
7673d49a | 813 | /// Returns additional initialisation data required by the codec. |
2422d969 | 814 | pub fn get_extradata(&self) -> Option<Arc<Vec<u8>>> { |
8869d452 KS |
815 | if let Some(ref vec) = self.extradata { return Some(vec.clone()); } |
816 | None | |
5869fd63 | 817 | } |
7673d49a | 818 | /// Returns codec name. |
66116504 | 819 | pub fn get_name(&self) -> &'static str { self.name } |
7673d49a | 820 | /// Reports whether it is a video codec. |
66116504 KS |
821 | pub fn is_video(&self) -> bool { |
822 | if let NACodecTypeInfo::Video(_) = self.properties { return true; } | |
823 | false | |
824 | } | |
7673d49a | 825 | /// Reports whether it is an audio codec. |
66116504 KS |
826 | pub fn is_audio(&self) -> bool { |
827 | if let NACodecTypeInfo::Audio(_) = self.properties { return true; } | |
828 | false | |
829 | } | |
7673d49a | 830 | /// Constructs a new empty reference-counted instance of `NACodecInfo`. |
2422d969 KS |
831 | pub fn new_dummy() -> Arc<Self> { |
832 | Arc::new(DUMMY_CODEC_INFO) | |
5076115b | 833 | } |
7673d49a | 834 | /// Updates codec infomation. |
2422d969 KS |
835 | pub fn replace_info(&self, p: NACodecTypeInfo) -> Arc<Self> { |
836 | Arc::new(NACodecInfo { name: self.name, properties: p, extradata: self.extradata.clone() }) | |
5076115b | 837 | } |
66116504 KS |
838 | } |
839 | ||
241e56f1 KS |
840 | impl Default for NACodecInfo { |
841 | fn default() -> Self { DUMMY_CODEC_INFO } | |
842 | } | |
843 | ||
66116504 KS |
844 | impl fmt::Display for NACodecInfo { |
845 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
846 | let edata = match self.extradata.clone() { | |
e243ceb4 | 847 | None => "no extradata".to_string(), |
66116504 KS |
848 | Some(v) => format!("{} byte(s) of extradata", v.len()), |
849 | }; | |
850 | write!(f, "{}: {} {}", self.name, self.properties, edata) | |
851 | } | |
852 | } | |
853 | ||
7673d49a | 854 | /// Default empty codec information. |
66116504 KS |
855 | pub const DUMMY_CODEC_INFO: NACodecInfo = NACodecInfo { |
856 | name: "none", | |
857 | properties: NACodecTypeInfo::None, | |
858 | extradata: None }; | |
859 | ||
7673d49a | 860 | /// A list of accepted option values. |
66116504 KS |
861 | #[derive(Debug,Clone)] |
862 | pub enum NAValue { | |
7673d49a | 863 | /// Empty value. |
5869fd63 | 864 | None, |
7673d49a | 865 | /// Integer value. |
5869fd63 | 866 | Int(i32), |
7673d49a | 867 | /// Long integer value. |
5869fd63 | 868 | Long(i64), |
7673d49a | 869 | /// String value. |
5869fd63 | 870 | String(String), |
7673d49a | 871 | /// Binary data value. |
2422d969 | 872 | Data(Arc<Vec<u8>>), |
5869fd63 KS |
873 | } |
874 | ||
7673d49a | 875 | /// A list of recognized frame types. |
88c03b61 KS |
876 | #[derive(Debug,Clone,Copy,PartialEq)] |
877 | #[allow(dead_code)] | |
878 | pub enum FrameType { | |
7673d49a | 879 | /// Intra frame type. |
88c03b61 | 880 | I, |
7673d49a | 881 | /// Inter frame type. |
88c03b61 | 882 | P, |
7673d49a | 883 | /// Bidirectionally predicted frame. |
88c03b61 | 884 | B, |
7673d49a KS |
885 | /// Skip frame. |
886 | /// | |
887 | /// When such frame is encountered then last frame should be used again if it is needed. | |
bc6aac3d | 888 | Skip, |
7673d49a | 889 | /// Some other frame type. |
88c03b61 KS |
890 | Other, |
891 | } | |
892 | ||
893 | impl fmt::Display for FrameType { | |
894 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
895 | match *self { | |
896 | FrameType::I => write!(f, "I"), | |
897 | FrameType::P => write!(f, "P"), | |
898 | FrameType::B => write!(f, "B"), | |
bc6aac3d | 899 | FrameType::Skip => write!(f, "skip"), |
88c03b61 KS |
900 | FrameType::Other => write!(f, "x"), |
901 | } | |
902 | } | |
903 | } | |
904 | ||
7673d49a | 905 | /// Timestamp information. |
e189501e KS |
906 | #[derive(Debug,Clone,Copy)] |
907 | pub struct NATimeInfo { | |
bf507799 KS |
908 | /// Presentation timestamp. |
909 | pub pts: Option<u64>, | |
910 | /// Decode timestamp. | |
911 | pub dts: Option<u64>, | |
912 | /// Duration (in timebase units). | |
913 | pub duration: Option<u64>, | |
914 | /// Timebase numerator. | |
915 | pub tb_num: u32, | |
916 | /// Timebase denominator. | |
917 | pub tb_den: u32, | |
e189501e KS |
918 | } |
919 | ||
920 | impl NATimeInfo { | |
7673d49a | 921 | /// Constructs a new `NATimeInfo` instance. |
e189501e | 922 | pub fn new(pts: Option<u64>, dts: Option<u64>, duration: Option<u64>, tb_num: u32, tb_den: u32) -> Self { |
e243ceb4 | 923 | NATimeInfo { pts, dts, duration, tb_num, tb_den } |
e189501e | 924 | } |
7673d49a | 925 | /// Returns presentation timestamp. |
e189501e | 926 | pub fn get_pts(&self) -> Option<u64> { self.pts } |
7673d49a | 927 | /// Returns decoding timestamp. |
e189501e | 928 | pub fn get_dts(&self) -> Option<u64> { self.dts } |
7673d49a | 929 | /// Returns duration. |
e189501e | 930 | pub fn get_duration(&self) -> Option<u64> { self.duration } |
7673d49a | 931 | /// Sets new presentation timestamp. |
e189501e | 932 | pub fn set_pts(&mut self, pts: Option<u64>) { self.pts = pts; } |
7673d49a | 933 | /// Sets new decoding timestamp. |
e189501e | 934 | pub fn set_dts(&mut self, dts: Option<u64>) { self.dts = dts; } |
7673d49a | 935 | /// Sets new duration. |
e189501e | 936 | pub fn set_duration(&mut self, dur: Option<u64>) { self.duration = dur; } |
266da7b9 | 937 | |
7673d49a | 938 | /// Converts time in given scale into timestamp in given base. |
266da7b9 KS |
939 | pub fn time_to_ts(time: u64, base: u64, tb_num: u32, tb_den: u32) -> u64 { |
940 | let tb_num = tb_num as u64; | |
941 | let tb_den = tb_den as u64; | |
942 | let tmp = time.checked_mul(tb_num); | |
943 | if let Some(tmp) = tmp { | |
944 | tmp / base / tb_den | |
945 | } else { | |
946 | let tmp = time.checked_mul(tb_num); | |
947 | if let Some(tmp) = tmp { | |
948 | tmp / base / tb_den | |
949 | } else { | |
950 | let coarse = time / base; | |
951 | let tmp = coarse.checked_mul(tb_num); | |
952 | if let Some(tmp) = tmp { | |
953 | tmp / tb_den | |
954 | } else { | |
955 | (coarse / tb_den) * tb_num | |
956 | } | |
957 | } | |
958 | } | |
959 | } | |
7673d49a | 960 | /// Converts timestamp in given base into time in given scale. |
a65bdeac KS |
961 | pub fn ts_to_time(ts: u64, base: u64, tb_num: u32, tb_den: u32) -> u64 { |
962 | let tb_num = tb_num as u64; | |
963 | let tb_den = tb_den as u64; | |
964 | let tmp = ts.checked_mul(base); | |
965 | if let Some(tmp) = tmp { | |
966 | let tmp2 = tmp.checked_mul(tb_num); | |
967 | if let Some(tmp2) = tmp2 { | |
968 | tmp2 / tb_den | |
969 | } else { | |
970 | (tmp / tb_den) * tb_num | |
971 | } | |
972 | } else { | |
973 | let tmp = ts.checked_mul(tb_num); | |
974 | if let Some(tmp) = tmp { | |
975 | (tmp / tb_den) * base | |
976 | } else { | |
977 | (ts / tb_den) * base * tb_num | |
978 | } | |
979 | } | |
980 | } | |
e189501e KS |
981 | } |
982 | ||
7673d49a | 983 | /// Decoded frame information. |
e189501e KS |
984 | #[allow(dead_code)] |
985 | #[derive(Clone)] | |
986 | pub struct NAFrame { | |
bf507799 KS |
987 | /// Frame timestamp. |
988 | pub ts: NATimeInfo, | |
989 | /// Frame ID. | |
990 | pub id: i64, | |
991 | buffer: NABufferType, | |
992 | info: NACodecInfoRef, | |
993 | /// Frame type. | |
994 | pub frame_type: FrameType, | |
995 | /// Keyframe flag. | |
996 | pub key: bool, | |
a5ba48ac | 997 | // options: HashMap<String, NAValue>, |
66116504 KS |
998 | } |
999 | ||
7673d49a | 1000 | /// A specialised type for reference-counted `NAFrame`. |
171860fc | 1001 | pub type NAFrameRef = Arc<NAFrame>; |
ebd71c92 | 1002 | |
66116504 KS |
1003 | fn get_plane_size(info: &NAVideoInfo, idx: usize) -> (usize, usize) { |
1004 | let chromaton = info.get_format().get_chromaton(idx); | |
e243ceb4 | 1005 | if chromaton.is_none() { return (0, 0); } |
66116504 KS |
1006 | let (hs, vs) = chromaton.unwrap().get_subsampling(); |
1007 | let w = (info.get_width() + ((1 << hs) - 1)) >> hs; | |
1008 | let h = (info.get_height() + ((1 << vs) - 1)) >> vs; | |
1009 | (w, h) | |
1010 | } | |
1011 | ||
1012 | impl NAFrame { | |
7673d49a | 1013 | /// Constructs a new `NAFrame` instance. |
e189501e | 1014 | pub fn new(ts: NATimeInfo, |
88c03b61 KS |
1015 | ftype: FrameType, |
1016 | keyframe: bool, | |
2422d969 | 1017 | info: NACodecInfoRef, |
a5ba48ac | 1018 | /*options: HashMap<String, NAValue>,*/ |
22cb00db | 1019 | buffer: NABufferType) -> Self { |
a5ba48ac | 1020 | NAFrame { ts, id: 0, buffer, info, frame_type: ftype, key: keyframe/*, options*/ } |
ebd71c92 | 1021 | } |
7673d49a | 1022 | /// Returns frame format information. |
2422d969 | 1023 | pub fn get_info(&self) -> NACodecInfoRef { self.info.clone() } |
7673d49a | 1024 | /// Returns frame type. |
bf507799 | 1025 | pub fn get_frame_type(&self) -> FrameType { self.frame_type } |
7673d49a | 1026 | /// Reports whether the frame is a keyframe. |
88c03b61 | 1027 | pub fn is_keyframe(&self) -> bool { self.key } |
7673d49a | 1028 | /// Sets new frame type. |
bf507799 | 1029 | pub fn set_frame_type(&mut self, ftype: FrameType) { self.frame_type = ftype; } |
7673d49a | 1030 | /// Sets keyframe flag. |
88c03b61 | 1031 | pub fn set_keyframe(&mut self, key: bool) { self.key = key; } |
7673d49a | 1032 | /// Returns frame timestamp. |
e189501e | 1033 | pub fn get_time_information(&self) -> NATimeInfo { self.ts } |
7673d49a | 1034 | /// Returns frame presentation time. |
e189501e | 1035 | pub fn get_pts(&self) -> Option<u64> { self.ts.get_pts() } |
7673d49a | 1036 | /// Returns frame decoding time. |
e189501e | 1037 | pub fn get_dts(&self) -> Option<u64> { self.ts.get_dts() } |
7673d49a | 1038 | /// Returns picture ID. |
f18bba90 | 1039 | pub fn get_id(&self) -> i64 { self.id } |
7673d49a | 1040 | /// Returns frame display duration. |
e189501e | 1041 | pub fn get_duration(&self) -> Option<u64> { self.ts.get_duration() } |
7673d49a | 1042 | /// Sets new presentation timestamp. |
e189501e | 1043 | pub fn set_pts(&mut self, pts: Option<u64>) { self.ts.set_pts(pts); } |
7673d49a | 1044 | /// Sets new decoding timestamp. |
e189501e | 1045 | pub fn set_dts(&mut self, dts: Option<u64>) { self.ts.set_dts(dts); } |
7673d49a | 1046 | /// Sets new picture ID. |
f18bba90 | 1047 | pub fn set_id(&mut self, id: i64) { self.id = id; } |
7673d49a | 1048 | /// Sets new duration. |
e189501e | 1049 | pub fn set_duration(&mut self, dur: Option<u64>) { self.ts.set_duration(dur); } |
66116504 | 1050 | |
7673d49a | 1051 | /// Returns a reference to the frame data. |
22cb00db | 1052 | pub fn get_buffer(&self) -> NABufferType { self.buffer.clone() } |
171860fc | 1053 | |
7673d49a | 1054 | /// Converts current instance into a reference-counted one. |
171860fc | 1055 | pub fn into_ref(self) -> NAFrameRef { Arc::new(self) } |
2b8bf9a0 KS |
1056 | |
1057 | /// Creates new frame with metadata from `NAPacket`. | |
1058 | pub fn new_from_pkt(pkt: &NAPacket, info: NACodecInfoRef, buf: NABufferType) -> NAFrame { | |
1059 | NAFrame::new(pkt.ts, FrameType::Other, pkt.keyframe, info, /*HashMap::new(),*/ buf) | |
1060 | } | |
5869fd63 KS |
1061 | } |
1062 | ||
ebd71c92 KS |
1063 | impl fmt::Display for NAFrame { |
1064 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
bf507799 | 1065 | let mut ostr = format!("frame type {}", self.frame_type); |
e243ceb4 KS |
1066 | if let Some(pts) = self.ts.pts { ostr = format!("{} pts {}", ostr, pts); } |
1067 | if let Some(dts) = self.ts.dts { ostr = format!("{} dts {}", ostr, dts); } | |
1068 | if let Some(dur) = self.ts.duration { ostr = format!("{} duration {}", ostr, dur); } | |
1069 | if self.key { ostr = format!("{} kf", ostr); } | |
1070 | write!(f, "[{}]", ostr) | |
ebd71c92 KS |
1071 | } |
1072 | } | |
88c03b61 | 1073 | |
7673d49a | 1074 | /// A list of possible stream types. |
baf5478c | 1075 | #[derive(Debug,Clone,Copy,PartialEq)] |
5869fd63 | 1076 | #[allow(dead_code)] |
48c88fde | 1077 | pub enum StreamType { |
7673d49a | 1078 | /// Video stream. |
48c88fde | 1079 | Video, |
7673d49a | 1080 | /// Audio stream. |
48c88fde | 1081 | Audio, |
7673d49a | 1082 | /// Subtitles. |
48c88fde | 1083 | Subtitles, |
7673d49a | 1084 | /// Any data stream (or might be an unrecognized audio/video stream). |
48c88fde | 1085 | Data, |
7673d49a | 1086 | /// Nonexistent stream. |
48c88fde KS |
1087 | None, |
1088 | } | |
1089 | ||
1090 | impl fmt::Display for StreamType { | |
1091 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
1092 | match *self { | |
1093 | StreamType::Video => write!(f, "Video"), | |
1094 | StreamType::Audio => write!(f, "Audio"), | |
1095 | StreamType::Subtitles => write!(f, "Subtitles"), | |
1096 | StreamType::Data => write!(f, "Data"), | |
1097 | StreamType::None => write!(f, "-"), | |
1098 | } | |
1099 | } | |
1100 | } | |
1101 | ||
7673d49a | 1102 | /// Stream data. |
48c88fde KS |
1103 | #[allow(dead_code)] |
1104 | #[derive(Clone)] | |
1105 | pub struct NAStream { | |
bf507799 KS |
1106 | media_type: StreamType, |
1107 | /// Stream ID. | |
1108 | pub id: u32, | |
1109 | num: usize, | |
1110 | info: NACodecInfoRef, | |
1111 | /// Timebase numerator. | |
1112 | pub tb_num: u32, | |
1113 | /// Timebase denominator. | |
1114 | pub tb_den: u32, | |
e189501e KS |
1115 | } |
1116 | ||
7673d49a | 1117 | /// A specialised reference-counted `NAStream` type. |
70910ac3 KS |
1118 | pub type NAStreamRef = Arc<NAStream>; |
1119 | ||
7673d49a | 1120 | /// Downscales the timebase by its greatest common denominator. |
e189501e KS |
1121 | pub fn reduce_timebase(tb_num: u32, tb_den: u32) -> (u32, u32) { |
1122 | if tb_num == 0 { return (tb_num, tb_den); } | |
1123 | if (tb_den % tb_num) == 0 { return (1, tb_den / tb_num); } | |
1124 | ||
1125 | let mut a = tb_num; | |
1126 | let mut b = tb_den; | |
1127 | ||
1128 | while a != b { | |
1129 | if a > b { a -= b; } | |
1130 | else if b > a { b -= a; } | |
1131 | } | |
1132 | ||
1133 | (tb_num / a, tb_den / a) | |
5869fd63 | 1134 | } |
48c88fde KS |
1135 | |
1136 | impl NAStream { | |
7673d49a | 1137 | /// Constructs a new `NAStream` instance. |
e189501e KS |
1138 | pub fn new(mt: StreamType, id: u32, info: NACodecInfo, tb_num: u32, tb_den: u32) -> Self { |
1139 | let (n, d) = reduce_timebase(tb_num, tb_den); | |
e243ceb4 | 1140 | NAStream { media_type: mt, id, num: 0, info: info.into_ref(), tb_num: n, tb_den: d } |
48c88fde | 1141 | } |
7673d49a | 1142 | /// Returns stream id. |
48c88fde | 1143 | pub fn get_id(&self) -> u32 { self.id } |
7673d49a | 1144 | /// Returns stream type. |
baf5478c | 1145 | pub fn get_media_type(&self) -> StreamType { self.media_type } |
7673d49a | 1146 | /// Returns stream number assigned by demuxer. |
48c88fde | 1147 | pub fn get_num(&self) -> usize { self.num } |
7673d49a | 1148 | /// Sets stream number. |
48c88fde | 1149 | pub fn set_num(&mut self, num: usize) { self.num = num; } |
7673d49a | 1150 | /// Returns codec information. |
2422d969 | 1151 | pub fn get_info(&self) -> NACodecInfoRef { self.info.clone() } |
7673d49a | 1152 | /// Returns stream timebase. |
e189501e | 1153 | pub fn get_timebase(&self) -> (u32, u32) { (self.tb_num, self.tb_den) } |
7673d49a | 1154 | /// Sets new stream timebase. |
e189501e KS |
1155 | pub fn set_timebase(&mut self, tb_num: u32, tb_den: u32) { |
1156 | let (n, d) = reduce_timebase(tb_num, tb_den); | |
1157 | self.tb_num = n; | |
1158 | self.tb_den = d; | |
1159 | } | |
7673d49a | 1160 | /// Converts current instance into a reference-counted one. |
70910ac3 | 1161 | pub fn into_ref(self) -> NAStreamRef { Arc::new(self) } |
48c88fde KS |
1162 | } |
1163 | ||
1164 | impl fmt::Display for NAStream { | |
1165 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
e189501e | 1166 | write!(f, "({}#{} @ {}/{} - {})", self.media_type, self.id, self.tb_num, self.tb_den, self.info.get_properties()) |
48c88fde KS |
1167 | } |
1168 | } | |
1169 | ||
8057a7fd KS |
1170 | /// Side data that may accompany demuxed data. |
1171 | #[derive(Clone)] | |
1172 | pub enum NASideData { | |
1173 | /// Palette information. | |
1174 | /// | |
1175 | /// This side data contains a flag signalling that palette has changed since previous time and a reference to the current palette. | |
1176 | /// Palette is stored in 8-bit RGBA format. | |
1177 | Palette(bool, Arc<[u8; 1024]>), | |
1178 | /// Generic user data. | |
1179 | UserData(Arc<Vec<u8>>), | |
1180 | } | |
1181 | ||
7673d49a | 1182 | /// Packet with compressed data. |
48c88fde KS |
1183 | #[allow(dead_code)] |
1184 | pub struct NAPacket { | |
bf507799 KS |
1185 | stream: NAStreamRef, |
1186 | /// Packet timestamp. | |
1187 | pub ts: NATimeInfo, | |
1188 | buffer: NABufferRef<Vec<u8>>, | |
1189 | /// Keyframe flag. | |
1190 | pub keyframe: bool, | |
48c88fde | 1191 | // options: HashMap<String, NAValue<'a>>, |
8057a7fd KS |
1192 | /// Packet side data (e.g. palette for paletted formats). |
1193 | pub side_data: Vec<NASideData>, | |
48c88fde KS |
1194 | } |
1195 | ||
1196 | impl NAPacket { | |
7673d49a | 1197 | /// Constructs a new `NAPacket` instance. |
70910ac3 | 1198 | pub fn new(str: NAStreamRef, ts: NATimeInfo, kf: bool, vec: Vec<u8>) -> Self { |
48c88fde KS |
1199 | // let mut vec: Vec<u8> = Vec::new(); |
1200 | // vec.resize(size, 0); | |
8057a7fd | 1201 | NAPacket { stream: str, ts, keyframe: kf, buffer: NABufferRef::new(vec), side_data: Vec::new() } |
48c88fde | 1202 | } |
7673d49a | 1203 | /// Returns information about the stream packet belongs to. |
70910ac3 | 1204 | pub fn get_stream(&self) -> NAStreamRef { self.stream.clone() } |
7673d49a | 1205 | /// Returns packet timestamp. |
e189501e | 1206 | pub fn get_time_information(&self) -> NATimeInfo { self.ts } |
7673d49a | 1207 | /// Returns packet presentation timestamp. |
e189501e | 1208 | pub fn get_pts(&self) -> Option<u64> { self.ts.get_pts() } |
7673d49a | 1209 | /// Returns packet decoding timestamp. |
e189501e | 1210 | pub fn get_dts(&self) -> Option<u64> { self.ts.get_dts() } |
7673d49a | 1211 | /// Returns packet duration. |
e189501e | 1212 | pub fn get_duration(&self) -> Option<u64> { self.ts.get_duration() } |
7673d49a | 1213 | /// Reports whether this is a keyframe packet. |
48c88fde | 1214 | pub fn is_keyframe(&self) -> bool { self.keyframe } |
7673d49a | 1215 | /// Returns a reference to packet data. |
1a967e6b | 1216 | pub fn get_buffer(&self) -> NABufferRef<Vec<u8>> { self.buffer.clone() } |
8057a7fd KS |
1217 | /// Adds side data for a packet. |
1218 | pub fn add_side_data(&mut self, side_data: NASideData) { self.side_data.push(side_data); } | |
48c88fde KS |
1219 | } |
1220 | ||
1221 | impl Drop for NAPacket { | |
1222 | fn drop(&mut self) {} | |
1223 | } | |
1224 | ||
1225 | impl fmt::Display for NAPacket { | |
1226 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
e243ceb4 KS |
1227 | let mut ostr = format!("[pkt for {} size {}", self.stream, self.buffer.len()); |
1228 | if let Some(pts) = self.ts.pts { ostr = format!("{} pts {}", ostr, pts); } | |
1229 | if let Some(dts) = self.ts.dts { ostr = format!("{} dts {}", ostr, dts); } | |
1230 | if let Some(dur) = self.ts.duration { ostr = format!("{} duration {}", ostr, dur); } | |
1231 | if self.keyframe { ostr = format!("{} kf", ostr); } | |
1232 | ostr += "]"; | |
1233 | write!(f, "{}", ostr) | |
48c88fde KS |
1234 | } |
1235 | } |