frame: make get_vbuf() work for immutable refs
[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 Video32 (NAVideoBuffer<u32>),
181 VideoPacked(NAVideoBuffer<u8>),
182 AudioU8 (NAAudioBuffer<u8>),
183 AudioI16 (NAAudioBuffer<i16>),
184 AudioI32 (NAAudioBuffer<i32>),
185 AudioF32 (NAAudioBuffer<f32>),
186 AudioPacked(NAAudioBuffer<u8>),
187 Data (NABufferRefT<u8>),
188 None,
189 }
190
191 impl NABufferType {
192 pub fn get_offset(&self, idx: usize) -> usize {
193 match *self {
194 NABufferType::Video(ref vb) => vb.get_offset(idx),
195 NABufferType::Video16(ref vb) => vb.get_offset(idx),
196 NABufferType::Video32(ref vb) => vb.get_offset(idx),
197 NABufferType::VideoPacked(ref vb) => vb.get_offset(idx),
198 NABufferType::AudioU8(ref ab) => ab.get_offset(idx),
199 NABufferType::AudioI16(ref ab) => ab.get_offset(idx),
200 NABufferType::AudioF32(ref ab) => ab.get_offset(idx),
201 NABufferType::AudioPacked(ref ab) => ab.get_offset(idx),
202 _ => 0,
203 }
204 }
205 pub fn get_video_info(&self) -> Option<NAVideoInfo> {
206 match *self {
207 NABufferType::Video(ref vb) => Some(vb.get_info()),
208 NABufferType::Video16(ref vb) => Some(vb.get_info()),
209 NABufferType::Video32(ref vb) => Some(vb.get_info()),
210 NABufferType::VideoPacked(ref vb) => Some(vb.get_info()),
211 _ => None,
212 }
213 }
214 pub fn get_vbuf(&self) -> Option<NAVideoBuffer<u8>> {
215 match *self {
216 NABufferType::Video(ref vb) => Some(vb.clone()),
217 NABufferType::VideoPacked(ref vb) => Some(vb.clone()),
218 _ => None,
219 }
220 }
221 pub fn get_vbuf16(&self) -> Option<NAVideoBuffer<u16>> {
222 match *self {
223 NABufferType::Video16(ref vb) => Some(vb.clone()),
224 _ => None,
225 }
226 }
227 pub fn get_vbuf32(&self) -> Option<NAVideoBuffer<u32>> {
228 match *self {
229 NABufferType::Video32(ref vb) => Some(vb.clone()),
230 _ => None,
231 }
232 }
233 pub fn get_abuf_u8(&self) -> Option<NAAudioBuffer<u8>> {
234 match *self {
235 NABufferType::AudioU8(ref ab) => Some(ab.clone()),
236 NABufferType::AudioPacked(ref ab) => Some(ab.clone()),
237 _ => None,
238 }
239 }
240 pub fn get_abuf_i16(&self) -> Option<NAAudioBuffer<i16>> {
241 match *self {
242 NABufferType::AudioI16(ref ab) => Some(ab.clone()),
243 _ => None,
244 }
245 }
246 pub fn get_abuf_i32(&self) -> Option<NAAudioBuffer<i32>> {
247 match *self {
248 NABufferType::AudioI32(ref ab) => Some(ab.clone()),
249 _ => None,
250 }
251 }
252 pub fn get_abuf_f32(&self) -> Option<NAAudioBuffer<f32>> {
253 match *self {
254 NABufferType::AudioF32(ref ab) => Some(ab.clone()),
255 _ => None,
256 }
257 }
258 }
259
260 #[derive(Debug,Clone,Copy,PartialEq)]
261 pub enum AllocatorError {
262 TooLargeDimensions,
263 FormatError,
264 }
265
266 pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result<NABufferType, AllocatorError> {
267 let fmt = &vinfo.format;
268 let mut new_size: usize = 0;
269 let mut offs: Vec<usize> = Vec::new();
270 let mut strides: Vec<usize> = Vec::new();
271
272 for i in 0..fmt.get_num_comp() {
273 if fmt.get_chromaton(i) == None { return Err(AllocatorError::FormatError); }
274 }
275
276 let align_mod = ((1 << align) as usize) - 1;
277 let width = ((vinfo.width as usize) + align_mod) & !align_mod;
278 let height = ((vinfo.height as usize) + align_mod) & !align_mod;
279 let mut max_depth = 0;
280 let mut all_packed = true;
281 let mut all_bytealigned = true;
282 for i in 0..fmt.get_num_comp() {
283 let ochr = fmt.get_chromaton(i);
284 if let None = ochr { continue; }
285 let chr = ochr.unwrap();
286 if !chr.is_packed() {
287 all_packed = false;
288 } else if ((chr.get_shift() + chr.get_depth()) & 7) != 0 {
289 all_bytealigned = false;
290 }
291 max_depth = max(max_depth, chr.get_depth());
292 }
293 let unfit_elem_size = match fmt.get_elem_size() {
294 2 | 4 => false,
295 _ => true,
296 };
297
298 //todo semi-packed like NV12
299 if fmt.is_paletted() {
300 //todo various-sized palettes?
301 let stride = vinfo.get_format().get_chromaton(0).unwrap().get_linesize(width);
302 let pic_sz = stride.checked_mul(height);
303 if pic_sz == None { return Err(AllocatorError::TooLargeDimensions); }
304 let pal_size = 256 * (fmt.get_elem_size() as usize);
305 let new_size = pic_sz.unwrap().checked_add(pal_size);
306 if new_size == None { return Err(AllocatorError::TooLargeDimensions); }
307 offs.push(0);
308 offs.push(stride * height);
309 strides.push(stride);
310 let mut data: Vec<u8> = Vec::with_capacity(new_size.unwrap());
311 data.resize(new_size.unwrap(), 0);
312 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: Rc::new(RefCell::new(data)), info: vinfo, offs: offs, strides: strides };
313 Ok(NABufferType::Video(buf))
314 } else if !all_packed {
315 for i in 0..fmt.get_num_comp() {
316 let ochr = fmt.get_chromaton(i);
317 if let None = ochr { continue; }
318 let chr = ochr.unwrap();
319 if !vinfo.is_flipped() {
320 offs.push(new_size as usize);
321 }
322 let stride = chr.get_linesize(width);
323 let cur_h = chr.get_height(height);
324 let cur_sz = stride.checked_mul(cur_h);
325 if cur_sz == None { return Err(AllocatorError::TooLargeDimensions); }
326 let new_sz = new_size.checked_add(cur_sz.unwrap());
327 if new_sz == None { return Err(AllocatorError::TooLargeDimensions); }
328 new_size = new_sz.unwrap();
329 if vinfo.is_flipped() {
330 offs.push(new_size as usize);
331 }
332 strides.push(stride);
333 }
334 if max_depth <= 8 {
335 let mut data: Vec<u8> = Vec::with_capacity(new_size);
336 data.resize(new_size, 0);
337 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: Rc::new(RefCell::new(data)), info: vinfo, offs: offs, strides: strides };
338 Ok(NABufferType::Video(buf))
339 } else if max_depth <= 16 {
340 let mut data: Vec<u16> = Vec::with_capacity(new_size);
341 data.resize(new_size, 0);
342 let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: Rc::new(RefCell::new(data)), info: vinfo, offs: offs, strides: strides };
343 Ok(NABufferType::Video16(buf))
344 } else {
345 let mut data: Vec<u32> = Vec::with_capacity(new_size);
346 data.resize(new_size, 0);
347 let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: Rc::new(RefCell::new(data)), info: vinfo, offs: offs, strides: strides };
348 Ok(NABufferType::Video32(buf))
349 }
350 } else if all_bytealigned || unfit_elem_size {
351 let elem_sz = fmt.get_elem_size();
352 let line_sz = width.checked_mul(elem_sz as usize);
353 if line_sz == None { return Err(AllocatorError::TooLargeDimensions); }
354 let new_sz = line_sz.unwrap().checked_mul(height);
355 if new_sz == None { return Err(AllocatorError::TooLargeDimensions); }
356 new_size = new_sz.unwrap();
357 let mut data: Vec<u8> = Vec::with_capacity(new_size);
358 data.resize(new_size, 0);
359 strides.push(line_sz.unwrap());
360 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: Rc::new(RefCell::new(data)), info: vinfo, offs: offs, strides: strides };
361 Ok(NABufferType::VideoPacked(buf))
362 } else {
363 let elem_sz = fmt.get_elem_size();
364 let new_sz = width.checked_mul(height);
365 if new_sz == None { return Err(AllocatorError::TooLargeDimensions); }
366 new_size = new_sz.unwrap();
367 match elem_sz {
368 2 => {
369 let mut data: Vec<u16> = Vec::with_capacity(new_size);
370 data.resize(new_size, 0);
371 strides.push(width);
372 let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: Rc::new(RefCell::new(data)), info: vinfo, offs: offs, strides: strides };
373 Ok(NABufferType::Video16(buf))
374 },
375 4 => {
376 let mut data: Vec<u32> = Vec::with_capacity(new_size);
377 data.resize(new_size, 0);
378 strides.push(width);
379 let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: Rc::new(RefCell::new(data)), info: vinfo, offs: offs, strides: strides };
380 Ok(NABufferType::Video32(buf))
381 },
382 _ => unreachable!(),
383 }
384 }
385 }
386
387 pub fn alloc_audio_buffer(ainfo: NAAudioInfo, nsamples: usize, chmap: NAChannelMap) -> Result<NABufferType, AllocatorError> {
388 let mut offs: Vec<usize> = Vec::new();
389 if ainfo.format.is_planar() || (ainfo.channels == 1 && (ainfo.format.get_bits() % 8) == 0) {
390 let len = nsamples.checked_mul(ainfo.channels as usize);
391 if len == None { return Err(AllocatorError::TooLargeDimensions); }
392 let length = len.unwrap();
393 for i in 0..ainfo.channels {
394 offs.push((i as usize) * nsamples);
395 }
396 if ainfo.format.is_float() {
397 if ainfo.format.get_bits() == 32 {
398 let mut data: Vec<f32> = Vec::with_capacity(length);
399 data.resize(length, 0.0);
400 let buf: NAAudioBuffer<f32> = NAAudioBuffer { data: Rc::new(RefCell::new(data)), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
401 Ok(NABufferType::AudioF32(buf))
402 } else {
403 Err(AllocatorError::TooLargeDimensions)
404 }
405 } else {
406 if ainfo.format.get_bits() == 8 && !ainfo.format.is_signed() {
407 let mut data: Vec<u8> = Vec::with_capacity(length);
408 data.resize(length, 0);
409 let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: Rc::new(RefCell::new(data)), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
410 Ok(NABufferType::AudioU8(buf))
411 } else if ainfo.format.get_bits() == 16 && ainfo.format.is_signed() {
412 let mut data: Vec<i16> = Vec::with_capacity(length);
413 data.resize(length, 0);
414 let buf: NAAudioBuffer<i16> = NAAudioBuffer { data: Rc::new(RefCell::new(data)), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
415 Ok(NABufferType::AudioI16(buf))
416 } else {
417 Err(AllocatorError::TooLargeDimensions)
418 }
419 }
420 } else {
421 let len = nsamples.checked_mul(ainfo.channels as usize);
422 if len == None { return Err(AllocatorError::TooLargeDimensions); }
423 let length = ainfo.format.get_audio_size(len.unwrap() as u64);
424 let mut data: Vec<u8> = Vec::with_capacity(length);
425 data.resize(length, 0);
426 let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: Rc::new(RefCell::new(data)), info: ainfo, offs: offs, chmap: chmap, len: nsamples };
427 Ok(NABufferType::AudioPacked(buf))
428 }
429 }
430
431 pub fn alloc_data_buffer(size: usize) -> Result<NABufferType, AllocatorError> {
432 let mut data: Vec<u8> = Vec::with_capacity(size);
433 data.resize(size, 0);
434 let buf: NABufferRefT<u8> = Rc::new(RefCell::new(data));
435 Ok(NABufferType::Data(buf))
436 }
437
438 pub fn copy_buffer(buf: NABufferType) -> NABufferType {
439 buf.clone()
440 }
441
442 #[allow(dead_code)]
443 #[derive(Clone)]
444 pub struct NACodecInfo {
445 name: &'static str,
446 properties: NACodecTypeInfo,
447 extradata: Option<Rc<Vec<u8>>>,
448 }
449
450 impl NACodecInfo {
451 pub fn new(name: &'static str, p: NACodecTypeInfo, edata: Option<Vec<u8>>) -> Self {
452 let extradata = match edata {
453 None => None,
454 Some(vec) => Some(Rc::new(vec)),
455 };
456 NACodecInfo { name: name, properties: p, extradata: extradata }
457 }
458 pub fn new_ref(name: &'static str, p: NACodecTypeInfo, edata: Option<Rc<Vec<u8>>>) -> Self {
459 NACodecInfo { name: name, properties: p, extradata: edata }
460 }
461 pub fn get_properties(&self) -> NACodecTypeInfo { self.properties }
462 pub fn get_extradata(&self) -> Option<Rc<Vec<u8>>> {
463 if let Some(ref vec) = self.extradata { return Some(vec.clone()); }
464 None
465 }
466 pub fn get_name(&self) -> &'static str { self.name }
467 pub fn is_video(&self) -> bool {
468 if let NACodecTypeInfo::Video(_) = self.properties { return true; }
469 false
470 }
471 pub fn is_audio(&self) -> bool {
472 if let NACodecTypeInfo::Audio(_) = self.properties { return true; }
473 false
474 }
475 pub fn new_dummy() -> Rc<Self> {
476 Rc::new(DUMMY_CODEC_INFO)
477 }
478 pub fn replace_info(&self, p: NACodecTypeInfo) -> Rc<Self> {
479 Rc::new(NACodecInfo { name: self.name, properties: p, extradata: self.extradata.clone() })
480 }
481 }
482
483 impl Default for NACodecInfo {
484 fn default() -> Self { DUMMY_CODEC_INFO }
485 }
486
487 impl fmt::Display for NACodecInfo {
488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489 let edata = match self.extradata.clone() {
490 None => format!("no extradata"),
491 Some(v) => format!("{} byte(s) of extradata", v.len()),
492 };
493 write!(f, "{}: {} {}", self.name, self.properties, edata)
494 }
495 }
496
497 pub const DUMMY_CODEC_INFO: NACodecInfo = NACodecInfo {
498 name: "none",
499 properties: NACodecTypeInfo::None,
500 extradata: None };
501
502 #[derive(Debug,Clone)]
503 pub enum NAValue {
504 None,
505 Int(i32),
506 Long(i64),
507 String(String),
508 Data(Rc<Vec<u8>>),
509 }
510
511 #[derive(Debug,Clone,Copy,PartialEq)]
512 #[allow(dead_code)]
513 pub enum FrameType {
514 I,
515 P,
516 B,
517 Skip,
518 Other,
519 }
520
521 impl fmt::Display for FrameType {
522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
523 match *self {
524 FrameType::I => write!(f, "I"),
525 FrameType::P => write!(f, "P"),
526 FrameType::B => write!(f, "B"),
527 FrameType::Skip => write!(f, "skip"),
528 FrameType::Other => write!(f, "x"),
529 }
530 }
531 }
532
533 #[derive(Debug,Clone,Copy)]
534 pub struct NATimeInfo {
535 pts: Option<u64>,
536 dts: Option<u64>,
537 duration: Option<u64>,
538 tb_num: u32,
539 tb_den: u32,
540 }
541
542 impl NATimeInfo {
543 pub fn new(pts: Option<u64>, dts: Option<u64>, duration: Option<u64>, tb_num: u32, tb_den: u32) -> Self {
544 NATimeInfo { pts: pts, dts: dts, duration: duration, tb_num: tb_num, tb_den: tb_den }
545 }
546 pub fn get_pts(&self) -> Option<u64> { self.pts }
547 pub fn get_dts(&self) -> Option<u64> { self.dts }
548 pub fn get_duration(&self) -> Option<u64> { self.duration }
549 pub fn set_pts(&mut self, pts: Option<u64>) { self.pts = pts; }
550 pub fn set_dts(&mut self, dts: Option<u64>) { self.dts = dts; }
551 pub fn set_duration(&mut self, dur: Option<u64>) { self.duration = dur; }
552 }
553
554 #[allow(dead_code)]
555 #[derive(Clone)]
556 pub struct NAFrame {
557 ts: NATimeInfo,
558 buffer: NABufferType,
559 info: Rc<NACodecInfo>,
560 ftype: FrameType,
561 key: bool,
562 options: HashMap<String, NAValue>,
563 }
564
565 pub type NAFrameRef = Rc<RefCell<NAFrame>>;
566
567 fn get_plane_size(info: &NAVideoInfo, idx: usize) -> (usize, usize) {
568 let chromaton = info.get_format().get_chromaton(idx);
569 if let None = chromaton { return (0, 0); }
570 let (hs, vs) = chromaton.unwrap().get_subsampling();
571 let w = (info.get_width() + ((1 << hs) - 1)) >> hs;
572 let h = (info.get_height() + ((1 << vs) - 1)) >> vs;
573 (w, h)
574 }
575
576 impl NAFrame {
577 pub fn new(ts: NATimeInfo,
578 ftype: FrameType,
579 keyframe: bool,
580 info: Rc<NACodecInfo>,
581 options: HashMap<String, NAValue>,
582 buffer: NABufferType) -> Self {
583 NAFrame { ts: ts, buffer: buffer, info: info, ftype: ftype, key: keyframe, options: options }
584 }
585 pub fn get_info(&self) -> Rc<NACodecInfo> { self.info.clone() }
586 pub fn get_frame_type(&self) -> FrameType { self.ftype }
587 pub fn is_keyframe(&self) -> bool { self.key }
588 pub fn set_frame_type(&mut self, ftype: FrameType) { self.ftype = ftype; }
589 pub fn set_keyframe(&mut self, key: bool) { self.key = key; }
590 pub fn get_time_information(&self) -> NATimeInfo { self.ts }
591 pub fn get_pts(&self) -> Option<u64> { self.ts.get_pts() }
592 pub fn get_dts(&self) -> Option<u64> { self.ts.get_dts() }
593 pub fn get_duration(&self) -> Option<u64> { self.ts.get_duration() }
594 pub fn set_pts(&mut self, pts: Option<u64>) { self.ts.set_pts(pts); }
595 pub fn set_dts(&mut self, dts: Option<u64>) { self.ts.set_dts(dts); }
596 pub fn set_duration(&mut self, dur: Option<u64>) { self.ts.set_duration(dur); }
597
598 pub fn get_buffer(&self) -> NABufferType { self.buffer.clone() }
599 }
600
601 impl fmt::Display for NAFrame {
602 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
603 let mut foo = format!("frame type {}", self.ftype);
604 if let Some(pts) = self.ts.pts { foo = format!("{} pts {}", foo, pts); }
605 if let Some(dts) = self.ts.dts { foo = format!("{} dts {}", foo, dts); }
606 if let Some(dur) = self.ts.duration { foo = format!("{} duration {}", foo, dur); }
607 if self.key { foo = format!("{} kf", foo); }
608 write!(f, "[{}]", foo)
609 }
610 }
611
612 /// Possible stream types.
613 #[derive(Debug,Clone,Copy)]
614 #[allow(dead_code)]
615 pub enum StreamType {
616 /// video stream
617 Video,
618 /// audio stream
619 Audio,
620 /// subtitles
621 Subtitles,
622 /// any data stream (or might be an unrecognized audio/video stream)
623 Data,
624 /// nonexistent stream
625 None,
626 }
627
628 impl fmt::Display for StreamType {
629 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
630 match *self {
631 StreamType::Video => write!(f, "Video"),
632 StreamType::Audio => write!(f, "Audio"),
633 StreamType::Subtitles => write!(f, "Subtitles"),
634 StreamType::Data => write!(f, "Data"),
635 StreamType::None => write!(f, "-"),
636 }
637 }
638 }
639
640 #[allow(dead_code)]
641 #[derive(Clone)]
642 pub struct NAStream {
643 media_type: StreamType,
644 id: u32,
645 num: usize,
646 info: Rc<NACodecInfo>,
647 tb_num: u32,
648 tb_den: u32,
649 }
650
651 pub fn reduce_timebase(tb_num: u32, tb_den: u32) -> (u32, u32) {
652 if tb_num == 0 { return (tb_num, tb_den); }
653 if (tb_den % tb_num) == 0 { return (1, tb_den / tb_num); }
654
655 let mut a = tb_num;
656 let mut b = tb_den;
657
658 while a != b {
659 if a > b { a -= b; }
660 else if b > a { b -= a; }
661 }
662
663 (tb_num / a, tb_den / a)
664 }
665
666 impl NAStream {
667 pub fn new(mt: StreamType, id: u32, info: NACodecInfo, tb_num: u32, tb_den: u32) -> Self {
668 let (n, d) = reduce_timebase(tb_num, tb_den);
669 NAStream { media_type: mt, id: id, num: 0, info: Rc::new(info), tb_num: n, tb_den: d }
670 }
671 pub fn get_id(&self) -> u32 { self.id }
672 pub fn get_num(&self) -> usize { self.num }
673 pub fn set_num(&mut self, num: usize) { self.num = num; }
674 pub fn get_info(&self) -> Rc<NACodecInfo> { self.info.clone() }
675 pub fn get_timebase(&self) -> (u32, u32) { (self.tb_num, self.tb_den) }
676 pub fn set_timebase(&mut self, tb_num: u32, tb_den: u32) {
677 let (n, d) = reduce_timebase(tb_num, tb_den);
678 self.tb_num = n;
679 self.tb_den = d;
680 }
681 }
682
683 impl fmt::Display for NAStream {
684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
685 write!(f, "({}#{} @ {}/{} - {})", self.media_type, self.id, self.tb_num, self.tb_den, self.info.get_properties())
686 }
687 }
688
689 #[allow(dead_code)]
690 pub struct NAPacket {
691 stream: Rc<NAStream>,
692 ts: NATimeInfo,
693 buffer: Rc<Vec<u8>>,
694 keyframe: bool,
695 // options: HashMap<String, NAValue<'a>>,
696 }
697
698 impl NAPacket {
699 pub fn new(str: Rc<NAStream>, ts: NATimeInfo, kf: bool, vec: Vec<u8>) -> Self {
700 // let mut vec: Vec<u8> = Vec::new();
701 // vec.resize(size, 0);
702 NAPacket { stream: str, ts: ts, keyframe: kf, buffer: Rc::new(vec) }
703 }
704 pub fn get_stream(&self) -> Rc<NAStream> { self.stream.clone() }
705 pub fn get_time_information(&self) -> NATimeInfo { self.ts }
706 pub fn get_pts(&self) -> Option<u64> { self.ts.get_pts() }
707 pub fn get_dts(&self) -> Option<u64> { self.ts.get_dts() }
708 pub fn get_duration(&self) -> Option<u64> { self.ts.get_duration() }
709 pub fn is_keyframe(&self) -> bool { self.keyframe }
710 pub fn get_buffer(&self) -> Rc<Vec<u8>> { self.buffer.clone() }
711 }
712
713 impl Drop for NAPacket {
714 fn drop(&mut self) {}
715 }
716
717 impl fmt::Display for NAPacket {
718 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
719 let mut foo = format!("[pkt for {} size {}", self.stream, self.buffer.len());
720 if let Some(pts) = self.ts.pts { foo = format!("{} pts {}", foo, pts); }
721 if let Some(dts) = self.ts.dts { foo = format!("{} dts {}", foo, dts); }
722 if let Some(dur) = self.ts.duration { foo = format!("{} duration {}", foo, dur); }
723 if self.keyframe { foo = format!("{} kf", foo); }
724 foo = foo + "]";
725 write!(f, "{}", foo)
726 }
727 }
728
729 pub trait FrameFromPacket {
730 fn new_from_pkt(pkt: &NAPacket, info: Rc<NACodecInfo>, buf: NABufferType) -> NAFrame;
731 fn fill_timestamps(&mut self, pkt: &NAPacket);
732 }
733
734 impl FrameFromPacket for NAFrame {
735 fn new_from_pkt(pkt: &NAPacket, info: Rc<NACodecInfo>, buf: NABufferType) -> NAFrame {
736 NAFrame::new(pkt.ts, FrameType::Other, pkt.keyframe, info, HashMap::new(), buf)
737 }
738 fn fill_timestamps(&mut self, pkt: &NAPacket) {
739 self.ts = pkt.get_time_information();
740 }
741 }
742