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