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