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