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