]> git.nihav.org Git - nihav.git/blob - src/demuxers/avi.rs
avi: output bps for audio in bits
[nihav.git] / src / demuxers / avi.rs
1 use super::*;
2 use register;
3 use super::DemuxerError::*;
4 use io::byteio::*;
5 use frame::*;
6 use formats::*;
7
8 macro_rules! mktag {
9 ($a:expr, $b:expr, $c:expr, $d:expr) => ({
10 (($a as u32) << 24) | (($b as u32) << 16) | (($c as u32) << 8) | ($d as u32)
11 });
12 ($arr:expr) => ({
13 (($arr[0] as u32) << 24) | (($arr[1] as u32) << 16) | (($arr[2] as u32) << 8) | ($arr[3] as u32)
14 });
15 }
16
17 struct StreamState {
18 strm_no: u8,
19 got_strf: bool,
20 strm_type: Option<StreamType>,
21 }
22
23 impl StreamState {
24 fn new() -> Self {
25 StreamState { strm_no: 0, got_strf: true, strm_type: None }
26 }
27 fn reset(&mut self) {
28 self.strm_type = None;
29 self.got_strf = true;
30 self.strm_no += 1;
31 }
32 fn valid_state(&self) -> bool {
33 match self.strm_type {
34 None => self.got_strf,
35 _ => false,
36 }
37 }
38 }
39
40 #[allow(dead_code)]
41 struct AVIDemuxer<'a> {
42 opened: bool,
43 src: &'a mut ByteReader<'a>,
44 cur_frame: Vec<u64>,
45 num_streams: u8,
46 dmx: Demuxer,
47 size: usize,
48 movi_size: usize,
49 sstate: StreamState,
50 tb_num: u32,
51 tb_den: u32,
52 }
53
54 #[derive(Debug,Clone,Copy,PartialEq)]
55 enum RIFFTag {
56 Chunk(u32),
57 List(u32,u32),
58 }
59
60 struct RIFFParser {
61 tag: RIFFTag,
62 parse: fn(&mut AVIDemuxer, size: usize) -> DemuxerResult<usize>,
63 }
64
65 impl<'a> Demux<'a> for AVIDemuxer<'a> {
66 #[allow(unused_variables)]
67 fn open(&mut self) -> DemuxerResult<()> {
68 self.read_header()?;
69 self.opened = true;
70 Ok(())
71 }
72
73 fn get_num_streams(&self) -> usize { self.dmx.get_num_streams() }
74 fn get_stream(&self, idx: usize) -> Option<Rc<NAStream>> { self.dmx.get_stream(idx) }
75
76 fn get_frame(&mut self) -> DemuxerResult<NAPacket> {
77 if !self.opened { return Err(NoSuchInput); }
78 if self.movi_size == 0 { return Err(EOF); }
79 let mut tag: [u8; 4] = [0; 4];
80 loop {
81 if (self.src.tell() & 1) == 1 {
82 self.src.read_skip(1)?;
83 self.movi_size -= 1;
84 }
85 self.src.read_buf(&mut tag)?;
86 let size = self.src.read_u32le()? as usize;
87 if mktag!(tag) == mktag!(b"JUNK") {
88 self.movi_size -= size + 8;
89 self.src.read_skip(size)?;
90 continue;
91 }
92 if tag[0] < b'0' || tag[0] > b'9' || tag[1] < b'0' || tag[1] > b'9' {
93 return Err(InvalidData);
94 }
95 let stream_no = (tag[0] - b'0') * 10 + (tag[1] - b'0');
96 let str = self.dmx.get_stream(stream_no as usize);
97 if let None = str { return Err(InvalidData); }
98 let stream = str.unwrap();
99 let (tb_num, tb_den) = stream.get_timebase();
100 let ts = NATimeInfo::new(Some(self.cur_frame[stream_no as usize]), None, None, tb_num, tb_den);
101 let pkt = self.src.read_packet(stream, ts, false, size)?;
102 self.cur_frame[stream_no as usize] += 1;
103 self.movi_size -= size + 8;
104
105 return Ok(pkt);
106 }
107 }
108
109 #[allow(unused_variables)]
110 fn seek(&mut self, time: u64) -> DemuxerResult<()> {
111 if !self.opened { return Err(NoSuchInput); }
112 Err(NotImplemented)
113 }
114 }
115
116 impl<'a> AVIDemuxer<'a> {
117 fn new(io: &'a mut ByteReader<'a>) -> Self {
118 AVIDemuxer {
119 cur_frame: Vec::new(),
120 num_streams: 0,
121 opened: false,
122 src: io,
123 size: 0,
124 movi_size: 0,
125 sstate: StreamState::new(),
126 tb_num: 0,
127 tb_den: 0,
128 dmx: Demuxer::new()
129 }
130 }
131
132 fn parse_chunk(&mut self, end_tag: RIFFTag, csize: usize, depth: u16) -> DemuxerResult<(usize, bool)> {
133 if csize < 8 { return Err(InvalidData); }
134 if depth > 42 { return Err(InvalidData); }
135
136 let tag = self.src.read_u32be()?;
137 let size = self.src.read_u32le()? as usize;
138 if size > csize { return Err(InvalidData); }
139 if RIFFTag::Chunk(tag) == end_tag {
140 return Ok((size, true));
141 }
142 let is_list = is_list_tag(tag);
143 let ltag = if is_list { self.src.read_u32be()? } else { 0 };
144 if RIFFTag::List(tag, ltag) == end_tag {
145 return Ok((size, true));
146 }
147
148 for i in 0..CHUNKS.len() {
149 if RIFFTag::Chunk(tag) == CHUNKS[i].tag {
150 let psize = (CHUNKS[i].parse)(self, size)?;
151 if psize != size { return Err(InvalidData); }
152 if (psize & 1) == 1 { self.src.read_skip(1)?; }
153 return Ok((size + 8, false));
154 }
155 if RIFFTag::List(tag, ltag) == CHUNKS[i].tag {
156 let mut rest_size = size - 4;
157 let psize = (CHUNKS[i].parse)(self, rest_size)?;
158 if psize > rest_size { return Err(InvalidData); }
159 rest_size -= psize;
160 while rest_size > 0 {
161 let (psize, _) = self.parse_chunk(end_tag, rest_size, depth+1)?;
162 if psize > rest_size { return Err(InvalidData); }
163 rest_size -= psize;
164 if (psize & 1) == 1 {
165 if rest_size > 0 {
166 rest_size -= 1;
167 }
168 }
169 }
170
171 return Ok((size + 8, false));
172 }
173 }
174 if !is_list {
175 self.src.read_skip(size)?;
176 } else {
177 if size < 4 { return Err(InvalidData); }
178 self.src.read_skip(size - 4)?;
179 }
180 if (size & 1) == 1 { self.src.read_skip(1)?; }
181 return Ok((size + 8, false));
182 }
183
184 fn read_header(&mut self) -> DemuxerResult<()> {
185 let riff_tag = self.src.read_u32be()?;
186 let size = self.src.read_u32le()? as usize;
187 let avi_tag = self.src.read_u32be()?;
188 if riff_tag != mktag!(b"RIFF") || avi_tag != mktag!(b"AVI ") {
189 return Err(InvalidData);
190 }
191 self.size = size;
192 let mut rest_size = size;
193 loop {
194 let (csz, end) = self.parse_chunk(RIFFTag::List(mktag!(b"LIST"), mktag!(b"movi")), rest_size,0)?;
195 if end { self.movi_size = csz - 4; break; }
196 rest_size -= csz;
197 }
198 if !self.sstate.valid_state() || self.sstate.strm_no != self.num_streams {
199 return Err(InvalidData);
200 }
201 Ok(())
202 }
203
204 fn read_extradata(&mut self, size: usize) -> DemuxerResult<Option<Vec<u8>>> {
205 if size == 0 { return Ok(None); }
206 let mut edvec: Vec<u8> = Vec::with_capacity(size);
207 edvec.resize(size, 0);
208 self.src.read_buf(&mut edvec)?;
209 Ok(Some(edvec))
210 }
211 }
212
213 const CHUNKS: [RIFFParser; 6] = [
214 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"hdrl")), parse: parse_hdrl },
215 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"strl")), parse: parse_strl },
216 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"avih")), parse: parse_avih },
217 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"strf")), parse: parse_strf },
218 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"strh")), parse: parse_strh },
219 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"JUNK")), parse: parse_junk },
220 ];
221
222 fn is_list_tag(tag: u32) -> bool {
223 for i in 0..CHUNKS.len() {
224 if let RIFFTag::List(ltag, _) = CHUNKS[i].tag {
225 if tag == ltag {
226 return true;
227 }
228 }
229 }
230 false
231 }
232
233 #[allow(unused_variables)]
234 fn parse_hdrl(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
235 Ok(0)
236 }
237
238 #[allow(unused_variables)]
239 fn parse_strl(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
240 Ok(0)
241 }
242
243 #[allow(unused_variables)]
244 fn parse_strh(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
245 if size < 0x38 { return Err(InvalidData); }
246 let tag = dmx.src.read_u32be()?; //stream type
247 let fcc = dmx.src.read_u32be()?; //handler(fourcc)
248 dmx.src.read_u32le()?; //flags
249 dmx.src.read_skip(2)?; //priority
250 dmx.src.read_skip(2)?; //language
251 dmx.src.read_skip(4)?; //initial frames
252 dmx.tb_num = dmx.src.read_u32le()?; //scale
253 dmx.tb_den = dmx.src.read_u32le()?; //rate
254 dmx.src.read_skip(4)?; //start
255 dmx.src.read_skip(4)?; //length
256 dmx.src.read_skip(4)?; //buf size
257 dmx.src.read_skip(4)?; //quality
258 dmx.src.read_skip(4)?; //sample size
259 let a = dmx.src.read_u16le()?;
260 let b = dmx.src.read_u16le()?;
261 let c = dmx.src.read_u16le()?;
262 let d = dmx.src.read_u16le()?;
263
264 dmx.src.read_skip(size - 0x38)?;
265
266 if !dmx.sstate.valid_state() || dmx.sstate.strm_no >= dmx.num_streams {
267 return Err(InvalidData);
268 }
269 if tag == mktag!(b"vids") {
270 dmx.sstate.strm_type = Some(StreamType::Video);
271 } else if tag == mktag!(b"auds") {
272 dmx.sstate.strm_type = Some(StreamType::Audio);
273 } else {
274 dmx.sstate.strm_type = Some(StreamType::Data);
275 }
276 dmx.sstate.got_strf = false;
277
278 Ok(size)
279 }
280
281 fn parse_strf(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
282 if let None = dmx.sstate.strm_type { return Err(InvalidData); }
283 match dmx.sstate.strm_type.unwrap() {
284 StreamType::Video => parse_strf_vids(dmx, size),
285 StreamType::Audio => parse_strf_auds(dmx, size),
286 _ => parse_strf_xxxx(dmx, size),
287 }
288 }
289
290 #[allow(unused_variables)]
291 fn parse_strf_vids(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
292 if size < 40 { return Err(InvalidData); }
293 let bi_size = dmx.src.read_u32le()?;
294 if (bi_size as usize) > size { return Err(InvalidData); }
295 let width = dmx.src.read_u32le()?;
296 let height = dmx.src.read_u32le()? as i32;
297 let planes = dmx.src.read_u16le()?;
298 let bitcount = dmx.src.read_u16le()?;
299 let mut compression: [u8; 4] = [0; 4];
300 dmx.src.read_buf(&mut compression)?;
301 let img_size = dmx.src.read_u32le()?;
302 let xdpi = dmx.src.read_u32le()?;
303 let ydpi = dmx.src.read_u32le()?;
304 let colors = dmx.src.read_u32le()?;
305 let imp_colors = dmx.src.read_u32le()?;
306
307 let flip = height < 0;
308 let format = if bitcount > 8 { RGB24_FORMAT } else { PAL8_FORMAT };
309 let vhdr = NAVideoInfo::new(width as usize, if flip { -height as usize } else { height as usize}, flip, PAL8_FORMAT);
310 let vci = NACodecTypeInfo::Video(vhdr);
311 let edata = dmx.read_extradata(size - 40)?;
312 let cname = match register::find_codec_from_avi_fourcc(&compression) {
313 None => "unknown",
314 Some(name) => name,
315 };
316 let vinfo = NACodecInfo::new(cname, vci, edata);
317 let res = dmx.dmx.add_stream(NAStream::new(StreamType::Video, dmx.sstate.strm_no as u32, vinfo, dmx.tb_num, dmx.tb_den));
318 if let None = res { return Err(MemoryError); }
319 dmx.sstate.reset();
320 Ok(size)
321 }
322
323 #[allow(unused_variables)]
324 fn parse_strf_auds(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
325 if size < 16 { return Err(InvalidData); }
326 let w_format_tag = dmx.src.read_u16le()?;
327 let channels = dmx.src.read_u16le()?;
328 let samplespersec = dmx.src.read_u32le()?;
329 let avgbytespersec = dmx.src.read_u32le()?;
330 let block_align = dmx.src.read_u16le()?;
331 let bits_per_sample = dmx.src.read_u16le()? * 8;
332
333 let soniton = NASoniton::new(bits_per_sample as u8, SONITON_FLAG_SIGNED);
334 let ahdr = NAAudioInfo::new(samplespersec, channels as u8, soniton, block_align as usize);
335 let edata = dmx.read_extradata(size - 16)?;
336 let cname = match register::find_codec_from_wav_twocc(w_format_tag) {
337 None => "unknown",
338 Some(name) => name,
339 };
340 let ainfo = NACodecInfo::new(cname, NACodecTypeInfo::Audio(ahdr), edata);
341 let res = dmx.dmx.add_stream(NAStream::new(StreamType::Audio, dmx.sstate.strm_no as u32, ainfo, dmx.tb_num, dmx.tb_den));
342 if let None = res { return Err(MemoryError); }
343 dmx.sstate.reset();
344 Ok(size)
345 }
346
347 fn parse_strf_xxxx(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
348 let edata = dmx.read_extradata(size)?;
349 let info = NACodecInfo::new("unknown", NACodecTypeInfo::None, edata);
350 let res = dmx.dmx.add_stream(NAStream::new(StreamType::Data, dmx.sstate.strm_no as u32, info, dmx.tb_num, dmx.tb_den));
351 if let None = res { return Err(MemoryError); }
352 dmx.sstate.reset();
353 Ok(size)
354 }
355
356 #[allow(unused_variables)]
357 fn parse_avih(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
358 if size < 0x38 { return Err(InvalidData); }
359 let timebase = dmx.src.read_u32le()?; //microsec per frame
360 dmx.src.read_skip(4)?; //max frame size
361 dmx.src.read_skip(4)?; //padding
362 dmx.src.read_u32le()?; //flags
363 let frames = dmx.src.read_u32le()?; //frames
364 dmx.src.read_skip(4)?; //initial frames
365 let streams = dmx.src.read_u32le()?; //streams
366 if streams > 100 { return Err(InvalidData); }
367 dmx.num_streams = streams as u8;
368
369 dmx.src.read_skip(4)?; //buf size
370 let width = dmx.src.read_u32le()?; //width
371 let height = dmx.src.read_u32le()? as i32; //height
372 dmx.src.read_skip(16)?; //reserved
373
374 dmx.cur_frame.resize(streams as usize, 0);
375 dmx.src.read_skip(size - 0x38)?;
376 Ok(size)
377 }
378
379 fn parse_junk(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
380 dmx.src.read_skip(size)?;
381 Ok(size)
382 }
383
384 pub struct AVIDemuxerCreator { }
385
386 impl DemuxerCreator for AVIDemuxerCreator {
387 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<Demux<'a> + 'a> {
388 Box::new(AVIDemuxer::new(br))
389 }
390 fn get_name(&self) -> &'static str { "avi" }
391 }
392
393 #[cfg(test)]
394 mod test {
395 use super::*;
396 use std::fs::File;
397
398 #[test]
399 fn test_avi_demux() {
400 let mut file = File::open("assets/laser05.avi").unwrap();
401 let mut fr = FileReader::new_read(&mut file);
402 let mut br = ByteReader::new(&mut fr);
403 let mut dmx = AVIDemuxer::new(&mut br);
404 dmx.open().unwrap();
405
406 loop {
407 let pktres = dmx.get_frame();
408 if let Err(e) = pktres {
409 if e == DemuxerError::EOF { break; }
410 panic!("error");
411 }
412 let pkt = pktres.unwrap();
413 println!("Got {}", pkt);
414 }
415 }
416 }