]> git.nihav.org Git - nihav.git/blob - nihav-core/src/frame.rs
ea9f2031b5b7eacc4e6da36653399a0420bf22b3
[nihav.git] / nihav-core / src / frame.rs
1 use std::cmp::max;
2 use std::collections::HashMap;
3 use std::fmt;
4 pub use std::rc::Rc;
5 pub use std::cell::*;
6 pub use crate::formats::*;
7 pub use crate::refs::*;
8
9 #[allow(dead_code)]
10 #[derive(Clone,Copy,PartialEq)]
11 pub struct NAAudioInfo {
12 sample_rate: u32,
13 channels: u8,
14 format: NASoniton,
15 block_len: usize,
16 }
17
18 impl 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 }
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 }
26 }
27
28 impl 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
34 #[allow(dead_code)]
35 #[derive(Clone,Copy,PartialEq)]
36 pub struct NAVideoInfo {
37 width: usize,
38 height: usize,
39 flipped: bool,
40 format: NAPixelFormaton,
41 }
42
43 impl NAVideoInfo {
44 pub fn new(w: usize, h: usize, flip: bool, fmt: NAPixelFormaton) -> Self {
45 NAVideoInfo { width: w, height: h, flipped: flip, format: fmt }
46 }
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 }
51 pub fn set_width(&mut self, w: usize) { self.width = w; }
52 pub fn set_height(&mut self, h: usize) { self.height = h; }
53 }
54
55 impl 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
61 #[derive(Clone,Copy,PartialEq)]
62 pub enum NACodecTypeInfo {
63 None,
64 Audio(NAAudioInfo),
65 Video(NAVideoInfo),
66 }
67
68 impl 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 }
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 }
93 }
94
95 impl 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
106 #[derive(Clone)]
107 pub struct NAVideoBuffer<T> {
108 info: NAVideoInfo,
109 data: NABufferRef<Vec<T>>,
110 offs: Vec<usize>,
111 strides: Vec<usize>,
112 }
113
114 impl<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 }
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() }
122 pub fn copy_buffer(&mut self) -> Self {
123 let mut data: Vec<T> = Vec::with_capacity(self.data.len());
124 data.clone_from(self.data.as_ref());
125 let mut offs: Vec<usize> = Vec::with_capacity(self.offs.len());
126 offs.clone_from(&self.offs);
127 let mut strides: Vec<usize> = Vec::with_capacity(self.strides.len());
128 strides.clone_from(&self.strides);
129 NAVideoBuffer { info: self.info, data: NABufferRef::new(data), offs: offs, strides: strides }
130 }
131 pub fn get_stride(&self, idx: usize) -> usize {
132 if idx >= self.strides.len() { return 0; }
133 self.strides[idx]
134 }
135 pub fn get_dimensions(&self, idx: usize) -> (usize, usize) {
136 get_plane_size(&self.info, idx)
137 }
138 }
139
140 #[derive(Clone)]
141 pub struct NAAudioBuffer<T> {
142 info: NAAudioInfo,
143 data: NABufferRef<Vec<T>>,
144 offs: Vec<usize>,
145 chmap: NAChannelMap,
146 len: usize,
147 }
148
149 impl<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() }
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() }
158 pub fn copy_buffer(&mut self) -> Self {
159 let mut data: Vec<T> = Vec::with_capacity(self.data.len());
160 data.clone_from(self.data.as_ref());
161 let mut offs: Vec<usize> = Vec::with_capacity(self.offs.len());
162 offs.clone_from(&self.offs);
163 NAAudioBuffer { info: self.info, data: NABufferRef::new(data), offs: offs, chmap: self.get_chmap(), len: self.len }
164 }
165 pub fn get_length(&self) -> usize { self.len }
166 }
167
168 impl NAAudioBuffer<u8> {
169 pub fn new_from_buf(info: NAAudioInfo, data: NABufferRef<Vec<u8>>, chmap: NAChannelMap) -> Self {
170 let len = data.len();
171 NAAudioBuffer { info: info, data: data, chmap: chmap, offs: Vec::new(), len: len }
172 }
173 }
174
175 #[derive(Clone)]
176 pub enum NABufferType {
177 Video (NAVideoBuffer<u8>),
178 Video16 (NAVideoBuffer<u16>),
179 Video32 (NAVideoBuffer<u32>),
180 VideoPacked(NAVideoBuffer<u8>),
181 AudioU8 (NAAudioBuffer<u8>),
182 AudioI16 (NAAudioBuffer<i16>),
183 AudioI32 (NAAudioBuffer<i32>),
184 AudioF32 (NAAudioBuffer<f32>),
185 AudioPacked(NAAudioBuffer<u8>),
186 Data (NABufferRef<Vec<u8>>),
187 None,
188 }
189
190 impl 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),
195 NABufferType::Video32(ref vb) => vb.get_offset(idx),
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 }
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 }
213 pub fn get_vbuf(&self) -> Option<NAVideoBuffer<u8>> {
214 match *self {
215 NABufferType::Video(ref vb) => Some(vb.clone()),
216 NABufferType::VideoPacked(ref vb) => Some(vb.clone()),
217 _ => None,
218 }
219 }
220 pub fn get_vbuf16(&self) -> Option<NAVideoBuffer<u16>> {
221 match *self {
222 NABufferType::Video16(ref vb) => Some(vb.clone()),
223 _ => None,
224 }
225 }
226 pub fn get_vbuf32(&self) -> Option<NAVideoBuffer<u32>> {
227 match *self {
228 NABufferType::Video32(ref vb) => Some(vb.clone()),
229 _ => None,
230 }
231 }
232 pub fn get_abuf_u8(&self) -> Option<NAAudioBuffer<u8>> {
233 match *self {
234 NABufferType::AudioU8(ref ab) => Some(ab.clone()),
235 NABufferType::AudioPacked(ref ab) => Some(ab.clone()),
236 _ => None,
237 }
238 }
239 pub fn get_abuf_i16(&self) -> Option<NAAudioBuffer<i16>> {
240 match *self {
241 NABufferType::AudioI16(ref ab) => Some(ab.clone()),
242 _ => None,
243 }
244 }
245 pub fn get_abuf_i32(&self) -> Option<NAAudioBuffer<i32>> {
246 match *self {
247 NABufferType::AudioI32(ref ab) => Some(ab.clone()),
248 _ => None,
249 }
250 }
251 pub fn get_abuf_f32(&self) -> Option<NAAudioBuffer<f32>> {
252 match *self {
253 NABufferType::AudioF32(ref ab) => Some(ab.clone()),
254 _ => None,
255 }
256 }
257 }
258
259 #[derive(Debug,Clone,Copy,PartialEq)]
260 pub enum AllocatorError {
261 TooLargeDimensions,
262 FormatError,
263 }
264
265 pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result<NABufferType, AllocatorError> {
266 let fmt = &vinfo.format;
267 let mut new_size: usize = 0;
268 let mut offs: Vec<usize> = Vec::new();
269 let mut strides: Vec<usize> = Vec::new();
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;
280 let mut all_bytealigned = true;
281 for i in 0..fmt.get_num_comp() {
282 let ochr = fmt.get_chromaton(i);
283 if let None = ochr { continue; }
284 let chr = ochr.unwrap();
285 if !chr.is_packed() {
286 all_packed = false;
287 } else if ((chr.get_shift() + chr.get_depth()) & 7) != 0 {
288 all_bytealigned = false;
289 }
290 max_depth = max(max_depth, chr.get_depth());
291 }
292 let unfit_elem_size = match fmt.get_elem_size() {
293 2 | 4 => false,
294 _ => true,
295 };
296
297 //todo semi-packed like NV12
298 if fmt.is_paletted() {
299 //todo various-sized palettes?
300 let stride = vinfo.get_format().get_chromaton(0).unwrap().get_linesize(width);
301 let pic_sz = stride.checked_mul(height);
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);
307 offs.push(stride * height);
308 strides.push(stride);
309 let mut data: Vec<u8> = Vec::with_capacity(new_size.unwrap());
310 data.resize(new_size.unwrap(), 0);
311 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
312 Ok(NABufferType::Video(buf))
313 } else if !all_packed {
314 for i in 0..fmt.get_num_comp() {
315 let ochr = fmt.get_chromaton(i);
316 if let None = ochr { continue; }
317 let chr = ochr.unwrap();
318 if !vinfo.is_flipped() {
319 offs.push(new_size as usize);
320 }
321 let stride = chr.get_linesize(width);
322 let cur_h = chr.get_height(height);
323 let cur_sz = stride.checked_mul(cur_h);
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 }
331 strides.push(stride);
332 }
333 if max_depth <= 8 {
334 let mut data: Vec<u8> = Vec::with_capacity(new_size);
335 data.resize(new_size, 0);
336 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
337 Ok(NABufferType::Video(buf))
338 } else if max_depth <= 16 {
339 let mut data: Vec<u16> = Vec::with_capacity(new_size);
340 data.resize(new_size, 0);
341 let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
342 Ok(NABufferType::Video16(buf))
343 } else {
344 let mut data: Vec<u32> = Vec::with_capacity(new_size);
345 data.resize(new_size, 0);
346 let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
347 Ok(NABufferType::Video32(buf))
348 }
349 } else if all_bytealigned || unfit_elem_size {
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);
358 strides.push(line_sz.unwrap());
359 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
360 Ok(NABufferType::VideoPacked(buf))
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);
371 let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
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);
378 let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides };
379 Ok(NABufferType::Video32(buf))
380 },
381 _ => unreachable!(),
382 }
383 }
384 }
385
386 pub fn alloc_audio_buffer(ainfo: NAAudioInfo, nsamples: usize, chmap: NAChannelMap) -> Result<NABufferType, AllocatorError> {
387 let mut offs: Vec<usize> = Vec::new();
388 if ainfo.format.is_planar() || (ainfo.channels == 1 && (ainfo.format.get_bits() % 8) == 0) {
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);
399 let buf: NAAudioBuffer<f32> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
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);
408 let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
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);
413 let buf: NAAudioBuffer<i16> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
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);
425 let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
426 Ok(NABufferType::AudioPacked(buf))
427 }
428 }
429
430 pub fn alloc_data_buffer(size: usize) -> Result<NABufferType, AllocatorError> {
431 let mut data: Vec<u8> = Vec::with_capacity(size);
432 data.resize(size, 0);
433 let buf: NABufferRef<Vec<u8>> = NABufferRef::new(data);
434 Ok(NABufferType::Data(buf))
435 }
436
437 pub fn copy_buffer(buf: NABufferType) -> NABufferType {
438 buf.clone()
439 }
440
441 pub struct NABufferPool {
442 pool: Vec<NABufferRef<NABufferType>>,
443 max_len: usize,
444 }
445
446 impl 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
487 #[allow(dead_code)]
488 #[derive(Clone)]
489 pub struct NACodecInfo {
490 name: &'static str,
491 properties: NACodecTypeInfo,
492 extradata: Option<Rc<Vec<u8>>>,
493 }
494
495 impl NACodecInfo {
496 pub fn new(name: &'static str, p: NACodecTypeInfo, edata: Option<Vec<u8>>) -> Self {
497 let extradata = match edata {
498 None => None,
499 Some(vec) => Some(Rc::new(vec)),
500 };
501 NACodecInfo { name: name, properties: p, extradata: extradata }
502 }
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 }
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
510 }
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 }
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 }
526 }
527
528 impl Default for NACodecInfo {
529 fn default() -> Self { DUMMY_CODEC_INFO }
530 }
531
532 impl 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
542 pub const DUMMY_CODEC_INFO: NACodecInfo = NACodecInfo {
543 name: "none",
544 properties: NACodecTypeInfo::None,
545 extradata: None };
546
547 #[derive(Debug,Clone)]
548 pub enum NAValue {
549 None,
550 Int(i32),
551 Long(i64),
552 String(String),
553 Data(Rc<Vec<u8>>),
554 }
555
556 #[derive(Debug,Clone,Copy,PartialEq)]
557 #[allow(dead_code)]
558 pub enum FrameType {
559 I,
560 P,
561 B,
562 Skip,
563 Other,
564 }
565
566 impl 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"),
572 FrameType::Skip => write!(f, "skip"),
573 FrameType::Other => write!(f, "x"),
574 }
575 }
576 }
577
578 #[derive(Debug,Clone,Copy)]
579 pub struct NATimeInfo {
580 pts: Option<u64>,
581 dts: Option<u64>,
582 duration: Option<u64>,
583 tb_num: u32,
584 tb_den: u32,
585 }
586
587 impl 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)]
601 pub struct NAFrame {
602 ts: NATimeInfo,
603 buffer: NABufferType,
604 info: Rc<NACodecInfo>,
605 ftype: FrameType,
606 key: bool,
607 options: HashMap<String, NAValue>,
608 }
609
610 pub type NAFrameRef = Rc<RefCell<NAFrame>>;
611
612 fn 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
621 impl NAFrame {
622 pub fn new(ts: NATimeInfo,
623 ftype: FrameType,
624 keyframe: bool,
625 info: Rc<NACodecInfo>,
626 options: HashMap<String, NAValue>,
627 buffer: NABufferType) -> Self {
628 NAFrame { ts: ts, buffer: buffer, info: info, ftype: ftype, key: keyframe, options: options }
629 }
630 pub fn get_info(&self) -> Rc<NACodecInfo> { self.info.clone() }
631 pub fn get_frame_type(&self) -> FrameType { self.ftype }
632 pub fn is_keyframe(&self) -> bool { self.key }
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; }
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); }
642
643 pub fn get_buffer(&self) -> NABufferType { self.buffer.clone() }
644 }
645
646 impl fmt::Display for NAFrame {
647 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
648 let mut foo = format!("frame type {}", self.ftype);
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); }
652 if self.key { foo = format!("{} kf", foo); }
653 write!(f, "[{}]", foo)
654 }
655 }
656
657 /// Possible stream types.
658 #[derive(Debug,Clone,Copy)]
659 #[allow(dead_code)]
660 pub 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
673 impl 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)]
687 pub struct NAStream {
688 media_type: StreamType,
689 id: u32,
690 num: usize,
691 info: Rc<NACodecInfo>,
692 tb_num: u32,
693 tb_den: u32,
694 }
695
696 pub 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)
709 }
710
711 impl NAStream {
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 }
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() }
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 }
726 }
727
728 impl fmt::Display for NAStream {
729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
730 write!(f, "({}#{} @ {}/{} - {})", self.media_type, self.id, self.tb_num, self.tb_den, self.info.get_properties())
731 }
732 }
733
734 #[allow(dead_code)]
735 pub struct NAPacket {
736 stream: Rc<NAStream>,
737 ts: NATimeInfo,
738 buffer: NABufferRef<Vec<u8>>,
739 keyframe: bool,
740 // options: HashMap<String, NAValue<'a>>,
741 }
742
743 impl NAPacket {
744 pub fn new(str: Rc<NAStream>, ts: NATimeInfo, kf: bool, vec: Vec<u8>) -> Self {
745 // let mut vec: Vec<u8> = Vec::new();
746 // vec.resize(size, 0);
747 NAPacket { stream: str, ts: ts, keyframe: kf, buffer: NABufferRef::new(vec) }
748 }
749 pub fn get_stream(&self) -> Rc<NAStream> { self.stream.clone() }
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() }
754 pub fn is_keyframe(&self) -> bool { self.keyframe }
755 pub fn get_buffer(&self) -> NABufferRef<Vec<u8>> { self.buffer.clone() }
756 }
757
758 impl Drop for NAPacket {
759 fn drop(&mut self) {}
760 }
761
762 impl 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());
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); }
768 if self.keyframe { foo = format!("{} kf", foo); }
769 foo = foo + "]";
770 write!(f, "{}", foo)
771 }
772 }
773
774 pub trait FrameFromPacket {
775 fn new_from_pkt(pkt: &NAPacket, info: Rc<NACodecInfo>, buf: NABufferType) -> NAFrame;
776 fn fill_timestamps(&mut self, pkt: &NAPacket);
777 }
778
779 impl FrameFromPacket for NAFrame {
780 fn new_from_pkt(pkt: &NAPacket, info: Rc<NACodecInfo>, buf: NABufferType) -> NAFrame {
781 NAFrame::new(pkt.ts, FrameType::Other, pkt.keyframe, info, HashMap::new(), buf)
782 }
783 fn fill_timestamps(&mut self, pkt: &NAPacket) {
784 self.ts = pkt.get_time_information();
785 }
786 }
787