vp3: codec outputs flipped frames
[nihav.git] / nihav-core / src / frame.rs
CommitLineData
22cb00db 1use std::cmp::max;
5869fd63 2use std::collections::HashMap;
83e603fa 3use std::fmt;
2422d969 4use std::sync::Arc;
4e8b4f31 5pub use crate::formats::*;
1a967e6b 6pub use crate::refs::*;
94dbb551 7
5869fd63 8#[allow(dead_code)]
66116504 9#[derive(Clone,Copy,PartialEq)]
5869fd63 10pub struct NAAudioInfo {
df159213
KS
11 pub sample_rate: u32,
12 pub channels: u8,
13 pub format: NASoniton,
14 pub block_len: usize,
5869fd63
KS
15}
16
17impl 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 }
66116504
KS
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 }
5869fd63
KS
25}
26
83e603fa
KS
27impl 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
5869fd63 33#[allow(dead_code)]
66116504 34#[derive(Clone,Copy,PartialEq)]
5869fd63 35pub struct NAVideoInfo {
66116504
KS
36 width: usize,
37 height: usize,
5869fd63
KS
38 flipped: bool,
39 format: NAPixelFormaton,
40}
41
42impl NAVideoInfo {
66116504 43 pub fn new(w: usize, h: usize, flip: bool, fmt: NAPixelFormaton) -> Self {
5869fd63
KS
44 NAVideoInfo { width: w, height: h, flipped: flip, format: fmt }
45 }
66116504
KS
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 }
dd1b60e1
KS
50 pub fn set_width(&mut self, w: usize) { self.width = w; }
51 pub fn set_height(&mut self, h: usize) { self.height = h; }
5869fd63
KS
52}
53
83e603fa
KS
54impl 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
66116504 60#[derive(Clone,Copy,PartialEq)]
5869fd63
KS
61pub enum NACodecTypeInfo {
62 None,
63 Audio(NAAudioInfo),
64 Video(NAVideoInfo),
65}
66
22cb00db
KS
67impl 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 }
5076115b
KS
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 }
22cb00db
KS
92}
93
83e603fa
KS
94impl fmt::Display for NACodecTypeInfo {
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 let ret = match *self {
e243ceb4 97 NACodecTypeInfo::None => "".to_string(),
83e603fa
KS
98 NACodecTypeInfo::Audio(fmt) => format!("{}", fmt),
99 NACodecTypeInfo::Video(fmt) => format!("{}", fmt),
100 };
101 write!(f, "{}", ret)
102 }
103}
104
22cb00db
KS
105#[derive(Clone)]
106pub struct NAVideoBuffer<T> {
6c8e5c40 107 info: NAVideoInfo,
1a967e6b 108 data: NABufferRef<Vec<T>>,
6c8e5c40
KS
109 offs: Vec<usize>,
110 strides: Vec<usize>,
22cb00db
KS
111}
112
113impl<T: Clone> NAVideoBuffer<T> {
114 pub fn get_offset(&self, idx: usize) -> usize {
115 if idx >= self.offs.len() { 0 }
116 else { self.offs[idx] }
117 }
118 pub fn get_info(&self) -> NAVideoInfo { self.info }
1a967e6b
KS
119 pub fn get_data(&self) -> &Vec<T> { self.data.as_ref() }
120 pub fn get_data_mut(&mut self) -> Option<&mut Vec<T>> { self.data.as_mut() }
22cb00db 121 pub fn copy_buffer(&mut self) -> Self {
1a967e6b
KS
122 let mut data: Vec<T> = Vec::with_capacity(self.data.len());
123 data.clone_from(self.data.as_ref());
22cb00db
KS
124 let mut offs: Vec<usize> = Vec::with_capacity(self.offs.len());
125 offs.clone_from(&self.offs);
6c8e5c40
KS
126 let mut strides: Vec<usize> = Vec::with_capacity(self.strides.len());
127 strides.clone_from(&self.strides);
e243ceb4 128 NAVideoBuffer { info: self.info, data: NABufferRef::new(data), offs, strides }
22cb00db
KS
129 }
130 pub fn get_stride(&self, idx: usize) -> usize {
6c8e5c40
KS
131 if idx >= self.strides.len() { return 0; }
132 self.strides[idx]
22cb00db
KS
133 }
134 pub fn get_dimensions(&self, idx: usize) -> (usize, usize) {
135 get_plane_size(&self.info, idx)
136 }
3fc28ece
KS
137 pub fn into_ref(self) -> NABufferRef<Self> {
138 NABufferRef::new(self)
139 }
22cb00db
KS
140}
141
3fc28ece
KS
142pub type NAVideoBufferRef<T> = NABufferRef<NAVideoBuffer<T>>;
143
22cb00db
KS
144#[derive(Clone)]
145pub struct NAAudioBuffer<T> {
146 info: NAAudioInfo,
1a967e6b 147 data: NABufferRef<Vec<T>>,
22cb00db 148 offs: Vec<usize>,
01e2d496 149 stride: usize,
22cb00db 150 chmap: NAChannelMap,
5076115b 151 len: usize,
22cb00db
KS
152}
153
154impl<T: Clone> NAAudioBuffer<T> {
155 pub fn get_offset(&self, idx: usize) -> usize {
156 if idx >= self.offs.len() { 0 }
157 else { self.offs[idx] }
158 }
01e2d496 159 pub fn get_stride(&self) -> usize { self.stride }
22cb00db 160 pub fn get_info(&self) -> NAAudioInfo { self.info }
8ee4352b 161 pub fn get_chmap(&self) -> &NAChannelMap { &self.chmap }
1a967e6b
KS
162 pub fn get_data(&self) -> &Vec<T> { self.data.as_ref() }
163 pub fn get_data_mut(&mut self) -> Option<&mut Vec<T>> { self.data.as_mut() }
22cb00db 164 pub fn copy_buffer(&mut self) -> Self {
1a967e6b
KS
165 let mut data: Vec<T> = Vec::with_capacity(self.data.len());
166 data.clone_from(self.data.as_ref());
22cb00db
KS
167 let mut offs: Vec<usize> = Vec::with_capacity(self.offs.len());
168 offs.clone_from(&self.offs);
8ee4352b 169 NAAudioBuffer { info: self.info, data: NABufferRef::new(data), offs, chmap: self.get_chmap().clone(), len: self.len, stride: self.stride }
22cb00db 170 }
5076115b 171 pub fn get_length(&self) -> usize { self.len }
22cb00db
KS
172}
173
87a1ebc3 174impl NAAudioBuffer<u8> {
1a967e6b
KS
175 pub fn new_from_buf(info: NAAudioInfo, data: NABufferRef<Vec<u8>>, chmap: NAChannelMap) -> Self {
176 let len = data.len();
01e2d496 177 NAAudioBuffer { info, data, chmap, offs: Vec::new(), len, stride: 0 }
87a1ebc3
KS
178 }
179}
180
22cb00db
KS
181#[derive(Clone)]
182pub enum NABufferType {
3fc28ece
KS
183 Video (NAVideoBufferRef<u8>),
184 Video16 (NAVideoBufferRef<u16>),
185 Video32 (NAVideoBufferRef<u32>),
186 VideoPacked(NAVideoBufferRef<u8>),
22cb00db
KS
187 AudioU8 (NAAudioBuffer<u8>),
188 AudioI16 (NAAudioBuffer<i16>),
87a1ebc3 189 AudioI32 (NAAudioBuffer<i32>),
22cb00db
KS
190 AudioF32 (NAAudioBuffer<f32>),
191 AudioPacked(NAAudioBuffer<u8>),
1a967e6b 192 Data (NABufferRef<Vec<u8>>),
22cb00db
KS
193 None,
194}
195
196impl NABufferType {
197 pub fn get_offset(&self, idx: usize) -> usize {
198 match *self {
199 NABufferType::Video(ref vb) => vb.get_offset(idx),
200 NABufferType::Video16(ref vb) => vb.get_offset(idx),
3bba1c4a 201 NABufferType::Video32(ref vb) => vb.get_offset(idx),
22cb00db
KS
202 NABufferType::VideoPacked(ref vb) => vb.get_offset(idx),
203 NABufferType::AudioU8(ref ab) => ab.get_offset(idx),
204 NABufferType::AudioI16(ref ab) => ab.get_offset(idx),
205 NABufferType::AudioF32(ref ab) => ab.get_offset(idx),
206 NABufferType::AudioPacked(ref ab) => ab.get_offset(idx),
207 _ => 0,
208 }
209 }
3bba1c4a
KS
210 pub fn get_video_info(&self) -> Option<NAVideoInfo> {
211 match *self {
212 NABufferType::Video(ref vb) => Some(vb.get_info()),
213 NABufferType::Video16(ref vb) => Some(vb.get_info()),
214 NABufferType::Video32(ref vb) => Some(vb.get_info()),
215 NABufferType::VideoPacked(ref vb) => Some(vb.get_info()),
216 _ => None,
217 }
218 }
3fc28ece 219 pub fn get_vbuf(&self) -> Option<NAVideoBufferRef<u8>> {
22cb00db
KS
220 match *self {
221 NABufferType::Video(ref vb) => Some(vb.clone()),
87a1ebc3
KS
222 NABufferType::VideoPacked(ref vb) => Some(vb.clone()),
223 _ => None,
224 }
225 }
3fc28ece 226 pub fn get_vbuf16(&self) -> Option<NAVideoBufferRef<u16>> {
87a1ebc3
KS
227 match *self {
228 NABufferType::Video16(ref vb) => Some(vb.clone()),
229 _ => None,
230 }
231 }
3fc28ece 232 pub fn get_vbuf32(&self) -> Option<NAVideoBufferRef<u32>> {
3bba1c4a
KS
233 match *self {
234 NABufferType::Video32(ref vb) => Some(vb.clone()),
235 _ => None,
236 }
237 }
049474a0
KS
238 pub fn get_audio_info(&self) -> Option<NAAudioInfo> {
239 match *self {
240 NABufferType::AudioU8(ref ab) => Some(ab.get_info()),
241 NABufferType::AudioI16(ref ab) => Some(ab.get_info()),
242 NABufferType::AudioI32(ref ab) => Some(ab.get_info()),
243 NABufferType::AudioF32(ref ab) => Some(ab.get_info()),
244 NABufferType::AudioPacked(ref ab) => Some(ab.get_info()),
245 _ => None,
246 }
247 }
248 pub fn get_chmap(&self) -> Option<&NAChannelMap> {
249 match *self {
250 NABufferType::AudioU8(ref ab) => Some(ab.get_chmap()),
251 NABufferType::AudioI16(ref ab) => Some(ab.get_chmap()),
252 NABufferType::AudioI32(ref ab) => Some(ab.get_chmap()),
253 NABufferType::AudioF32(ref ab) => Some(ab.get_chmap()),
254 NABufferType::AudioPacked(ref ab) => Some(ab.get_chmap()),
255 _ => None,
256 }
257 }
258 pub fn get_audio_length(&self) -> usize {
259 match *self {
260 NABufferType::AudioU8(ref ab) => ab.get_length(),
261 NABufferType::AudioI16(ref ab) => ab.get_length(),
262 NABufferType::AudioI32(ref ab) => ab.get_length(),
263 NABufferType::AudioF32(ref ab) => ab.get_length(),
264 NABufferType::AudioPacked(ref ab) => ab.get_length(),
265 _ => 0,
266 }
267 }
268 pub fn get_audio_stride(&self) -> usize {
269 match *self {
270 NABufferType::AudioU8(ref ab) => ab.get_stride(),
271 NABufferType::AudioI16(ref ab) => ab.get_stride(),
272 NABufferType::AudioI32(ref ab) => ab.get_stride(),
273 NABufferType::AudioF32(ref ab) => ab.get_stride(),
274 NABufferType::AudioPacked(ref ab) => ab.get_stride(),
275 _ => 0,
276 }
277 }
6e09a92e 278 pub fn get_abuf_u8(&self) -> Option<NAAudioBuffer<u8>> {
87a1ebc3
KS
279 match *self {
280 NABufferType::AudioU8(ref ab) => Some(ab.clone()),
281 NABufferType::AudioPacked(ref ab) => Some(ab.clone()),
282 _ => None,
283 }
284 }
6e09a92e 285 pub fn get_abuf_i16(&self) -> Option<NAAudioBuffer<i16>> {
87a1ebc3
KS
286 match *self {
287 NABufferType::AudioI16(ref ab) => Some(ab.clone()),
288 _ => None,
289 }
290 }
6e09a92e 291 pub fn get_abuf_i32(&self) -> Option<NAAudioBuffer<i32>> {
87a1ebc3
KS
292 match *self {
293 NABufferType::AudioI32(ref ab) => Some(ab.clone()),
294 _ => None,
295 }
296 }
6e09a92e 297 pub fn get_abuf_f32(&self) -> Option<NAAudioBuffer<f32>> {
87a1ebc3
KS
298 match *self {
299 NABufferType::AudioF32(ref ab) => Some(ab.clone()),
22cb00db
KS
300 _ => None,
301 }
302 }
303}
304
cd830591
KS
305const NA_SIMPLE_VFRAME_COMPONENTS: usize = 4;
306pub struct NASimpleVideoFrame<'a, T: Copy> {
307 pub width: [usize; NA_SIMPLE_VFRAME_COMPONENTS],
308 pub height: [usize; NA_SIMPLE_VFRAME_COMPONENTS],
309 pub flip: bool,
310 pub stride: [usize; NA_SIMPLE_VFRAME_COMPONENTS],
311 pub offset: [usize; NA_SIMPLE_VFRAME_COMPONENTS],
312 pub components: usize,
dc45d8ce 313 pub data: &'a mut [T],
cd830591
KS
314}
315
316impl<'a, T:Copy> NASimpleVideoFrame<'a, T> {
317 pub fn from_video_buf(vbuf: &'a mut NAVideoBuffer<T>) -> Option<Self> {
318 let vinfo = vbuf.get_info();
319 let components = vinfo.format.components as usize;
320 if components > NA_SIMPLE_VFRAME_COMPONENTS {
321 return None;
322 }
323 let mut w: [usize; NA_SIMPLE_VFRAME_COMPONENTS] = [0; NA_SIMPLE_VFRAME_COMPONENTS];
324 let mut h: [usize; NA_SIMPLE_VFRAME_COMPONENTS] = [0; NA_SIMPLE_VFRAME_COMPONENTS];
325 let mut s: [usize; NA_SIMPLE_VFRAME_COMPONENTS] = [0; NA_SIMPLE_VFRAME_COMPONENTS];
326 let mut o: [usize; NA_SIMPLE_VFRAME_COMPONENTS] = [0; NA_SIMPLE_VFRAME_COMPONENTS];
327 for comp in 0..components {
328 let (width, height) = vbuf.get_dimensions(comp);
329 w[comp] = width;
330 h[comp] = height;
331 s[comp] = vbuf.get_stride(comp);
332 o[comp] = vbuf.get_offset(comp);
333 }
334 let flip = vinfo.flipped;
335 Some(NASimpleVideoFrame {
336 width: w,
337 height: h,
338 flip,
339 stride: s,
340 offset: o,
341 components,
dc45d8ce 342 data: vbuf.data.as_mut_slice(),
cd830591
KS
343 })
344 }
345}
346
22cb00db
KS
347#[derive(Debug,Clone,Copy,PartialEq)]
348pub enum AllocatorError {
349 TooLargeDimensions,
350 FormatError,
351}
352
353pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result<NABufferType, AllocatorError> {
354 let fmt = &vinfo.format;
355 let mut new_size: usize = 0;
6c8e5c40
KS
356 let mut offs: Vec<usize> = Vec::new();
357 let mut strides: Vec<usize> = Vec::new();
22cb00db
KS
358
359 for i in 0..fmt.get_num_comp() {
360 if fmt.get_chromaton(i) == None { return Err(AllocatorError::FormatError); }
361 }
362
363 let align_mod = ((1 << align) as usize) - 1;
364 let width = ((vinfo.width as usize) + align_mod) & !align_mod;
365 let height = ((vinfo.height as usize) + align_mod) & !align_mod;
366 let mut max_depth = 0;
367 let mut all_packed = true;
3bba1c4a 368 let mut all_bytealigned = true;
22cb00db 369 for i in 0..fmt.get_num_comp() {
6c8e5c40 370 let ochr = fmt.get_chromaton(i);
e243ceb4 371 if ochr.is_none() { continue; }
6c8e5c40 372 let chr = ochr.unwrap();
22cb00db
KS
373 if !chr.is_packed() {
374 all_packed = false;
3bba1c4a
KS
375 } else if ((chr.get_shift() + chr.get_depth()) & 7) != 0 {
376 all_bytealigned = false;
22cb00db
KS
377 }
378 max_depth = max(max_depth, chr.get_depth());
379 }
3bba1c4a
KS
380 let unfit_elem_size = match fmt.get_elem_size() {
381 2 | 4 => false,
382 _ => true,
383 };
22cb00db
KS
384
385//todo semi-packed like NV12
bc6aac3d
KS
386 if fmt.is_paletted() {
387//todo various-sized palettes?
6c8e5c40
KS
388 let stride = vinfo.get_format().get_chromaton(0).unwrap().get_linesize(width);
389 let pic_sz = stride.checked_mul(height);
bc6aac3d
KS
390 if pic_sz == None { return Err(AllocatorError::TooLargeDimensions); }
391 let pal_size = 256 * (fmt.get_elem_size() as usize);
392 let new_size = pic_sz.unwrap().checked_add(pal_size);
393 if new_size == None { return Err(AllocatorError::TooLargeDimensions); }
394 offs.push(0);
6c8e5c40
KS
395 offs.push(stride * height);
396 strides.push(stride);
e243ceb4
KS
397 let data: Vec<u8> = vec![0; new_size.unwrap()];
398 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides };
3fc28ece 399 Ok(NABufferType::Video(buf.into_ref()))
bc6aac3d 400 } else if !all_packed {
22cb00db 401 for i in 0..fmt.get_num_comp() {
6c8e5c40 402 let ochr = fmt.get_chromaton(i);
e243ceb4 403 if ochr.is_none() { continue; }
6c8e5c40 404 let chr = ochr.unwrap();
74afc7de 405 offs.push(new_size as usize);
6c8e5c40 406 let stride = chr.get_linesize(width);
22cb00db 407 let cur_h = chr.get_height(height);
6c8e5c40 408 let cur_sz = stride.checked_mul(cur_h);
22cb00db
KS
409 if cur_sz == None { return Err(AllocatorError::TooLargeDimensions); }
410 let new_sz = new_size.checked_add(cur_sz.unwrap());
411 if new_sz == None { return Err(AllocatorError::TooLargeDimensions); }
412 new_size = new_sz.unwrap();
6c8e5c40 413 strides.push(stride);
22cb00db
KS
414 }
415 if max_depth <= 8 {
e243ceb4
KS
416 let data: Vec<u8> = vec![0; new_size];
417 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides };
3fc28ece 418 Ok(NABufferType::Video(buf.into_ref()))
3bba1c4a 419 } else if max_depth <= 16 {
e243ceb4
KS
420 let data: Vec<u16> = vec![0; new_size];
421 let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides };
3fc28ece 422 Ok(NABufferType::Video16(buf.into_ref()))
3bba1c4a 423 } else {
e243ceb4
KS
424 let data: Vec<u32> = vec![0; new_size];
425 let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides };
3fc28ece 426 Ok(NABufferType::Video32(buf.into_ref()))
22cb00db 427 }
3bba1c4a 428 } else if all_bytealigned || unfit_elem_size {
22cb00db
KS
429 let elem_sz = fmt.get_elem_size();
430 let line_sz = width.checked_mul(elem_sz as usize);
431 if line_sz == None { return Err(AllocatorError::TooLargeDimensions); }
432 let new_sz = line_sz.unwrap().checked_mul(height);
433 if new_sz == None { return Err(AllocatorError::TooLargeDimensions); }
434 new_size = new_sz.unwrap();
e243ceb4 435 let data: Vec<u8> = vec![0; new_size];
6c8e5c40 436 strides.push(line_sz.unwrap());
e243ceb4 437 let buf: NAVideoBuffer<u8> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides };
3fc28ece 438 Ok(NABufferType::VideoPacked(buf.into_ref()))
3bba1c4a
KS
439 } else {
440 let elem_sz = fmt.get_elem_size();
441 let new_sz = width.checked_mul(height);
442 if new_sz == None { return Err(AllocatorError::TooLargeDimensions); }
443 new_size = new_sz.unwrap();
444 match elem_sz {
445 2 => {
e243ceb4 446 let data: Vec<u16> = vec![0; new_size];
3bba1c4a 447 strides.push(width);
e243ceb4 448 let buf: NAVideoBuffer<u16> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides };
3fc28ece 449 Ok(NABufferType::Video16(buf.into_ref()))
3bba1c4a
KS
450 },
451 4 => {
e243ceb4 452 let data: Vec<u32> = vec![0; new_size];
3bba1c4a 453 strides.push(width);
e243ceb4 454 let buf: NAVideoBuffer<u32> = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides };
3fc28ece 455 Ok(NABufferType::Video32(buf.into_ref()))
3bba1c4a
KS
456 },
457 _ => unreachable!(),
458 }
22cb00db
KS
459 }
460}
461
e243ceb4 462#[allow(clippy::collapsible_if)]
22cb00db
KS
463pub fn alloc_audio_buffer(ainfo: NAAudioInfo, nsamples: usize, chmap: NAChannelMap) -> Result<NABufferType, AllocatorError> {
464 let mut offs: Vec<usize> = Vec::new();
4c6c19cb 465 if ainfo.format.is_planar() || (ainfo.channels == 1 && (ainfo.format.get_bits() % 8) == 0) {
22cb00db
KS
466 let len = nsamples.checked_mul(ainfo.channels as usize);
467 if len == None { return Err(AllocatorError::TooLargeDimensions); }
468 let length = len.unwrap();
01e2d496 469 let stride = nsamples;
22cb00db 470 for i in 0..ainfo.channels {
01e2d496 471 offs.push((i as usize) * stride);
22cb00db
KS
472 }
473 if ainfo.format.is_float() {
474 if ainfo.format.get_bits() == 32 {
e243ceb4 475 let data: Vec<f32> = vec![0.0; length];
01e2d496 476 let buf: NAAudioBuffer<f32> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples, stride };
22cb00db
KS
477 Ok(NABufferType::AudioF32(buf))
478 } else {
479 Err(AllocatorError::TooLargeDimensions)
480 }
481 } else {
482 if ainfo.format.get_bits() == 8 && !ainfo.format.is_signed() {
e243ceb4 483 let data: Vec<u8> = vec![0; length];
01e2d496 484 let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples, stride };
22cb00db
KS
485 Ok(NABufferType::AudioU8(buf))
486 } else if ainfo.format.get_bits() == 16 && ainfo.format.is_signed() {
e243ceb4 487 let data: Vec<i16> = vec![0; length];
01e2d496 488 let buf: NAAudioBuffer<i16> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples, stride };
22cb00db
KS
489 Ok(NABufferType::AudioI16(buf))
490 } else {
491 Err(AllocatorError::TooLargeDimensions)
492 }
493 }
494 } else {
495 let len = nsamples.checked_mul(ainfo.channels as usize);
496 if len == None { return Err(AllocatorError::TooLargeDimensions); }
497 let length = ainfo.format.get_audio_size(len.unwrap() as u64);
e243ceb4 498 let data: Vec<u8> = vec![0; length];
01e2d496 499 let buf: NAAudioBuffer<u8> = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples, stride: 0 };
1a151e53 500 Ok(NABufferType::AudioPacked(buf))
22cb00db
KS
501 }
502}
503
504pub fn alloc_data_buffer(size: usize) -> Result<NABufferType, AllocatorError> {
e243ceb4 505 let data: Vec<u8> = vec![0; size];
1a967e6b 506 let buf: NABufferRef<Vec<u8>> = NABufferRef::new(data);
22cb00db
KS
507 Ok(NABufferType::Data(buf))
508}
509
510pub fn copy_buffer(buf: NABufferType) -> NABufferType {
511 buf.clone()
512}
513
01613464
KS
514pub struct NAVideoBufferPool<T:Copy> {
515 pool: Vec<NAVideoBufferRef<T>>,
1a967e6b 516 max_len: usize,
01613464 517 add_len: usize,
1a967e6b
KS
518}
519
01613464 520impl<T:Copy> NAVideoBufferPool<T> {
1a967e6b
KS
521 pub fn new(max_len: usize) -> Self {
522 Self {
523 pool: Vec::with_capacity(max_len),
524 max_len,
01613464 525 add_len: 0,
1a967e6b
KS
526 }
527 }
01613464
KS
528 pub fn set_dec_bufs(&mut self, add_len: usize) {
529 self.add_len = add_len;
530 }
531 pub fn get_free(&mut self) -> Option<NAVideoBufferRef<T>> {
532 for e in self.pool.iter() {
533 if e.get_num_refs() == 1 {
534 return Some(e.clone());
535 }
536 }
537 None
538 }
539 pub fn get_copy(&mut self, rbuf: &NAVideoBufferRef<T>) -> Option<NAVideoBufferRef<T>> {
e243ceb4 540 let mut dbuf = self.get_free()?;
01613464
KS
541 dbuf.data.copy_from_slice(&rbuf.data);
542 Some(dbuf)
543 }
544 pub fn reset(&mut self) {
545 self.pool.truncate(0);
546 }
547}
548
549impl NAVideoBufferPool<u8> {
1a967e6b 550 pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> {
01613464 551 let nbufs = self.max_len + self.add_len - self.pool.len();
1a967e6b 552 for _ in 0..nbufs {
e243ceb4 553 let vbuf = alloc_video_buffer(vinfo, align)?;
01613464
KS
554 if let NABufferType::Video(buf) = vbuf {
555 self.pool.push(buf);
556 } else if let NABufferType::VideoPacked(buf) = vbuf {
557 self.pool.push(buf);
558 } else {
559 return Err(AllocatorError::FormatError);
560 }
1a967e6b
KS
561 }
562 Ok(())
563 }
01613464
KS
564}
565
566impl NAVideoBufferPool<u16> {
567 pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> {
568 let nbufs = self.max_len + self.add_len - self.pool.len();
1a967e6b 569 for _ in 0..nbufs {
e243ceb4 570 let vbuf = alloc_video_buffer(vinfo, align)?;
01613464
KS
571 if let NABufferType::Video16(buf) = vbuf {
572 self.pool.push(buf);
573 } else {
574 return Err(AllocatorError::FormatError);
575 }
1a967e6b
KS
576 }
577 Ok(())
578 }
01613464
KS
579}
580
581impl NAVideoBufferPool<u32> {
582 pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> {
583 let nbufs = self.max_len + self.add_len - self.pool.len();
584 for _ in 0..nbufs {
e243ceb4 585 let vbuf = alloc_video_buffer(vinfo, align)?;
01613464
KS
586 if let NABufferType::Video32(buf) = vbuf {
587 self.pool.push(buf);
588 } else {
589 return Err(AllocatorError::FormatError);
1a967e6b
KS
590 }
591 }
01613464 592 Ok(())
1a967e6b
KS
593 }
594}
595
5869fd63 596#[allow(dead_code)]
8869d452
KS
597#[derive(Clone)]
598pub struct NACodecInfo {
ccae5343 599 name: &'static str,
5869fd63 600 properties: NACodecTypeInfo,
2422d969 601 extradata: Option<Arc<Vec<u8>>>,
5869fd63
KS
602}
603
2422d969
KS
604pub type NACodecInfoRef = Arc<NACodecInfo>;
605
8869d452 606impl NACodecInfo {
ccae5343 607 pub fn new(name: &'static str, p: NACodecTypeInfo, edata: Option<Vec<u8>>) -> Self {
8869d452
KS
608 let extradata = match edata {
609 None => None,
2422d969 610 Some(vec) => Some(Arc::new(vec)),
8869d452 611 };
e243ceb4 612 NACodecInfo { name, properties: p, extradata }
8869d452 613 }
2422d969 614 pub fn new_ref(name: &'static str, p: NACodecTypeInfo, edata: Option<Arc<Vec<u8>>>) -> Self {
e243ceb4 615 NACodecInfo { name, properties: p, extradata: edata }
66116504 616 }
2422d969 617 pub fn into_ref(self) -> NACodecInfoRef { Arc::new(self) }
8869d452 618 pub fn get_properties(&self) -> NACodecTypeInfo { self.properties }
2422d969 619 pub fn get_extradata(&self) -> Option<Arc<Vec<u8>>> {
8869d452
KS
620 if let Some(ref vec) = self.extradata { return Some(vec.clone()); }
621 None
5869fd63 622 }
66116504
KS
623 pub fn get_name(&self) -> &'static str { self.name }
624 pub fn is_video(&self) -> bool {
625 if let NACodecTypeInfo::Video(_) = self.properties { return true; }
626 false
627 }
628 pub fn is_audio(&self) -> bool {
629 if let NACodecTypeInfo::Audio(_) = self.properties { return true; }
630 false
631 }
2422d969
KS
632 pub fn new_dummy() -> Arc<Self> {
633 Arc::new(DUMMY_CODEC_INFO)
5076115b 634 }
2422d969
KS
635 pub fn replace_info(&self, p: NACodecTypeInfo) -> Arc<Self> {
636 Arc::new(NACodecInfo { name: self.name, properties: p, extradata: self.extradata.clone() })
5076115b 637 }
66116504
KS
638}
639
241e56f1
KS
640impl Default for NACodecInfo {
641 fn default() -> Self { DUMMY_CODEC_INFO }
642}
643
66116504
KS
644impl fmt::Display for NACodecInfo {
645 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
646 let edata = match self.extradata.clone() {
e243ceb4 647 None => "no extradata".to_string(),
66116504
KS
648 Some(v) => format!("{} byte(s) of extradata", v.len()),
649 };
650 write!(f, "{}: {} {}", self.name, self.properties, edata)
651 }
652}
653
654pub const DUMMY_CODEC_INFO: NACodecInfo = NACodecInfo {
655 name: "none",
656 properties: NACodecTypeInfo::None,
657 extradata: None };
658
66116504
KS
659#[derive(Debug,Clone)]
660pub enum NAValue {
5869fd63
KS
661 None,
662 Int(i32),
663 Long(i64),
664 String(String),
2422d969 665 Data(Arc<Vec<u8>>),
5869fd63
KS
666}
667
88c03b61
KS
668#[derive(Debug,Clone,Copy,PartialEq)]
669#[allow(dead_code)]
670pub enum FrameType {
671 I,
672 P,
673 B,
bc6aac3d 674 Skip,
88c03b61
KS
675 Other,
676}
677
678impl fmt::Display for FrameType {
679 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
680 match *self {
681 FrameType::I => write!(f, "I"),
682 FrameType::P => write!(f, "P"),
683 FrameType::B => write!(f, "B"),
bc6aac3d 684 FrameType::Skip => write!(f, "skip"),
88c03b61
KS
685 FrameType::Other => write!(f, "x"),
686 }
687 }
688}
689
e189501e
KS
690#[derive(Debug,Clone,Copy)]
691pub struct NATimeInfo {
5869fd63
KS
692 pts: Option<u64>,
693 dts: Option<u64>,
694 duration: Option<u64>,
e189501e
KS
695 tb_num: u32,
696 tb_den: u32,
697}
698
699impl NATimeInfo {
700 pub fn new(pts: Option<u64>, dts: Option<u64>, duration: Option<u64>, tb_num: u32, tb_den: u32) -> Self {
e243ceb4 701 NATimeInfo { pts, dts, duration, tb_num, tb_den }
e189501e
KS
702 }
703 pub fn get_pts(&self) -> Option<u64> { self.pts }
704 pub fn get_dts(&self) -> Option<u64> { self.dts }
705 pub fn get_duration(&self) -> Option<u64> { self.duration }
706 pub fn set_pts(&mut self, pts: Option<u64>) { self.pts = pts; }
707 pub fn set_dts(&mut self, dts: Option<u64>) { self.dts = dts; }
708 pub fn set_duration(&mut self, dur: Option<u64>) { self.duration = dur; }
266da7b9
KS
709
710 pub fn time_to_ts(time: u64, base: u64, tb_num: u32, tb_den: u32) -> u64 {
711 let tb_num = tb_num as u64;
712 let tb_den = tb_den as u64;
713 let tmp = time.checked_mul(tb_num);
714 if let Some(tmp) = tmp {
715 tmp / base / tb_den
716 } else {
717 let tmp = time.checked_mul(tb_num);
718 if let Some(tmp) = tmp {
719 tmp / base / tb_den
720 } else {
721 let coarse = time / base;
722 let tmp = coarse.checked_mul(tb_num);
723 if let Some(tmp) = tmp {
724 tmp / tb_den
725 } else {
726 (coarse / tb_den) * tb_num
727 }
728 }
729 }
730 }
a65bdeac
KS
731 pub fn ts_to_time(ts: u64, base: u64, tb_num: u32, tb_den: u32) -> u64 {
732 let tb_num = tb_num as u64;
733 let tb_den = tb_den as u64;
734 let tmp = ts.checked_mul(base);
735 if let Some(tmp) = tmp {
736 let tmp2 = tmp.checked_mul(tb_num);
737 if let Some(tmp2) = tmp2 {
738 tmp2 / tb_den
739 } else {
740 (tmp / tb_den) * tb_num
741 }
742 } else {
743 let tmp = ts.checked_mul(tb_num);
744 if let Some(tmp) = tmp {
745 (tmp / tb_den) * base
746 } else {
747 (ts / tb_den) * base * tb_num
748 }
749 }
750 }
e189501e
KS
751}
752
753#[allow(dead_code)]
754#[derive(Clone)]
755pub struct NAFrame {
756 ts: NATimeInfo,
f18bba90 757 id: i64,
22cb00db 758 buffer: NABufferType,
2422d969 759 info: NACodecInfoRef,
88c03b61
KS
760 ftype: FrameType,
761 key: bool,
66116504
KS
762 options: HashMap<String, NAValue>,
763}
764
171860fc 765pub type NAFrameRef = Arc<NAFrame>;
ebd71c92 766
66116504
KS
767fn get_plane_size(info: &NAVideoInfo, idx: usize) -> (usize, usize) {
768 let chromaton = info.get_format().get_chromaton(idx);
e243ceb4 769 if chromaton.is_none() { return (0, 0); }
66116504
KS
770 let (hs, vs) = chromaton.unwrap().get_subsampling();
771 let w = (info.get_width() + ((1 << hs) - 1)) >> hs;
772 let h = (info.get_height() + ((1 << vs) - 1)) >> vs;
773 (w, h)
774}
775
776impl NAFrame {
e189501e 777 pub fn new(ts: NATimeInfo,
88c03b61
KS
778 ftype: FrameType,
779 keyframe: bool,
2422d969 780 info: NACodecInfoRef,
22cb00db
KS
781 options: HashMap<String, NAValue>,
782 buffer: NABufferType) -> Self {
f18bba90 783 NAFrame { ts, id: 0, buffer, info, ftype, key: keyframe, options }
ebd71c92 784 }
2422d969 785 pub fn get_info(&self) -> NACodecInfoRef { self.info.clone() }
88c03b61
KS
786 pub fn get_frame_type(&self) -> FrameType { self.ftype }
787 pub fn is_keyframe(&self) -> bool { self.key }
88c03b61
KS
788 pub fn set_frame_type(&mut self, ftype: FrameType) { self.ftype = ftype; }
789 pub fn set_keyframe(&mut self, key: bool) { self.key = key; }
e189501e
KS
790 pub fn get_time_information(&self) -> NATimeInfo { self.ts }
791 pub fn get_pts(&self) -> Option<u64> { self.ts.get_pts() }
792 pub fn get_dts(&self) -> Option<u64> { self.ts.get_dts() }
f18bba90 793 pub fn get_id(&self) -> i64 { self.id }
e189501e
KS
794 pub fn get_duration(&self) -> Option<u64> { self.ts.get_duration() }
795 pub fn set_pts(&mut self, pts: Option<u64>) { self.ts.set_pts(pts); }
796 pub fn set_dts(&mut self, dts: Option<u64>) { self.ts.set_dts(dts); }
f18bba90 797 pub fn set_id(&mut self, id: i64) { self.id = id; }
e189501e 798 pub fn set_duration(&mut self, dur: Option<u64>) { self.ts.set_duration(dur); }
66116504 799
22cb00db 800 pub fn get_buffer(&self) -> NABufferType { self.buffer.clone() }
171860fc
KS
801
802 pub fn into_ref(self) -> NAFrameRef { Arc::new(self) }
5869fd63
KS
803}
804
ebd71c92
KS
805impl fmt::Display for NAFrame {
806 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
e243ceb4
KS
807 let mut ostr = format!("frame type {}", self.ftype);
808 if let Some(pts) = self.ts.pts { ostr = format!("{} pts {}", ostr, pts); }
809 if let Some(dts) = self.ts.dts { ostr = format!("{} dts {}", ostr, dts); }
810 if let Some(dur) = self.ts.duration { ostr = format!("{} duration {}", ostr, dur); }
811 if self.key { ostr = format!("{} kf", ostr); }
812 write!(f, "[{}]", ostr)
ebd71c92
KS
813 }
814}
88c03b61 815
48c88fde 816/// Possible stream types.
baf5478c 817#[derive(Debug,Clone,Copy,PartialEq)]
5869fd63 818#[allow(dead_code)]
48c88fde
KS
819pub enum StreamType {
820 /// video stream
821 Video,
822 /// audio stream
823 Audio,
824 /// subtitles
825 Subtitles,
826 /// any data stream (or might be an unrecognized audio/video stream)
827 Data,
828 /// nonexistent stream
829 None,
830}
831
832impl fmt::Display for StreamType {
833 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
834 match *self {
835 StreamType::Video => write!(f, "Video"),
836 StreamType::Audio => write!(f, "Audio"),
837 StreamType::Subtitles => write!(f, "Subtitles"),
838 StreamType::Data => write!(f, "Data"),
839 StreamType::None => write!(f, "-"),
840 }
841 }
842}
843
844#[allow(dead_code)]
845#[derive(Clone)]
846pub struct NAStream {
847 media_type: StreamType,
848 id: u32,
849 num: usize,
2422d969 850 info: NACodecInfoRef,
e189501e
KS
851 tb_num: u32,
852 tb_den: u32,
853}
854
70910ac3
KS
855pub type NAStreamRef = Arc<NAStream>;
856
e189501e
KS
857pub fn reduce_timebase(tb_num: u32, tb_den: u32) -> (u32, u32) {
858 if tb_num == 0 { return (tb_num, tb_den); }
859 if (tb_den % tb_num) == 0 { return (1, tb_den / tb_num); }
860
861 let mut a = tb_num;
862 let mut b = tb_den;
863
864 while a != b {
865 if a > b { a -= b; }
866 else if b > a { b -= a; }
867 }
868
869 (tb_num / a, tb_den / a)
5869fd63 870}
48c88fde
KS
871
872impl NAStream {
e189501e
KS
873 pub fn new(mt: StreamType, id: u32, info: NACodecInfo, tb_num: u32, tb_den: u32) -> Self {
874 let (n, d) = reduce_timebase(tb_num, tb_den);
e243ceb4 875 NAStream { media_type: mt, id, num: 0, info: info.into_ref(), tb_num: n, tb_den: d }
48c88fde
KS
876 }
877 pub fn get_id(&self) -> u32 { self.id }
baf5478c 878 pub fn get_media_type(&self) -> StreamType { self.media_type }
48c88fde
KS
879 pub fn get_num(&self) -> usize { self.num }
880 pub fn set_num(&mut self, num: usize) { self.num = num; }
2422d969 881 pub fn get_info(&self) -> NACodecInfoRef { self.info.clone() }
e189501e
KS
882 pub fn get_timebase(&self) -> (u32, u32) { (self.tb_num, self.tb_den) }
883 pub fn set_timebase(&mut self, tb_num: u32, tb_den: u32) {
884 let (n, d) = reduce_timebase(tb_num, tb_den);
885 self.tb_num = n;
886 self.tb_den = d;
887 }
70910ac3 888 pub fn into_ref(self) -> NAStreamRef { Arc::new(self) }
48c88fde
KS
889}
890
891impl fmt::Display for NAStream {
892 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
e189501e 893 write!(f, "({}#{} @ {}/{} - {})", self.media_type, self.id, self.tb_num, self.tb_den, self.info.get_properties())
48c88fde
KS
894 }
895}
896
897#[allow(dead_code)]
898pub struct NAPacket {
70910ac3 899 stream: NAStreamRef,
e189501e 900 ts: NATimeInfo,
1a967e6b 901 buffer: NABufferRef<Vec<u8>>,
48c88fde
KS
902 keyframe: bool,
903// options: HashMap<String, NAValue<'a>>,
904}
905
906impl NAPacket {
70910ac3 907 pub fn new(str: NAStreamRef, ts: NATimeInfo, kf: bool, vec: Vec<u8>) -> Self {
48c88fde
KS
908// let mut vec: Vec<u8> = Vec::new();
909// vec.resize(size, 0);
e243ceb4 910 NAPacket { stream: str, ts, keyframe: kf, buffer: NABufferRef::new(vec) }
48c88fde 911 }
70910ac3 912 pub fn get_stream(&self) -> NAStreamRef { self.stream.clone() }
e189501e
KS
913 pub fn get_time_information(&self) -> NATimeInfo { self.ts }
914 pub fn get_pts(&self) -> Option<u64> { self.ts.get_pts() }
915 pub fn get_dts(&self) -> Option<u64> { self.ts.get_dts() }
916 pub fn get_duration(&self) -> Option<u64> { self.ts.get_duration() }
48c88fde 917 pub fn is_keyframe(&self) -> bool { self.keyframe }
1a967e6b 918 pub fn get_buffer(&self) -> NABufferRef<Vec<u8>> { self.buffer.clone() }
48c88fde
KS
919}
920
921impl Drop for NAPacket {
922 fn drop(&mut self) {}
923}
924
925impl fmt::Display for NAPacket {
926 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
e243ceb4
KS
927 let mut ostr = format!("[pkt for {} size {}", self.stream, self.buffer.len());
928 if let Some(pts) = self.ts.pts { ostr = format!("{} pts {}", ostr, pts); }
929 if let Some(dts) = self.ts.dts { ostr = format!("{} dts {}", ostr, dts); }
930 if let Some(dur) = self.ts.duration { ostr = format!("{} duration {}", ostr, dur); }
931 if self.keyframe { ostr = format!("{} kf", ostr); }
932 ostr += "]";
933 write!(f, "{}", ostr)
48c88fde
KS
934 }
935}
936
937pub trait FrameFromPacket {
2422d969 938 fn new_from_pkt(pkt: &NAPacket, info: NACodecInfoRef, buf: NABufferType) -> NAFrame;
48c88fde
KS
939 fn fill_timestamps(&mut self, pkt: &NAPacket);
940}
941
942impl FrameFromPacket for NAFrame {
2422d969 943 fn new_from_pkt(pkt: &NAPacket, info: NACodecInfoRef, buf: NABufferType) -> NAFrame {
e189501e 944 NAFrame::new(pkt.ts, FrameType::Other, pkt.keyframe, info, HashMap::new(), buf)
48c88fde
KS
945 }
946 fn fill_timestamps(&mut self, pkt: &NAPacket) {
e189501e 947 self.ts = pkt.get_time_information();
48c88fde
KS
948 }
949}
950