1 use nihav_core::demuxers::*;
2 use nihav_registry::register;
3 use nihav_core::demuxers::DemuxerError::*;
7 ($a:expr, $b:expr, $c:expr, $d:expr) => ({
8 (($a as u32) << 24) | (($b as u32) << 16) | (($c as u32) << 8) | ($d as u32)
11 (($arr[0] as u32) << 24) | (($arr[1] as u32) << 16) | (($arr[2] as u32) << 8) | ($arr[3] as u32)
18 strm_type: Option<StreamType>,
23 StreamState { strm_no: 0, got_strf: true, strm_type: None }
26 self.strm_type = None;
30 fn valid_state(&self) -> bool {
31 match self.strm_type {
32 None => self.got_strf,
45 struct AVIDemuxer<'a> {
46 src: &'a mut ByteReader<'a>,
61 #[derive(Debug,Clone,Copy,PartialEq)]
69 parse: fn(&mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize>,
72 impl<'a> DemuxCore<'a> for AVIDemuxer<'a> {
73 fn open(&mut self, strmgr: &mut StreamManager, seek_index: &mut SeekIndex) -> DemuxerResult<()> {
74 self.read_header(strmgr, seek_index)?;
78 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket> {
79 if self.movi_size == 0 { return Err(EOF); }
80 let mut tag: [u8; 4] = [0; 4];
82 if (self.src.tell() & 1) == 1 {
83 self.src.read_skip(1)?;
85 if self.movi_size == 0 { return Err(EOF); }
87 let is_keyframe = self.key_offs.binary_search(&self.src.tell()).is_ok();
88 self.src.read_buf(&mut tag)?;
89 let size = self.src.read_u32le()? as usize;
90 if mktag!(tag) == mktag!(b"JUNK") {
91 self.movi_size -= size + 8;
92 self.src.read_skip(size)?;
93 if self.movi_size == 0 { return Err(EOF); }
96 if mktag!(tag) == mktag!(b"LIST") {
98 self.src.read_skip(4)?;
99 if self.movi_size == 0 { return Err(EOF); }
102 if (tag[0] == b'i' && tag[1] == b'x') || (&tag == b"idx1") {
105 if tag[0] < b'0' || tag[0] > b'9' || tag[1] < b'0' || tag[1] > b'9' {
106 return Err(InvalidData);
108 let stream_no = (tag[0] - b'0') * 10 + (tag[1] - b'0');
109 if tag[2] == b'p' && tag[3] == b'c' {
110 self.parse_palette_change(stream_no as usize, size)?;
111 self.movi_size -= size;
112 if self.movi_size == 0 { return Err(EOF); }
115 let str = strmgr.get_stream(stream_no as usize);
116 if str.is_none() { return Err(InvalidData); }
117 let stream = str.unwrap();
120 if self.movi_size == 0 { return Err(EOF); }
123 let (tb_num, tb_den) = stream.get_timebase();
124 let mut ts = NATimeInfo::new(Some(self.cur_frame[stream_no as usize]), None, None, tb_num, tb_den);
125 if stream.get_media_type() == StreamType::Audio && tb_num == 1 && stream.get_info().get_name() == "pcm" {
128 let mut pkt = self.src.read_packet(stream, ts, is_keyframe, size)?;
129 for pe in self.pal.iter_mut() {
130 if pe.stream_no == (stream_no as usize) {
131 pkt.add_side_data(NASideData::Palette(pe.changed, pe.pal.clone()));
136 self.cur_frame[stream_no as usize] += 1;
137 self.movi_size -= size + 8;
143 fn seek(&mut self, time: NATimePoint, seek_index: &SeekIndex) -> DemuxerResult<()> {
144 let ret = seek_index.find_pos(time);
146 return Err(DemuxerError::SeekError);
148 let seek_info = ret.unwrap();
150 if seek_info.pos < self.movi_pos { return Err(DemuxerError::SeekError); }
151 let skip_size = (seek_info.pos - self.movi_pos) as usize;
152 if skip_size > self.movi_size { return Err(DemuxerError::SeekError); }
153 self.movi_size = self.movi_orig - skip_size;
155 self.cur_frame[seek_info.str_id as usize] = seek_info.pts;
156 self.src.seek(SeekFrom::Start(seek_info.pos))?;
160 fn get_duration(&self) -> u64 { 0 }
163 impl<'a> NAOptionHandler for AVIDemuxer<'a> {
164 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
165 fn set_options(&mut self, _options: &[NAOption]) { }
166 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
169 impl<'a> AVIDemuxer<'a> {
170 fn new(io: &'a mut ByteReader<'a>) -> Self {
172 cur_frame: Vec::new(),
179 sstate: StreamState::new(),
183 key_offs: Vec::new(),
188 fn parse_chunk(&mut self, strmgr: &mut StreamManager, end_tag: RIFFTag, csize: usize, depth: u16) -> DemuxerResult<(usize, bool)> {
189 if csize < 8 { return Err(InvalidData); }
190 if depth > 42 { return Err(InvalidData); }
192 let tag = self.src.read_u32be()?;
193 let size = self.src.read_u32le()? as usize;
194 if size > csize { return Err(InvalidData); }
195 if RIFFTag::Chunk(tag) == end_tag {
196 return Ok((size, true));
198 let is_list = is_list_tag(tag);
199 let ltag = if is_list { self.src.read_u32be()? } else { 0 };
200 if RIFFTag::List(tag, ltag) == end_tag {
201 return Ok((size, true));
204 for chunk in CHUNKS.iter() {
205 if RIFFTag::Chunk(tag) == chunk.tag {
206 let psize = (chunk.parse)(self, strmgr, size)?;
207 if psize != size { return Err(InvalidData); }
208 if (psize & 1) == 1 { self.src.read_skip(1)?; }
209 return Ok((size + 8, false));
211 if RIFFTag::List(tag, ltag) == chunk.tag {
212 let mut rest_size = size - 4;
213 let psize = (chunk.parse)(self, strmgr, rest_size)?;
214 if psize > rest_size { return Err(InvalidData); }
216 while rest_size > 0 {
217 let (psize, _) = self.parse_chunk(strmgr, end_tag, rest_size, depth+1)?;
218 if psize > rest_size { return Err(InvalidData); }
220 if ((psize & 1) == 1) && (rest_size > 0) {
225 return Ok((size + 8, false));
229 self.src.read_skip(size)?;
231 if size < 4 { return Err(InvalidData); }
232 self.src.read_skip(size - 4)?;
234 if (size & 1) == 1 { self.src.read_skip(1)?; }
235 Ok((size + 8, false))
238 fn read_header(&mut self, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex) -> DemuxerResult<()> {
239 let riff_tag = self.src.read_u32be()?;
240 let size = self.src.read_u32le()? as usize;
241 let avi_tag = self.src.read_u32be()?;
242 let mut matches = false;
243 for rt in RIFF_TAGS.iter() {
244 if rt[0] == riff_tag && rt[1] == avi_tag {
250 return Err(InvalidData);
253 let mut rest_size = size;
255 let (csz, end) = self.parse_chunk(strmgr, RIFFTag::List(mktag!(b"LIST"), mktag!(b"movi")), rest_size,0)?;
257 self.movi_size = csz - 4;
258 self.movi_orig = self.movi_size;
259 self.movi_pos = self.src.tell();
264 if !seek_idx.skip_index {
265 self.src.read_skip(self.movi_size)?;
266 while rest_size > 0 {
267 let ret = self.parse_chunk(strmgr, RIFFTag::Chunk(mktag!(b"idx1")), rest_size,0);
268 if ret.is_err() { break; }
269 let (csz, end) = ret.unwrap();
271 let _res = parse_idx1(&mut self.src, strmgr, seek_idx, csz, self.movi_pos, &mut self.key_offs);
277 if self.movi_pos != 0 {
278 self.src.seek(SeekFrom::Start(self.movi_pos))?;
280 return Err(InvalidData);
282 if !self.sstate.valid_state() || self.sstate.strm_no != self.num_streams {
283 return Err(InvalidData);
288 fn read_extradata(&mut self, size: usize) -> DemuxerResult<Option<Vec<u8>>> {
289 if size == 0 { return Ok(None); }
290 let mut edvec: Vec<u8> = vec![0; size];
291 self.src.read_buf(&mut edvec)?;
295 fn parse_palette_change(&mut self, stream_no: usize, size: usize) -> DemuxerResult<()> {
296 for pe in self.pal.iter_mut() {
297 if pe.stream_no == stream_no {
298 let start_clr = self.src.read_byte()? as usize;
299 let len = self.src.read_byte()? as usize;
300 let _flags = self.src.read_u16le()?;
301 validate!(start_clr + len <= 256);
302 validate!(len * 4 + 4 == size);
303 let mut newpal = *pe.pal;
304 for i in start_clr..(start_clr + len) {
305 newpal[i * 4] = self.src.read_byte()?;
306 newpal[i * 4 + 1] = self.src.read_byte()?;
307 newpal[i * 4 + 2] = self.src.read_byte()?;
308 newpal[i * 4 + 3] = 0;
309 self.src.read_byte()?; // flags
311 pe.pal = Arc::new(newpal);
316 self.src.read_skip(size)?;
321 const RIFF_TAGS: &[[u32; 2]] = &[
322 [ mktag!(b"RIFF"), mktag!(b"AVI ") ],
323 [ mktag!(b"RIFF"), mktag!(b"AVIX") ],
324 [ mktag!(b"ON2 "), mktag!(b"ON2f") ],
327 const CHUNKS: [RIFFParser; 7] = [
328 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"hdrl")), parse: parse_hdrl },
329 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"strl")), parse: parse_strl },
330 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"avih")), parse: parse_avih },
331 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"ON2h")), parse: parse_avih },
332 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"strf")), parse: parse_strf },
333 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"strh")), parse: parse_strh },
334 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"JUNK")), parse: parse_junk },
337 fn is_list_tag(tag: u32) -> bool {
338 for chunk in CHUNKS.iter() {
339 if let RIFFTag::List(ltag, _) = chunk.tag {
348 #[allow(unused_variables)]
349 fn parse_hdrl(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
353 #[allow(unused_variables)]
354 fn parse_strl(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
358 #[allow(unused_variables)]
359 fn parse_strh(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
360 if size < 0x38 { return Err(InvalidData); }
361 let tag = dmx.src.read_u32be()?; //stream type
362 let fcc = dmx.src.read_u32be()?; //handler(fourcc)
363 dmx.src.read_u32le()?; //flags
364 dmx.src.read_skip(2)?; //priority
365 dmx.src.read_skip(2)?; //language
366 dmx.src.read_skip(4)?; //initial frames
367 dmx.tb_num = dmx.src.read_u32le()?; //scale
368 dmx.tb_den = dmx.src.read_u32le()?; //rate
369 dmx.src.read_skip(4)?; //start
370 dmx.strm_duration = dmx.src.read_u32le()?;
371 dmx.src.read_skip(4)?; //buf size
372 dmx.src.read_skip(4)?; //quality
373 dmx.src.read_skip(4)?; //sample size
374 let a = dmx.src.read_u16le()?;
375 let b = dmx.src.read_u16le()?;
376 let c = dmx.src.read_u16le()?;
377 let d = dmx.src.read_u16le()?;
379 dmx.src.read_skip(size - 0x38)?;
381 if !dmx.sstate.valid_state() || dmx.sstate.strm_no >= dmx.num_streams {
382 return Err(InvalidData);
384 if tag == mktag!(b"vids") {
385 dmx.sstate.strm_type = Some(StreamType::Video);
386 } else if tag == mktag!(b"auds") {
387 dmx.sstate.strm_type = Some(StreamType::Audio);
389 dmx.sstate.strm_type = Some(StreamType::Data);
391 dmx.sstate.got_strf = false;
396 fn parse_strf(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
397 if dmx.sstate.strm_type.is_none() { return Err(InvalidData); }
398 match dmx.sstate.strm_type.unwrap() {
399 StreamType::Video => parse_strf_vids(dmx, strmgr, size),
400 StreamType::Audio => parse_strf_auds(dmx, strmgr, size),
401 _ => parse_strf_xxxx(dmx, strmgr, size),
405 #[allow(unused_variables)]
406 fn parse_strf_vids(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
407 if size < 40 { return Err(InvalidData); }
408 let bi_size = dmx.src.read_u32le()?;
409 if (bi_size as usize) < 40 { return Err(InvalidData); }
410 let width = dmx.src.read_u32le()?;
411 let height = dmx.src.read_u32le()? as i32;
412 let planes = dmx.src.read_u16le()?;
413 let bitcount = dmx.src.read_u16le()?;
414 let mut compression: [u8; 4] = [0; 4];
415 dmx.src.read_buf(&mut compression)?;
416 let img_size = dmx.src.read_u32le()?;
417 let xdpi = dmx.src.read_u32le()?;
418 let ydpi = dmx.src.read_u32le()?;
419 let colors = dmx.src.read_u32le()?;
420 validate!(colors <= 256);
421 let imp_colors = dmx.src.read_u32le()?;
423 let flip = height < 0;
424 let format = if bitcount > 8 { RGB24_FORMAT } else { PAL8_FORMAT };
425 let mut vhdr = NAVideoInfo::new(width as usize, if flip { -height as usize } else { height as usize}, flip, format);
426 vhdr.bits = (planes as u8) * (bitcount as u8);
427 let cname = if find_raw_fmt(&compression, planes, bitcount, &mut vhdr) {
430 match register::find_codec_from_avi_fourcc(&compression) {
435 let vci = NACodecTypeInfo::Video(vhdr);
436 let edata = dmx.read_extradata(size - 40)?;
438 if let Some(ref buf) = edata {
439 let mut pal = [0u8; 1024];
440 for (dpal, spal) in pal.chunks_mut(4).take(colors as usize).zip(buf.chunks(4)) {
446 let pal = PalInfo { pal: Arc::new(pal), changed: true, stream_no: strmgr.get_num_streams() };
450 let vinfo = NACodecInfo::new(cname, vci, edata);
451 let res = strmgr.add_stream(NAStream::new(StreamType::Video, u32::from(dmx.sstate.strm_no), vinfo, dmx.tb_num, dmx.tb_den, u64::from(dmx.strm_duration)));
452 if res.is_none() { return Err(MemoryError); }
457 fn find_raw_fmt(compr: &[u8; 4], planes: u16, bitcount: u16, vhdr: &mut NAVideoInfo) -> bool {
459 &[0, 0, 0, 0] | b"DIB " => {
463 let fmt_name = match bitcount {
470 if let Ok(fmt) = NAPixelFormaton::from_str(fmt_name) {
482 #[allow(unused_variables)]
483 fn parse_strf_auds(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
484 if size < 16 { return Err(InvalidData); }
485 let w_format_tag = dmx.src.read_u16le()?;
486 let channels = dmx.src.read_u16le()?;
487 let samplespersec = dmx.src.read_u32le()?;
488 let avgbytespersec = dmx.src.read_u32le()?;
489 let block_align = dmx.src.read_u16le()?;
490 let bits_per_sample = dmx.src.read_u16le()?;
492 let signed = bits_per_sample > 8;
493 let soniton = NASoniton::new(bits_per_sample as u8, if signed { SONITON_FLAG_SIGNED } else { 0 });
494 let ahdr = NAAudioInfo::new(samplespersec, channels as u8, soniton, block_align as usize);
495 let edata = if size > 16 {
496 let edata_size = dmx.src.read_u16le()? as usize;
497 validate!(edata_size + 18 <= size);
498 dmx.read_extradata(size - 18)?
502 let cname = match register::find_codec_from_wav_twocc(w_format_tag) {
506 let ainfo = NACodecInfo::new(cname, NACodecTypeInfo::Audio(ahdr), edata);
507 let res = strmgr.add_stream(NAStream::new(StreamType::Audio, u32::from(dmx.sstate.strm_no), ainfo, dmx.tb_num, dmx.tb_den, u64::from(dmx.strm_duration)));
508 if res.is_none() { return Err(MemoryError); }
513 fn parse_strf_xxxx(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
514 let edata = dmx.read_extradata(size)?;
515 let info = NACodecInfo::new("unknown", NACodecTypeInfo::None, edata);
516 let res = strmgr.add_stream(NAStream::new(StreamType::Data, u32::from(dmx.sstate.strm_no), info, dmx.tb_num, dmx.tb_den, u64::from(dmx.strm_duration)));
517 if res.is_none() { return Err(MemoryError); }
522 #[allow(unused_variables)]
523 fn parse_avih(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
524 if size < 0x38 { return Err(InvalidData); }
525 let timebase = dmx.src.read_u32le()?; //microsec per frame
526 dmx.src.read_skip(4)?; //max frame size
527 dmx.src.read_skip(4)?; //padding
528 dmx.src.read_u32le()?; //flags
529 let frames = dmx.src.read_u32le()?; //frames
530 dmx.src.read_skip(4)?; //initial frames
531 let streams = dmx.src.read_u32le()?; //streams
532 if streams > 100 { return Err(InvalidData); }
533 dmx.num_streams = streams as u8;
535 dmx.src.read_skip(4)?; //buf size
536 let width = dmx.src.read_u32le()?; //width
537 let height = dmx.src.read_u32le()? as i32; //height
538 dmx.src.read_skip(16)?; //reserved
540 dmx.cur_frame.resize(streams as usize, 0);
541 dmx.src.read_skip(size - 0x38)?;
545 #[allow(unused_variables)]
546 fn parse_junk(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
547 dmx.src.read_skip(size)?;
551 #[allow(clippy::verbose_bit_mask)]
552 fn parse_idx1(src: &mut ByteReader, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex, size: usize, movi_pos: u64, key_offs: &mut Vec<u64>) -> DemuxerResult<usize> {
553 validate!((size & 15) == 0);
554 let mut tag = [0u8; 4];
555 let num_entries = size >> 4;
556 let mut counter = [0u64; 100];
557 let mut add_offset = 0;
558 let mut set_offset = false;
559 for _ in 0..num_entries {
560 src.read_buf(&mut tag)?;
561 let flags = src.read_u32le()?;
562 let mut offset = src.read_u32le()? as u64;
563 let _length = src.read_u32le()?;
565 if !set_offset && offset < movi_pos {
566 add_offset = movi_pos - offset;
570 offset += add_offset;
572 if tag[0] < b'0' || tag[0] > b'9' || tag[1] < b'0' || tag[1] > b'9' {
573 return Err(InvalidData);
575 let stream_no = ((tag[0] - b'0') * 10 + (tag[1] - b'0')) as usize;
577 if (flags & 0x10) != 0 {
578 if let Some(str) = strmgr.get_stream(stream_no) {
579 if str.get_media_type() == StreamType::Video {
580 let (tb_num, tb_den) = str.get_timebase();
581 let pts = counter[stream_no];
582 let time = NATimeInfo::ts_to_time(pts, 1000, tb_num, tb_den);
583 validate!(offset >= movi_pos);
584 seek_idx.add_entry(stream_no as u32, SeekEntry { time, pts, pos: offset });
586 key_offs.push(offset);
589 counter[stream_no] += 1;
591 key_offs.sort_unstable();
595 pub struct AVIDemuxerCreator { }
597 impl DemuxerCreator for AVIDemuxerCreator {
598 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a> {
599 Box::new(AVIDemuxer::new(br))
601 fn get_name(&self) -> &'static str { "avi" }
610 fn test_avi_demux() {
611 let mut file = File::open("assets/Indeo/laser05.avi").unwrap();
612 let mut fr = FileReader::new_read(&mut file);
613 let mut br = ByteReader::new(&mut fr);
614 let mut dmx = AVIDemuxer::new(&mut br);
615 let mut sm = StreamManager::new();
616 let mut si = SeekIndex::new();
617 dmx.open(&mut sm, &mut si).unwrap();
620 let pktres = dmx.get_frame(&mut sm);
621 if let Err(e) = pktres {
622 if e == DemuxerError::EOF { break; }
625 let pkt = pktres.unwrap();
626 println!("Got {}", pkt);