more utility code
[nihav.git] / src / frame.rs
CommitLineData
5869fd63 1use std::collections::HashMap;
83e603fa 2use std::fmt;
8869d452 3use std::rc::Rc;
88c03b61 4use std::cell::*;
fba6f8e4 5use formats::*;
94dbb551 6
5869fd63 7#[allow(dead_code)]
66116504 8#[derive(Clone,Copy,PartialEq)]
5869fd63
KS
9pub struct NAAudioInfo {
10 sample_rate: u32,
11 channels: u8,
12 format: NASoniton,
13 block_len: usize,
14}
15
16impl NAAudioInfo {
17 pub fn new(sr: u32, ch: u8, fmt: NASoniton, bl: usize) -> Self {
18 NAAudioInfo { sample_rate: sr, channels: ch, format: fmt, block_len: bl }
19 }
66116504
KS
20 pub fn get_sample_rate(&self) -> u32 { self.sample_rate }
21 pub fn get_channels(&self) -> u8 { self.channels }
22 pub fn get_format(&self) -> NASoniton { self.format }
23 pub fn get_block_len(&self) -> usize { self.block_len }
5869fd63
KS
24}
25
83e603fa
KS
26impl fmt::Display for NAAudioInfo {
27 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
28 write!(f, "{} Hz, {} ch", self.sample_rate, self.channels)
29 }
30}
31
5869fd63 32#[allow(dead_code)]
66116504 33#[derive(Clone,Copy,PartialEq)]
5869fd63 34pub struct NAVideoInfo {
66116504
KS
35 width: usize,
36 height: usize,
5869fd63
KS
37 flipped: bool,
38 format: NAPixelFormaton,
39}
40
41impl NAVideoInfo {
66116504 42 pub fn new(w: usize, h: usize, flip: bool, fmt: NAPixelFormaton) -> Self {
5869fd63
KS
43 NAVideoInfo { width: w, height: h, flipped: flip, format: fmt }
44 }
66116504
KS
45 pub fn get_width(&self) -> usize { self.width as usize }
46 pub fn get_height(&self) -> usize { self.height as usize }
47 pub fn is_flipped(&self) -> bool { self.flipped }
48 pub fn get_format(&self) -> NAPixelFormaton { self.format }
5869fd63
KS
49}
50
83e603fa
KS
51impl fmt::Display for NAVideoInfo {
52 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53 write!(f, "{}x{}", self.width, self.height)
54 }
55}
56
66116504 57#[derive(Clone,Copy,PartialEq)]
5869fd63
KS
58pub enum NACodecTypeInfo {
59 None,
60 Audio(NAAudioInfo),
61 Video(NAVideoInfo),
62}
63
83e603fa
KS
64impl fmt::Display for NACodecTypeInfo {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66 let ret = match *self {
67 NACodecTypeInfo::None => format!(""),
68 NACodecTypeInfo::Audio(fmt) => format!("{}", fmt),
69 NACodecTypeInfo::Video(fmt) => format!("{}", fmt),
70 };
71 write!(f, "{}", ret)
72 }
73}
74
88c03b61 75pub type BufferRef = Rc<RefCell<Vec<u8>>>;
83e603fa 76
5869fd63 77#[allow(dead_code)]
66116504
KS
78#[derive(Clone)]
79pub struct NABuffer {
5869fd63 80 id: u64,
88c03b61 81 data: BufferRef,
66116504
KS
82}
83
84impl Drop for NABuffer {
85 fn drop(&mut self) { }
86}
87
88impl NABuffer {
88c03b61
KS
89 pub fn get_data(&self) -> Ref<Vec<u8>> { self.data.borrow() }
90 pub fn get_data_mut(&mut self) -> RefMut<Vec<u8>> { self.data.borrow_mut() }
5869fd63
KS
91}
92
88c03b61
KS
93pub type NABufferRef = Rc<RefCell<NABuffer>>;
94
5869fd63 95#[allow(dead_code)]
8869d452
KS
96#[derive(Clone)]
97pub struct NACodecInfo {
ccae5343 98 name: &'static str,
5869fd63 99 properties: NACodecTypeInfo,
8869d452 100 extradata: Option<Rc<Vec<u8>>>,
5869fd63
KS
101}
102
8869d452 103impl NACodecInfo {
ccae5343 104 pub fn new(name: &'static str, p: NACodecTypeInfo, edata: Option<Vec<u8>>) -> Self {
8869d452
KS
105 let extradata = match edata {
106 None => None,
107 Some(vec) => Some(Rc::new(vec)),
108 };
ccae5343 109 NACodecInfo { name: name, properties: p, extradata: extradata }
8869d452 110 }
66116504
KS
111 pub fn new_ref(name: &'static str, p: NACodecTypeInfo, edata: Option<Rc<Vec<u8>>>) -> Self {
112 NACodecInfo { name: name, properties: p, extradata: edata }
113 }
8869d452
KS
114 pub fn get_properties(&self) -> NACodecTypeInfo { self.properties }
115 pub fn get_extradata(&self) -> Option<Rc<Vec<u8>>> {
116 if let Some(ref vec) = self.extradata { return Some(vec.clone()); }
117 None
5869fd63 118 }
66116504
KS
119 pub fn get_name(&self) -> &'static str { self.name }
120 pub fn is_video(&self) -> bool {
121 if let NACodecTypeInfo::Video(_) = self.properties { return true; }
122 false
123 }
124 pub fn is_audio(&self) -> bool {
125 if let NACodecTypeInfo::Audio(_) = self.properties { return true; }
126 false
127 }
128}
129
130impl fmt::Display for NACodecInfo {
131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
132 let edata = match self.extradata.clone() {
133 None => format!("no extradata"),
134 Some(v) => format!("{} byte(s) of extradata", v.len()),
135 };
136 write!(f, "{}: {} {}", self.name, self.properties, edata)
137 }
138}
139
140pub const DUMMY_CODEC_INFO: NACodecInfo = NACodecInfo {
141 name: "none",
142 properties: NACodecTypeInfo::None,
143 extradata: None };
144
145fn alloc_video_buf(vinfo: NAVideoInfo, data: &mut Vec<u8>, offs: &mut Vec<usize>) {
146//todo use overflow detection mul
147 let width = vinfo.width as usize;
148 let height = vinfo.height as usize;
149 let fmt = &vinfo.format;
150 let mut new_size = 0;
151 for i in 0..fmt.get_num_comp() {
152 let chr = fmt.get_chromaton(i).unwrap();
153 if !vinfo.is_flipped() {
154 offs.push(new_size as usize);
155 }
156 new_size += chr.get_data_size(width, height);
157 if vinfo.is_flipped() {
158 offs.push(new_size as usize);
159 }
160 }
161 data.resize(new_size, 0);
5869fd63
KS
162}
163
66116504
KS
164fn alloc_audio_buf(ainfo: NAAudioInfo, data: &mut Vec<u8>, offs: &mut Vec<usize>) {
165//todo better alloc
166 let length = ((ainfo.sample_rate as usize) * (ainfo.format.get_bits() as usize)) >> 3;
167 let new_size: usize = length * (ainfo.channels as usize);
168 data.resize(new_size, 0);
169 for i in 0..ainfo.channels {
170 if ainfo.format.is_planar() {
171 offs.push((i as usize) * length);
172 } else {
173 offs.push(((i * ainfo.format.get_bits()) >> 3) as usize);
174 }
175 }
5869fd63
KS
176}
177
88c03b61 178pub fn alloc_buf(info: &NACodecInfo) -> (NABufferRef, Vec<usize>) {
66116504
KS
179 let mut data: Vec<u8> = Vec::new();
180 let mut offs: Vec<usize> = Vec::new();
181 match info.properties {
182 NACodecTypeInfo::Audio(ainfo) => alloc_audio_buf(ainfo, &mut data, &mut offs),
183 NACodecTypeInfo::Video(vinfo) => alloc_video_buf(vinfo, &mut data, &mut offs),
184 _ => (),
185 }
88c03b61 186 (Rc::new(RefCell::new(NABuffer { id: 0, data: Rc::new(RefCell::new(data)) })), offs)
66116504
KS
187}
188
88c03b61 189pub fn copy_buf(buf: &NABuffer) -> NABufferRef {
66116504
KS
190 let mut data: Vec<u8> = Vec::new();
191 data.clone_from(buf.get_data().as_ref());
88c03b61 192 Rc::new(RefCell::new(NABuffer { id: 0, data: Rc::new(RefCell::new(data)) }))
66116504
KS
193}
194
195#[derive(Debug,Clone)]
196pub enum NAValue {
5869fd63
KS
197 None,
198 Int(i32),
199 Long(i64),
200 String(String),
66116504 201 Data(Rc<Vec<u8>>),
5869fd63
KS
202}
203
88c03b61
KS
204#[derive(Debug,Clone,Copy,PartialEq)]
205#[allow(dead_code)]
206pub enum FrameType {
207 I,
208 P,
209 B,
210 Other,
211}
212
213impl fmt::Display for FrameType {
214 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
215 match *self {
216 FrameType::I => write!(f, "I"),
217 FrameType::P => write!(f, "P"),
218 FrameType::B => write!(f, "B"),
219 FrameType::Other => write!(f, "x"),
220 }
221 }
222}
223
5869fd63 224#[allow(dead_code)]
66116504
KS
225#[derive(Clone)]
226pub struct NAFrame {
5869fd63
KS
227 pts: Option<u64>,
228 dts: Option<u64>,
229 duration: Option<u64>,
88c03b61 230 buffer: NABufferRef,
66116504 231 info: Rc<NACodecInfo>,
88c03b61
KS
232 ftype: FrameType,
233 key: bool,
66116504
KS
234 offsets: Vec<usize>,
235 options: HashMap<String, NAValue>,
236}
237
ebd71c92
KS
238pub type NAFrameRef = Rc<RefCell<NAFrame>>;
239
66116504
KS
240fn get_plane_size(info: &NAVideoInfo, idx: usize) -> (usize, usize) {
241 let chromaton = info.get_format().get_chromaton(idx);
242 if let None = chromaton { return (0, 0); }
243 let (hs, vs) = chromaton.unwrap().get_subsampling();
244 let w = (info.get_width() + ((1 << hs) - 1)) >> hs;
245 let h = (info.get_height() + ((1 << vs) - 1)) >> vs;
246 (w, h)
247}
248
249impl NAFrame {
250 pub fn new(pts: Option<u64>,
251 dts: Option<u64>,
252 duration: Option<u64>,
88c03b61
KS
253 ftype: FrameType,
254 keyframe: bool,
66116504
KS
255 info: Rc<NACodecInfo>,
256 options: HashMap<String, NAValue>) -> Self {
257 let (buf, offs) = alloc_buf(&info);
88c03b61 258 NAFrame { pts: pts, dts: dts, duration: duration, buffer: buf, offsets: offs, info: info, ftype: ftype, key: keyframe, options: options }
66116504
KS
259 }
260 pub fn from_copy(src: &NAFrame) -> Self {
88c03b61 261 let buf = copy_buf(&src.get_buffer());
66116504
KS
262 let mut offs: Vec<usize> = Vec::new();
263 offs.clone_from(&src.offsets);
88c03b61 264 NAFrame { pts: None, dts: None, duration: None, buffer: buf, offsets: offs, info: src.info.clone(), ftype: src.ftype, key: src.key, options: src.options.clone() }
66116504 265 }
ebd71c92
KS
266 pub fn from_ref(srcref: NAFrameRef) -> Self {
267 let src = srcref.borrow();
268 let buf = copy_buf(&src.get_buffer());
269 let mut offs: Vec<usize> = Vec::new();
270 offs.clone_from(&src.offsets);
271 NAFrame { pts: None, dts: None, duration: None, buffer: buf, offsets: offs, info: src.info.clone(), ftype: src.ftype, key: src.key, options: src.options.clone() }
272 }
66116504
KS
273 pub fn get_pts(&self) -> Option<u64> { self.pts }
274 pub fn get_dts(&self) -> Option<u64> { self.dts }
275 pub fn get_duration(&self) -> Option<u64> { self.duration }
88c03b61
KS
276 pub fn get_frame_type(&self) -> FrameType { self.ftype }
277 pub fn is_keyframe(&self) -> bool { self.key }
66116504
KS
278 pub fn set_pts(&mut self, pts: Option<u64>) { self.pts = pts; }
279 pub fn set_dts(&mut self, dts: Option<u64>) { self.dts = dts; }
280 pub fn set_duration(&mut self, dur: Option<u64>) { self.duration = dur; }
88c03b61
KS
281 pub fn set_frame_type(&mut self, ftype: FrameType) { self.ftype = ftype; }
282 pub fn set_keyframe(&mut self, key: bool) { self.key = key; }
66116504
KS
283
284 pub fn get_offset(&self, idx: usize) -> usize { self.offsets[idx] }
88c03b61
KS
285 pub fn get_buffer(&self) -> Ref<NABuffer> { self.buffer.borrow() }
286 pub fn get_buffer_mut(&mut self) -> RefMut<NABuffer> { self.buffer.borrow_mut() }
66116504
KS
287 pub fn get_stride(&self, idx: usize) -> usize {
288 if let NACodecTypeInfo::Video(vinfo) = self.info.get_properties() {
289 if idx >= vinfo.get_format().get_num_comp() { return 0; }
290 vinfo.get_format().get_chromaton(idx).unwrap().get_linesize(vinfo.get_width())
291 } else {
292 0
293 }
294 }
295 pub fn get_dimensions(&self, idx: usize) -> (usize, usize) {
296 match self.info.get_properties() {
297 NACodecTypeInfo::Video(ref vinfo) => get_plane_size(vinfo, idx),
298 _ => (0, 0),
299 }
300 }
5869fd63
KS
301}
302
ebd71c92
KS
303impl fmt::Display for NAFrame {
304 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
305 let (w, h) = self.get_dimensions(0);
306 let mut foo = format!("frame type {} size {}x{}", self.ftype, w, h);
307 if let Some(pts) = self.pts { foo = format!("{} pts {}", foo, pts); }
308 if let Some(dts) = self.dts { foo = format!("{} dts {}", foo, dts); }
309 if let Some(dur) = self.duration { foo = format!("{} duration {}", foo, dur); }
310 if self.key { foo = format!("{} kf", foo); }
311 write!(f, "[{}]", foo)
312 }
313}
88c03b61 314
48c88fde
KS
315/// Possible stream types.
316#[derive(Debug,Clone,Copy)]
5869fd63 317#[allow(dead_code)]
48c88fde
KS
318pub enum StreamType {
319 /// video stream
320 Video,
321 /// audio stream
322 Audio,
323 /// subtitles
324 Subtitles,
325 /// any data stream (or might be an unrecognized audio/video stream)
326 Data,
327 /// nonexistent stream
328 None,
329}
330
331impl fmt::Display for StreamType {
332 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
333 match *self {
334 StreamType::Video => write!(f, "Video"),
335 StreamType::Audio => write!(f, "Audio"),
336 StreamType::Subtitles => write!(f, "Subtitles"),
337 StreamType::Data => write!(f, "Data"),
338 StreamType::None => write!(f, "-"),
339 }
340 }
341}
342
343#[allow(dead_code)]
344#[derive(Clone)]
345pub struct NAStream {
346 media_type: StreamType,
347 id: u32,
348 num: usize,
349 info: Rc<NACodecInfo>,
5869fd63 350}
48c88fde
KS
351
352impl NAStream {
353 pub fn new(mt: StreamType, id: u32, info: NACodecInfo) -> Self {
354 NAStream { media_type: mt, id: id, num: 0, info: Rc::new(info) }
355 }
356 pub fn get_id(&self) -> u32 { self.id }
357 pub fn get_num(&self) -> usize { self.num }
358 pub fn set_num(&mut self, num: usize) { self.num = num; }
359 pub fn get_info(&self) -> Rc<NACodecInfo> { self.info.clone() }
360}
361
362impl fmt::Display for NAStream {
363 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
364 write!(f, "({}#{} - {})", self.media_type, self.id, self.info.get_properties())
365 }
366}
367
368#[allow(dead_code)]
369pub struct NAPacket {
370 stream: Rc<NAStream>,
371 pts: Option<u64>,
372 dts: Option<u64>,
373 duration: Option<u64>,
374 buffer: Rc<Vec<u8>>,
375 keyframe: bool,
376// options: HashMap<String, NAValue<'a>>,
377}
378
379impl NAPacket {
380 pub fn new(str: Rc<NAStream>, pts: Option<u64>, dts: Option<u64>, dur: Option<u64>, kf: bool, vec: Vec<u8>) -> Self {
381// let mut vec: Vec<u8> = Vec::new();
382// vec.resize(size, 0);
383 NAPacket { stream: str, pts: pts, dts: dts, duration: dur, keyframe: kf, buffer: Rc::new(vec) }
384 }
385 pub fn get_stream(&self) -> Rc<NAStream> { self.stream.clone() }
386 pub fn get_pts(&self) -> Option<u64> { self.pts }
387 pub fn get_dts(&self) -> Option<u64> { self.dts }
388 pub fn get_duration(&self) -> Option<u64> { self.duration }
389 pub fn is_keyframe(&self) -> bool { self.keyframe }
390 pub fn get_buffer(&self) -> Rc<Vec<u8>> { self.buffer.clone() }
391}
392
393impl Drop for NAPacket {
394 fn drop(&mut self) {}
395}
396
397impl fmt::Display for NAPacket {
398 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
399 let mut foo = format!("[pkt for {} size {}", self.stream, self.buffer.len());
400 if let Some(pts) = self.pts { foo = format!("{} pts {}", foo, pts); }
401 if let Some(dts) = self.dts { foo = format!("{} dts {}", foo, dts); }
402 if let Some(dur) = self.duration { foo = format!("{} duration {}", foo, dur); }
403 if self.keyframe { foo = format!("{} kf", foo); }
404 foo = foo + "]";
405 write!(f, "{}", foo)
406 }
407}
408
409pub trait FrameFromPacket {
410 fn new_from_pkt(pkt: &NAPacket, info: Rc<NACodecInfo>) -> NAFrame;
411 fn fill_timestamps(&mut self, pkt: &NAPacket);
412}
413
414impl FrameFromPacket for NAFrame {
415 fn new_from_pkt(pkt: &NAPacket, info: Rc<NACodecInfo>) -> NAFrame {
88c03b61 416 NAFrame::new(pkt.pts, pkt.dts, pkt.duration, FrameType::Other, pkt.keyframe, info, HashMap::new())
48c88fde
KS
417 }
418 fn fill_timestamps(&mut self, pkt: &NAPacket) {
419 self.set_pts(pkt.pts);
420 self.set_dts(pkt.dts);
421 self.set_duration(pkt.duration);
422 }
423}
424