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