3 use super::DemuxerError::*;
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)
13 (($arr[0] as u32) << 24) | (($arr[1] as u32) << 16) | (($arr[2] as u32) << 8) | ($arr[3] as u32)
20 strm_type: Option<StreamType>,
25 StreamState { strm_no: 0, got_strf: true, strm_type: None }
28 self.strm_type = None;
32 fn valid_state(&self) -> bool {
33 match self.strm_type {
34 None => self.got_strf,
41 struct AVIDemuxer<'a> {
43 src: &'a mut ByteReader<'a>,
54 #[derive(Debug,Clone,Copy,PartialEq)]
62 parse: fn(&mut AVIDemuxer, size: usize) -> DemuxerResult<usize>,
65 impl<'a> Demux<'a> for AVIDemuxer<'a> {
66 #[allow(unused_variables)]
67 fn open(&mut self) -> DemuxerResult<()> {
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) }
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];
81 if (self.src.tell() & 1) == 1 {
82 self.src.read_skip(1)?;
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)?;
92 if tag[0] < b'0' || tag[0] > b'9' || tag[1] < b'0' || tag[1] > b'9' {
93 return Err(InvalidData);
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;
109 #[allow(unused_variables)]
110 fn seek(&mut self, time: u64) -> DemuxerResult<()> {
111 if !self.opened { return Err(NoSuchInput); }
116 impl<'a> AVIDemuxer<'a> {
117 fn new(io: &'a mut ByteReader<'a>) -> Self {
119 cur_frame: Vec::new(),
125 sstate: StreamState::new(),
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); }
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));
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));
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));
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); }
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); }
164 if (psize & 1) == 1 {
171 return Ok((size + 8, false));
175 self.src.read_skip(size)?;
177 if size < 4 { return Err(InvalidData); }
178 self.src.read_skip(size - 4)?;
180 if (size & 1) == 1 { self.src.read_skip(1)?; }
181 return Ok((size + 8, false));
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);
192 let mut rest_size = size;
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; }
198 if !self.sstate.valid_state() || self.sstate.strm_no != self.num_streams {
199 return Err(InvalidData);
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)?;
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 },
222 fn is_list_tag(tag: u32) -> bool {
223 for i in 0..CHUNKS.len() {
224 if let RIFFTag::List(ltag, _) = CHUNKS[i].tag {
233 #[allow(unused_variables)]
234 fn parse_hdrl(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
238 #[allow(unused_variables)]
239 fn parse_strl(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
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()?;
264 dmx.src.read_skip(size - 0x38)?;
266 if !dmx.sstate.valid_state() || dmx.sstate.strm_no >= dmx.num_streams {
267 return Err(InvalidData);
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);
274 dmx.sstate.strm_type = Some(StreamType::Data);
276 dmx.sstate.got_strf = false;
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),
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()?;
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) {
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); }
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;
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) {
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); }
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); }
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;
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
374 dmx.cur_frame.resize(streams as usize, 0);
375 dmx.src.read_skip(size - 0x38)?;
379 fn parse_junk(dmx: &mut AVIDemuxer, size: usize) -> DemuxerResult<usize> {
380 dmx.src.read_skip(size)?;
384 pub struct AVIDemuxerCreator { }
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))
390 fn get_name(&self) -> &'static str { "avi" }
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);
407 let pktres = dmx.get_frame();
408 if let Err(e) = pktres {
409 if e == DemuxerError::EOF { break; }
412 let pkt = pktres.unwrap();
413 println!("Got {}", pkt);