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