switch to refcounted buffers
[nihav.git] / nihav-core / src / frame.rs
CommitLineData
22cb00db 1use std::cmp::max;
5869fd63 2use std::collections::HashMap;
83e603fa 3use std::fmt;
4e8b4f31
KS
4pub use std::rc::Rc;
5pub use std::cell::*;
6pub use crate::formats::*;
1a967e6b 7pub use crate::refs::*;
94dbb551 8
5869fd63 9#[allow(dead_code)]
66116504 10#[derive(Clone,Copy,PartialEq)]
5869fd63
KS
11pub struct NAAudioInfo {
12 sample_rate: u32,
13 channels: u8,
14 format: NASoniton,
15 block_len: usize,
16}
17
18impl NAAudioInfo {
19 pub fn new(sr: u32, ch: u8, fmt: NASoniton, bl: usize) -> Self {
20 NAAudioInfo { sample_rate: sr, channels: ch, format: fmt, block_len: bl }
21 }
66116504
KS
22 pub fn get_sample_rate(&self) -> u32 { self.sample_rate }
23 pub fn get_channels(&self) -> u8 { self.channels }
24 pub fn get_format(&self) -> NASoniton { self.format }
25 pub fn get_block_len(&self) -> usize { self.block_len }
5869fd63
KS
26}
27
83e603fa
KS
28impl fmt::Display for NAAudioInfo {
29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30 write!(f, "{} Hz, {} ch", self.sample_rate, self.channels)
31 }
32}
33
5869fd63 34#[allow(dead_code)]
66116504 35#[derive(Clone,Copy,PartialEq)]
5869fd63 36pub struct NAVideoInfo {
66116504
KS
37 width: usize,
38 height: usize,
5869fd63
KS
39 flipped: bool,
40 format: NAPixelFormaton,
41}
42
43impl NAVideoInfo {
66116504 44 pub fn new(w: usize, h: usize, flip: bool, fmt: NAPixelFormaton) -> Self {
5869fd63
KS
45 NAVideoInfo { width: w, height: h, flipped: flip, format: fmt }
46 }
66116504
KS
47 pub fn get_width(&self) -> usize { self.width as usize }
48 pub fn get_height(&self) -> usize { self.height as usize }
49 pub fn is_flipped(&self) -> bool { self.flipped }
50 pub fn get_format(&self) -> NAPixelFormaton { self.format }
dd1b60e1
KS
51 pub fn set_width(&mut self, w: usize) { self.width = w; }
52 pub fn set_height(&mut self, h: usize) { self.height = h; }
5869fd63
KS
53}
54
83e603fa
KS
55impl fmt::Display for NAVideoInfo {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57 write!(f, "{}x{}", self.width, self.height)
58 }
59}
60
66116504 61#[derive(Clone,Copy,PartialEq)]
5869fd63
KS
62pub enum NACodecTypeInfo {
63 None,
64 Audio(NAAudioInfo),
65 Video(NAVideoInfo),
66}
67
22cb00db
KS
68impl NACodecTypeInfo {
69 pub fn get_video_info(&self) -> Option<NAVideoInfo> {
70 match *self {
71 NACodecTypeInfo::Video(vinfo) => Some(vinfo),
72 _ => None,
73 }
74 }
75 pub fn get_audio_info(&self) -> Option<NAAudioInfo> {
76 match *self {
77 NACodecTypeInfo::Audio(ainfo) => Some(ainfo),
78 _ => None,
79 }
80 }
5076115b
KS
81 pub fn is_video(&self) -> bool {
82 match *self {
83 NACodecTypeInfo::Video(_) => true,
84 _ => false,
85 }
86 }
87 pub fn is_audio(&self) -> bool {
88 match *self {
89 NACodecTypeInfo::Audio(_) => true,
90 _ => false,
91 }
92 }
22cb00db
KS
93}
94
83e603fa
KS
95impl fmt::Display for NACodecTypeInfo {
96 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97 let ret = match *self {
98 NACodecTypeInfo::None => format!(""),
99 NACodecTypeInfo::Audio(fmt) => format!("{}", fmt),
100 NACodecTypeInfo::Video(fmt) => format!("{}", fmt),
101 };
102 write!(f, "{}", ret)
103 }
104}
105
22cb00db
KS
106#[derive(Clone)]
107pub struct NAVideoBuffer<T> {
6c8e5c40 108 info: NAVideoInfo,
1a967e6b 109 data: NABufferRef<Vec<T>>,
6c8e5c40
KS
110 offs: Vec<usize>,
111 strides: Vec<usize>,
22cb00db
KS
112}
113
114impl<T: Clone> NAVideoBuffer<T> {
115 pub fn get_offset(&self, idx: usize) -> usize {
116 if idx >= self.offs.len() { 0 }
117 else { self.offs[idx] }
118 }
119 pub fn get_info(&self) -> NAVideoInfo { self.info }
1a967e6b
KS
120 pub fn get_data(&self) -> &Vec<T> { self.data.as_ref() }
121 pub fn get_data_mut(&mut self) -> Option<&mut Vec<T>> { self.data.as_mut() }
22cb00db 122 pub fn copy_buffer(&mut self) -> Self {
1a967e6b
KS
123 let mut data: Vec<T> = Vec::with_capacity(self.data.len());
124 data.clone_from(self.data.as_ref());
22cb00db
KS
125 let mut offs: Vec<usize> = Vec::with_capacity(self.offs.len());
126 offs.clone_from(&self.offs);
6c8e5c40
KS
127 let mut strides: Vec<usize> = Vec::with_capacity(self.strides.len());
128 strides.clone_from(&self.strides);
1a967e6b 129 NAVideoBuffer { info: self.info, data: NABufferRef::new(data), offs: offs, strides: strides }
22cb00db
KS
130 }
131 pub fn get_stride(&self, idx: usize) -> usize {
6c8e5c40
KS
132 if idx >= self.strides.len() { return 0; }
133 self.strides[idx]
22cb00db
KS
134 }
135 pub fn get_dimensions(&self, idx: usize) -> (usize, usize) {
136 get_plane_size(&self.info, idx)
137 }
138}
139
140#[derive(Clone)]
141pub struct NAAudioBuffer<T> {
142 info: NAAudioInfo,
1a967e6b 143 data: NABufferRef<Vec<T>>,
22cb00db
KS
144 offs: Vec<usize>,
145 chmap: NAChannelMap,
5076115b 146 len: usize,
22cb00db
KS
147}
148
149impl<T: Clone> NAAudioBuffer<T> {
150 pub fn get_offset(&self, idx: usize) -> usize {
151 if idx >= self.offs.len() { 0 }
152 else { self.offs[idx] }
153 }
154 pub fn get_info(&self) -> NAAudioInfo { self.info }
155 pub fn get_chmap(&self) -> NAChannelMap { self.chmap.clone() }
1a967e6b
KS
156 pub fn get_data(&self) -> &Vec<T> { self.data.as_ref() }
157 pub fn get_data_mut(&mut self) -> Option<&mut Vec<T>> { self.data.as_mut() }
22cb00db 158 pub fn copy_buffer(&mut self) -> Self {
1a967e6b
KS
159 let mut data: Vec<T> = Vec::with_capacity(self.data.len());
160 data.clone_from(self.data.as_ref());
22cb00db
KS
161 let mut offs: Vec<usize> = Vec::with_capacity(self.offs.len());
162 offs.clone_from(&self.offs);
1a967e6b 163 NAAudioBuffer { info: self.info, data: NABufferRef::new(data), offs: offs, chmap: self.get_chmap(), len: self.len }
22cb00db 164 }
5076115b 165 pub fn get_length(&self) -> usize { self.len }
22cb00db
KS
166}
167
87a1ebc3 168impl NAAudioBuffer<u8> {
1a967e6b
KS
169 pub fn new_from_buf(info: NAAudioInfo, data: NABufferRef<Vec<u8>>, chmap: NAChannelMap) -> Self {
170 let len = data.len();
5076115b 171 NAAudioBuffer { info: info, data: data, chmap: chmap, offs: Vec::new(), len: len }
87a1ebc3
KS
172 }
173}
174
22cb00db
KS
175#[derive(Clone)]
176pub enum NABufferType {
177 Video (NAVideoBuffer<u8>),
178 Video16 (NAVideoBuffer<u16>),
3bba1c4a 179 Video32 (NAVideoBuffer<u32>),
22cb00db
KS
180 VideoPacked(NAVideoBuffer<u8>),
181 AudioU8 (NAAudioBuffer<u8>),
182 AudioI16 (NAAudioBuffer<i16>),
87a1ebc3 183 AudioI32 (NAAudioBuffer<i32>),
22cb00db
KS
184 AudioF32 (NAAudioBuffer<f32>),
185 AudioPacked(NAAudioBuffer<u8>),
1a967e6b 186 Data (NABufferRef<Vec<u8>>),
22cb00db
KS
187 None,
188}
189
190impl NABufferType {
191 pub fn get_offset(&self, idx: usize) -> usize {
192 match *self {
193 NABufferType::Video(ref vb) => vb.get_offset(idx),
194 NABufferType::Video16(ref vb) => vb.get_offset(idx),
3bba1c4a 195 NABufferType::Video32(ref vb) => vb.get_offset(idx),
22cb00db
KS
196 NABufferType::VideoPacked(ref vb) => vb.get_offset(idx),
197 NABufferType::AudioU8(ref ab) => ab.get_offset(idx),
198 NABufferType::AudioI16(ref ab) => ab.get_offset(idx),
199 NABufferType::AudioF32(ref ab) => ab.get_offset(idx),
200 NABufferType::AudioPacked(ref ab) => ab.get_offset(idx),
201 _ => 0,
202 }
203 }
3bba1c4a
KS
204 pub fn get_video_info(&self) -> Option<NAVideoInfo> {
205 match *self {
206 NABufferType::Video(ref vb) => Some(vb.get_info()),
207 NABufferType::Video16(ref vb) => Some(vb.get_info()),
208 NABufferType::Video32(ref vb) => Some(vb.get_info()),
209 NABufferType::VideoPacked(ref vb) => Some(vb.get_info()),
210 _ => None,
211 }
212 }
6e09a92e 213 pub fn get_vbuf(&self) -> Option<NAVideoBuffer<u8>> {
22cb00db
KS
214 match *self {
215 NABufferType::Video(ref vb) => Some(vb.clone()),
87a1ebc3
KS
216 NABufferType::VideoPacked(ref vb) => Some(vb.clone()),
217 _ => None,
218 }
219 }
6e09a92e 220 pub fn get_vbuf16(&self) -> Option<NAVideoBuffer<u16>> {
87a1ebc3
KS
221 match *self {
222 NABufferType::Video16(ref vb) => Some(vb.clone()),
223 _ => None,
224 }
225 }
6e09a92e 226 pub fn get_vbuf32(&self) -> Option<NAVideoBuffer<u32>> {
3bba1c4a
KS
227 match *self {
228 NABufferType::Video32(ref vb) => Some(vb.clone()),
229 _ => None,
230 }
231 }
6e09a92e 232 pub fn get_abuf_u8(&self) -> Option<NAAudioBuffer<u8>> {
87a1ebc3
KS
233 match *self {
234 NABufferType::AudioU8(ref ab) => Some(ab.clone()),
235 NABufferType::AudioPacked(ref ab) => Some(ab.clone()),
236 _ => None,
237 }
238 }
6e09a92e 239 pub fn get_abuf_i16(&self) -> Option<NAAudioBuffer<i16>> {
87a1ebc3
KS
240 match *self {
241 NABufferType::AudioI16(ref ab) => Some(ab.clone()),
242 _ => None,
243 }
244 }
6e09a92e 245 pub fn get_abuf_i32(&self) -> Option<NAAudioBuffer<i32>> {
87a1ebc3
KS
246 match *self {
247 NABufferType::AudioI32(ref ab) => Some(ab.clone()),
248 _ => None,
249 }
250 }
6e09a92e 251 pub fn get_abuf_f32(&self) -> Option<NAAudioBuffer<f32>> {
87a1ebc3
KS
252 match *self {
253 NABufferType::AudioF32(ref ab) => Some(ab.clone()),
22cb00db
KS
254 _ => None,
255 }
256 }
257}
258
259#[derive(Debug,Clone,Copy,PartialEq)]
260pub enum AllocatorError {
261 TooLargeDimensions,
262 FormatError,
263}
264
265pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result<NABufferType, AllocatorError> {
266 let fmt = &vinfo.format;
267 let mut new_size: usize = 0;
6c8e5c40
KS
268 let mut offs: Vec<usize> = Vec::new();
269 let mut strides: Vec<usize> = Vec::new();
22cb00db
KS
270
271 for i in 0..fmt.get_num_comp() {
272 if fmt.get_chromaton(i) == None { return Err(AllocatorError::FormatError); }
273 }
274
275 let align_mod = ((1 << align) as usize) - 1;
276 let width = ((vinfo.width as usize) + align_mod) & !align_mod;
277 let height = ((vinfo.height as usize) + align_mod) & !align_mod;
278 let mut max_depth = 0;
279 let mut all_packed = true;
3bba1c4a 280 let mut all_bytealigned = true;
22cb00db 281 for i in 0..fmt.get_num_comp() {
6c8e5c40
KS
282 let ochr = fmt.get_chromaton(i);
283 if let None = ochr { continue; }
284 let chr = ochr.unwrap();
22cb00db
KS
285 if !chr.is_packed() {
286 all_packed = false;
3bba1c4a
KS
287 } else if ((chr.get_shift() + chr.get_depth()) & 7) != 0 {
288 all_bytealigned = false;
22cb00db
KS
289 }
290 max_depth = max(max_depth, chr.get_depth());
291 }
3bba1c4a
KS
292 let unfit_elem_size = match fmt.get_elem_size() {
293 2 | 4 => false,
294 _ => true,
295 };
22cb00db
KS
296
297//todo semi-packed like NV12
bc6aac3d
KS
298 if fmt.is_paletted() {
299//todo various-sized palettes?
6c8e5c40
KS
300 let stride = vinfo.get_format().get_chromaton(0).unwrap().get_linesize(width);
301 let pic_sz = stride.checked_mul(height);
bc6aac3d
KS
302 if pic_sz == None { return Err(AllocatorError::TooLargeDimensions); }
303 let pal_size = 256 * (fmt.get_elem_size() as usize);
304 let new_size = pic_sz.unwrap().checked_add(pal_size);
305 if new_size == None { return Err(AllocatorError::TooLargeDimensions); }
306 offs.push(0);
6c8e5c40
KS
307 offs.push(stride * height);
308 strides.push(stride);
bc6aac3d
KS
309 let mut data: Vec<u8> = Vec::with_capacity(new_size.unwrap());
310 data.resize(new_size.unwrap(), 0);
1a967e6b 311 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
bc6aac3d
KS
312 Ok(NABufferType::Video(buf))
313 } else if !all_packed {
22cb00db 314 for i in 0..fmt.get_num_comp() {
6c8e5c40
KS
315 let ochr = fmt.get_chromaton(i);
316 if let None = ochr { continue; }
317 let chr = ochr.unwrap();
22cb00db
KS
318 if !vinfo.is_flipped() {
319 offs.push(new_size as usize);
320 }
6c8e5c40 321 let stride = chr.get_linesize(width);
22cb00db 322 let cur_h = chr.get_height(height);
6c8e5c40 323 let cur_sz = stride.checked_mul(cur_h);
22cb00db
KS
324 if cur_sz == None { return Err(AllocatorError::TooLargeDimensions); }
325 let new_sz = new_size.checked_add(cur_sz.unwrap());
326 if new_sz == None { return Err(AllocatorError::TooLargeDimensions); }
327 new_size = new_sz.unwrap();
328 if vinfo.is_flipped() {
329 offs.push(new_size as usize);
330 }
6c8e5c40 331 strides.push(stride);
22cb00db
KS
332 }
333 if max_depth <= 8 {
334 let mut data: Vec<u8> = Vec::with_capacity(new_size);
335 data.resize(new_size, 0);
1a967e6b 336 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
22cb00db 337 Ok(NABufferType::Video(buf))
3bba1c4a 338 } else if max_depth <= 16 {
22cb00db
KS
339 let mut data: Vec<u16> = Vec::with_capacity(new_size);
340 data.resize(new_size, 0);
1a967e6b 341 let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
22cb00db 342 Ok(NABufferType::Video16(buf))
3bba1c4a
KS
343 } else {
344 let mut data: Vec<u32> = Vec::with_capacity(new_size);
345 data.resize(new_size, 0);
1a967e6b 346 let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
3bba1c4a 347 Ok(NABufferType::Video32(buf))
22cb00db 348 }
3bba1c4a 349 } else if all_bytealigned || unfit_elem_size {
22cb00db
KS
350 let elem_sz = fmt.get_elem_size();
351 let line_sz = width.checked_mul(elem_sz as usize);
352 if line_sz == None { return Err(AllocatorError::TooLargeDimensions); }
353 let new_sz = line_sz.unwrap().checked_mul(height);
354 if new_sz == None { return Err(AllocatorError::TooLargeDimensions); }
355 new_size = new_sz.unwrap();
356 let mut data: Vec<u8> = Vec::with_capacity(new_size);
357 data.resize(new_size, 0);
6c8e5c40 358 strides.push(line_sz.unwrap());
1a967e6b 359 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
22cb00db 360 Ok(NABufferType::VideoPacked(buf))
3bba1c4a
KS
361 } else {
362 let elem_sz = fmt.get_elem_size();
363 let new_sz = width.checked_mul(height);
364 if new_sz == None { return Err(AllocatorError::TooLargeDimensions); }
365 new_size = new_sz.unwrap();
366 match elem_sz {
367 2 => {
368 let mut data: Vec<u16> = Vec::with_capacity(new_size);
369 data.resize(new_size, 0);
370 strides.push(width);
1a967e6b 371 let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
3bba1c4a
KS
372 Ok(NABufferType::Video16(buf))
373 },
374 4 => {
375 let mut data: Vec<u32> = Vec::with_capacity(new_size);
376 data.resize(new_size, 0);
377 strides.push(width);
1a967e6b 378 let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
3bba1c4a
KS
379 Ok(NABufferType::Video32(buf))
380 },
381 _ => unreachable!(),
382 }
22cb00db
KS
383 }
384}
385
386pub fn alloc_audio_buffer(ainfo: NAAudioInfo, nsamples: usize, chmap: NAChannelMap) -> Result<NABufferType, AllocatorError> {
387 let mut offs: Vec<usize> = Vec::new();
4c6c19cb 388 if ainfo.format.is_planar() || (ainfo.channels == 1 && (ainfo.format.get_bits() % 8) == 0) {
22cb00db
KS
389 let len = nsamples.checked_mul(ainfo.channels as usize);
390 if len == None { return Err(AllocatorError::TooLargeDimensions); }
391 let length = len.unwrap();
392 for i in 0..ainfo.channels {
393 offs.push((i as usize) * nsamples);
394 }
395 if ainfo.format.is_float() {
396 if ainfo.format.get_bits() == 32 {
397 let mut data: Vec<f32> = Vec::with_capacity(length);
398 data.resize(length, 0.0);
1a967e6b 399 let buf: NAAudioBuffer<f32> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
22cb00db
KS
400 Ok(NABufferType::AudioF32(buf))
401 } else {
402 Err(AllocatorError::TooLargeDimensions)
403 }
404 } else {
405 if ainfo.format.get_bits() == 8 && !ainfo.format.is_signed() {
406 let mut data: Vec<u8> = Vec::with_capacity(length);
407 data.resize(length, 0);
1a967e6b 408 let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
22cb00db
KS
409 Ok(NABufferType::AudioU8(buf))
410 } else if ainfo.format.get_bits() == 16 && ainfo.format.is_signed() {
411 let mut data: Vec<i16> = Vec::with_capacity(length);
412 data.resize(length, 0);
1a967e6b 413 let buf: NAAudioBuffer<i16> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
22cb00db
KS
414 Ok(NABufferType::AudioI16(buf))
415 } else {
416 Err(AllocatorError::TooLargeDimensions)
417 }
418 }
419 } else {
420 let len = nsamples.checked_mul(ainfo.channels as usize);
421 if len == None { return Err(AllocatorError::TooLargeDimensions); }
422 let length = ainfo.format.get_audio_size(len.unwrap() as u64);
423 let mut data: Vec<u8> = Vec::with_capacity(length);
424 data.resize(length, 0);
1a967e6b 425 let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
1a151e53 426 Ok(NABufferType::AudioPacked(buf))
22cb00db
KS
427 }
428}
429
430pub fn alloc_data_buffer(size: usize) -> Result<NABufferType, AllocatorError> {
431 let mut data: Vec<u8> = Vec::with_capacity(size);
432 data.resize(size, 0);
1a967e6b 433 let buf: NABufferRef<Vec<u8>> = NABufferRef::new(data);
22cb00db
KS
434 Ok(NABufferType::Data(buf))
435}
436
437pub fn copy_buffer(buf: NABufferType) -> NABufferType {
438 buf.clone()
439}
440
1a967e6b
KS
441pub struct NABufferPool {
442 pool: Vec<NABufferRef<NABufferType>>,
443 max_len: usize,
444}
445
446impl NABufferPool {
447 pub fn new(max_len: usize) -> Self {
448 Self {
449 pool: Vec::with_capacity(max_len),
450 max_len,
451 }
452 }
453 pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> {
454 let nbufs = self.max_len - self.pool.len();
455 for _ in 0..nbufs {
456 let buf = alloc_video_buffer(vinfo.clone(), align)?;
457 self.pool.push(NABufferRef::new(buf));
458 }
459 Ok(())
460 }
461 pub fn prealloc_audio(&mut self, ainfo: NAAudioInfo, nsamples: usize, chmap: NAChannelMap) -> Result<(), AllocatorError> {
462 let nbufs = self.max_len - self.pool.len();
463 for _ in 0..nbufs {
464 let buf = alloc_audio_buffer(ainfo.clone(), nsamples, chmap.clone())?;
465 self.pool.push(NABufferRef::new(buf));
466 }
467 Ok(())
468 }
469 pub fn add(&mut self, buf: NABufferType) -> bool {
470 if self.pool.len() < self.max_len {
471 self.pool.push(NABufferRef::new(buf));
472 true
473 } else {
474 false
475 }
476 }
477 pub fn get_free(&mut self) -> Option<NABufferRef<NABufferType>> {
478 for e in self.pool.iter() {
479 if e.get_num_refs() == 1 {
480 return Some(e.clone());
481 }
482 }
483 None
484 }
485}
486
5869fd63 487#[allow(dead_code)]
8869d452
KS
488#[derive(Clone)]
489pub struct NACodecInfo {
ccae5343 490 name: &'static str,
5869fd63 491 properties: NACodecTypeInfo,
8869d452 492 extradata: Option<Rc<Vec<u8>>>,
5869fd63
KS
493}
494
8869d452 495impl NACodecInfo {
ccae5343 496 pub fn new(name: &'static str, p: NACodecTypeInfo, edata: Option<Vec<u8>>) -> Self {
8869d452
KS
497 let extradata = match edata {
498 None => None,
499 Some(vec) => Some(Rc::new(vec)),
500 };
ccae5343 501 NACodecInfo { name: name, properties: p, extradata: extradata }
8869d452 502 }
66116504
KS
503 pub fn new_ref(name: &'static str, p: NACodecTypeInfo, edata: Option<Rc<Vec<u8>>>) -> Self {
504 NACodecInfo { name: name, properties: p, extradata: edata }
505 }
8869d452
KS
506 pub fn get_properties(&self) -> NACodecTypeInfo { self.properties }
507 pub fn get_extradata(&self) -> Option<Rc<Vec<u8>>> {
508 if let Some(ref vec) = self.extradata { return Some(vec.clone()); }
509 None
5869fd63 510 }
66116504
KS
511 pub fn get_name(&self) -> &'static str { self.name }
512 pub fn is_video(&self) -> bool {
513 if let NACodecTypeInfo::Video(_) = self.properties { return true; }
514 false
515 }
516 pub fn is_audio(&self) -> bool {
517 if let NACodecTypeInfo::Audio(_) = self.properties { return true; }
518 false
519 }
5076115b
KS
520 pub fn new_dummy() -> Rc<Self> {
521 Rc::new(DUMMY_CODEC_INFO)
522 }
523 pub fn replace_info(&self, p: NACodecTypeInfo) -> Rc<Self> {
524 Rc::new(NACodecInfo { name: self.name, properties: p, extradata: self.extradata.clone() })
525 }
66116504
KS
526}
527
241e56f1
KS
528impl Default for NACodecInfo {
529 fn default() -> Self { DUMMY_CODEC_INFO }
530}
531
66116504
KS
532impl fmt::Display for NACodecInfo {
533 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
534 let edata = match self.extradata.clone() {
535 None => format!("no extradata"),
536 Some(v) => format!("{} byte(s) of extradata", v.len()),
537 };
538 write!(f, "{}: {} {}", self.name, self.properties, edata)
539 }
540}
541
542pub const DUMMY_CODEC_INFO: NACodecInfo = NACodecInfo {
543 name: "none",
544 properties: NACodecTypeInfo::None,
545 extradata: None };
546
66116504
KS
547#[derive(Debug,Clone)]
548pub enum NAValue {
5869fd63
KS
549 None,
550 Int(i32),
551 Long(i64),
552 String(String),
66116504 553 Data(Rc<Vec<u8>>),
5869fd63
KS
554}
555
88c03b61
KS
556#[derive(Debug,Clone,Copy,PartialEq)]
557#[allow(dead_code)]
558pub enum FrameType {
559 I,
560 P,
561 B,
bc6aac3d 562 Skip,
88c03b61
KS
563 Other,
564}
565
566impl fmt::Display for FrameType {
567 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
568 match *self {
569 FrameType::I => write!(f, "I"),
570 FrameType::P => write!(f, "P"),
571 FrameType::B => write!(f, "B"),
bc6aac3d 572 FrameType::Skip => write!(f, "skip"),
88c03b61
KS
573 FrameType::Other => write!(f, "x"),
574 }
575 }
576}
577
e189501e
KS
578#[derive(Debug,Clone,Copy)]
579pub struct NATimeInfo {
5869fd63
KS
580 pts: Option<u64>,
581 dts: Option<u64>,
582 duration: Option<u64>,
e189501e
KS
583 tb_num: u32,
584 tb_den: u32,
585}
586
587impl NATimeInfo {
588 pub fn new(pts: Option<u64>, dts: Option<u64>, duration: Option<u64>, tb_num: u32, tb_den: u32) -> Self {
589 NATimeInfo { pts: pts, dts: dts, duration: duration, tb_num: tb_num, tb_den: tb_den }
590 }
591 pub fn get_pts(&self) -> Option<u64> { self.pts }
592 pub fn get_dts(&self) -> Option<u64> { self.dts }
593 pub fn get_duration(&self) -> Option<u64> { self.duration }
594 pub fn set_pts(&mut self, pts: Option<u64>) { self.pts = pts; }
595 pub fn set_dts(&mut self, dts: Option<u64>) { self.dts = dts; }
596 pub fn set_duration(&mut self, dur: Option<u64>) { self.duration = dur; }
597}
598
599#[allow(dead_code)]
600#[derive(Clone)]
601pub struct NAFrame {
602 ts: NATimeInfo,
22cb00db 603 buffer: NABufferType,
66116504 604 info: Rc<NACodecInfo>,
88c03b61
KS
605 ftype: FrameType,
606 key: bool,
66116504
KS
607 options: HashMap<String, NAValue>,
608}
609
ebd71c92
KS
610pub type NAFrameRef = Rc<RefCell<NAFrame>>;
611
66116504
KS
612fn get_plane_size(info: &NAVideoInfo, idx: usize) -> (usize, usize) {
613 let chromaton = info.get_format().get_chromaton(idx);
614 if let None = chromaton { return (0, 0); }
615 let (hs, vs) = chromaton.unwrap().get_subsampling();
616 let w = (info.get_width() + ((1 << hs) - 1)) >> hs;
617 let h = (info.get_height() + ((1 << vs) - 1)) >> vs;
618 (w, h)
619}
620
621impl NAFrame {
e189501e 622 pub fn new(ts: NATimeInfo,
88c03b61
KS
623 ftype: FrameType,
624 keyframe: bool,
66116504 625 info: Rc<NACodecInfo>,
22cb00db
KS
626 options: HashMap<String, NAValue>,
627 buffer: NABufferType) -> Self {
e189501e 628 NAFrame { ts: ts, buffer: buffer, info: info, ftype: ftype, key: keyframe, options: options }
ebd71c92 629 }
5076115b 630 pub fn get_info(&self) -> Rc<NACodecInfo> { self.info.clone() }
88c03b61
KS
631 pub fn get_frame_type(&self) -> FrameType { self.ftype }
632 pub fn is_keyframe(&self) -> bool { self.key }
88c03b61
KS
633 pub fn set_frame_type(&mut self, ftype: FrameType) { self.ftype = ftype; }
634 pub fn set_keyframe(&mut self, key: bool) { self.key = key; }
e189501e
KS
635 pub fn get_time_information(&self) -> NATimeInfo { self.ts }
636 pub fn get_pts(&self) -> Option<u64> { self.ts.get_pts() }
637 pub fn get_dts(&self) -> Option<u64> { self.ts.get_dts() }
638 pub fn get_duration(&self) -> Option<u64> { self.ts.get_duration() }
639 pub fn set_pts(&mut self, pts: Option<u64>) { self.ts.set_pts(pts); }
640 pub fn set_dts(&mut self, dts: Option<u64>) { self.ts.set_dts(dts); }
641 pub fn set_duration(&mut self, dur: Option<u64>) { self.ts.set_duration(dur); }
66116504 642
22cb00db 643 pub fn get_buffer(&self) -> NABufferType { self.buffer.clone() }
5869fd63
KS
644}
645
ebd71c92
KS
646impl fmt::Display for NAFrame {
647 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
22cb00db 648 let mut foo = format!("frame type {}", self.ftype);
e189501e
KS
649 if let Some(pts) = self.ts.pts { foo = format!("{} pts {}", foo, pts); }
650 if let Some(dts) = self.ts.dts { foo = format!("{} dts {}", foo, dts); }
651 if let Some(dur) = self.ts.duration { foo = format!("{} duration {}", foo, dur); }
ebd71c92
KS
652 if self.key { foo = format!("{} kf", foo); }
653 write!(f, "[{}]", foo)
654 }
655}
88c03b61 656
48c88fde
KS
657/// Possible stream types.
658#[derive(Debug,Clone,Copy)]
5869fd63 659#[allow(dead_code)]
48c88fde
KS
660pub enum StreamType {
661 /// video stream
662 Video,
663 /// audio stream
664 Audio,
665 /// subtitles
666 Subtitles,
667 /// any data stream (or might be an unrecognized audio/video stream)
668 Data,
669 /// nonexistent stream
670 None,
671}
672
673impl fmt::Display for StreamType {
674 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
675 match *self {
676 StreamType::Video => write!(f, "Video"),
677 StreamType::Audio => write!(f, "Audio"),
678 StreamType::Subtitles => write!(f, "Subtitles"),
679 StreamType::Data => write!(f, "Data"),
680 StreamType::None => write!(f, "-"),
681 }
682 }
683}
684
685#[allow(dead_code)]
686#[derive(Clone)]
687pub struct NAStream {
688 media_type: StreamType,
689 id: u32,
690 num: usize,
691 info: Rc<NACodecInfo>,
e189501e
KS
692 tb_num: u32,
693 tb_den: u32,
694}
695
696pub fn reduce_timebase(tb_num: u32, tb_den: u32) -> (u32, u32) {
697 if tb_num == 0 { return (tb_num, tb_den); }
698 if (tb_den % tb_num) == 0 { return (1, tb_den / tb_num); }
699
700 let mut a = tb_num;
701 let mut b = tb_den;
702
703 while a != b {
704 if a > b { a -= b; }
705 else if b > a { b -= a; }
706 }
707
708 (tb_num / a, tb_den / a)
5869fd63 709}
48c88fde
KS
710
711impl NAStream {
e189501e
KS
712 pub fn new(mt: StreamType, id: u32, info: NACodecInfo, tb_num: u32, tb_den: u32) -> Self {
713 let (n, d) = reduce_timebase(tb_num, tb_den);
714 NAStream { media_type: mt, id: id, num: 0, info: Rc::new(info), tb_num: n, tb_den: d }
48c88fde
KS
715 }
716 pub fn get_id(&self) -> u32 { self.id }
717 pub fn get_num(&self) -> usize { self.num }
718 pub fn set_num(&mut self, num: usize) { self.num = num; }
719 pub fn get_info(&self) -> Rc<NACodecInfo> { self.info.clone() }
e189501e
KS
720 pub fn get_timebase(&self) -> (u32, u32) { (self.tb_num, self.tb_den) }
721 pub fn set_timebase(&mut self, tb_num: u32, tb_den: u32) {
722 let (n, d) = reduce_timebase(tb_num, tb_den);
723 self.tb_num = n;
724 self.tb_den = d;
725 }
48c88fde
KS
726}
727
728impl fmt::Display for NAStream {
729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
e189501e 730 write!(f, "({}#{} @ {}/{} - {})", self.media_type, self.id, self.tb_num, self.tb_den, self.info.get_properties())
48c88fde
KS
731 }
732}
733
734#[allow(dead_code)]
735pub struct NAPacket {
736 stream: Rc<NAStream>,
e189501e 737 ts: NATimeInfo,
1a967e6b 738 buffer: NABufferRef<Vec<u8>>,
48c88fde
KS
739 keyframe: bool,
740// options: HashMap<String, NAValue<'a>>,
741}
742
743impl NAPacket {
e189501e 744 pub fn new(str: Rc<NAStream>, ts: NATimeInfo, kf: bool, vec: Vec<u8>) -> Self {
48c88fde
KS
745// let mut vec: Vec<u8> = Vec::new();
746// vec.resize(size, 0);
1a967e6b 747 NAPacket { stream: str, ts: ts, keyframe: kf, buffer: NABufferRef::new(vec) }
48c88fde
KS
748 }
749 pub fn get_stream(&self) -> Rc<NAStream> { self.stream.clone() }
e189501e
KS
750 pub fn get_time_information(&self) -> NATimeInfo { self.ts }
751 pub fn get_pts(&self) -> Option<u64> { self.ts.get_pts() }
752 pub fn get_dts(&self) -> Option<u64> { self.ts.get_dts() }
753 pub fn get_duration(&self) -> Option<u64> { self.ts.get_duration() }
48c88fde 754 pub fn is_keyframe(&self) -> bool { self.keyframe }
1a967e6b 755 pub fn get_buffer(&self) -> NABufferRef<Vec<u8>> { self.buffer.clone() }
48c88fde
KS
756}
757
758impl Drop for NAPacket {
759 fn drop(&mut self) {}
760}
761
762impl fmt::Display for NAPacket {
763 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
764 let mut foo = format!("[pkt for {} size {}", self.stream, self.buffer.len());
e189501e
KS
765 if let Some(pts) = self.ts.pts { foo = format!("{} pts {}", foo, pts); }
766 if let Some(dts) = self.ts.dts { foo = format!("{} dts {}", foo, dts); }
767 if let Some(dur) = self.ts.duration { foo = format!("{} duration {}", foo, dur); }
48c88fde
KS
768 if self.keyframe { foo = format!("{} kf", foo); }
769 foo = foo + "]";
770 write!(f, "{}", foo)
771 }
772}
773
774pub trait FrameFromPacket {
22cb00db 775 fn new_from_pkt(pkt: &NAPacket, info: Rc<NACodecInfo>, buf: NABufferType) -> NAFrame;
48c88fde
KS
776 fn fill_timestamps(&mut self, pkt: &NAPacket);
777}
778
779impl FrameFromPacket for NAFrame {
22cb00db 780 fn new_from_pkt(pkt: &NAPacket, info: Rc<NACodecInfo>, buf: NABufferType) -> NAFrame {
e189501e 781 NAFrame::new(pkt.ts, FrameType::Other, pkt.keyframe, info, HashMap::new(), buf)
48c88fde
KS
782 }
783 fn fill_timestamps(&mut self, pkt: &NAPacket) {
e189501e 784 self.ts = pkt.get_time_information();
48c88fde
KS
785 }
786}
787