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