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