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