1 use nihav_core::demuxers::*;
2 use nihav_registry::register::*;
5 ($a:expr, $b:expr, $c:expr, $d:expr) => ({
6 (($a as u32) << 24) | (($b as u32) << 16) | (($c as u32) << 8) | ($d as u32)
9 (($arr[0] as u32) << 24) | (($arr[1] as u32) << 16) | (($arr[2] as u32) << 8) | ($arr[3] as u32)
14 fn skip64(&mut self, size: u64) -> ByteIOResult<()>;
17 impl<'a> Skip64 for ByteReader<'a> {
18 fn skip64(&mut self, size: u64) -> ByteIOResult<()> {
19 if (size as usize as u64) != size {
20 self.seek(SeekFrom::Current(size as i64))?;
22 self.read_skip(size as usize)?;
28 fn read_chunk_header(br: &mut ByteReader) -> DemuxerResult<(u32, u64)> {
29 let size = br.read_u32be()?;
30 let ctype = br.read_u32be()?;
32 Ok((ctype, br.left() as u64))
34 let size64 = br.read_u64be()?;
35 validate!(size64 >= 16);
36 Ok((ctype, size64 - 16))
39 Ok((ctype, (size as u64) - 8))
43 fn read_palette(br: &mut ByteReader, size: u64, pal: &mut [u8; 1024]) -> DemuxerResult<u64> {
44 let _seed = br.read_u32be()?;
45 let _flags = br.read_u16be()?;
46 let palsize = (br.read_u16be()? as usize) + 1;
47 validate!(palsize <= 256);
48 validate!((palsize as u64) * 8 + 8 == size);
50 let a = br.read_u16be()?;
51 let r = br.read_u16be()?;
52 let g = br.read_u16be()?;
53 let b = br.read_u16be()?;
54 pal[i * 4] = (r >> 8) as u8;
55 pal[i * 4 + 1] = (g >> 8) as u8;
56 pal[i * 4 + 2] = (b >> 8) as u8;
57 pal[i * 4 + 3] = (a >> 8) as u8;
62 struct RootChunkHandler {
64 parse: fn(dmx: &mut MOVDemuxer, strmgr: &mut StreamManager, size: u64) -> DemuxerResult<u64>,
67 struct TrackChunkHandler {
69 parse: fn(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64>,
72 const IGNORED_CHUNKS: &[u32] = &[
73 mktag!(b"free"), mktag!(b"skip"), mktag!(b"udta"), mktag!(b"wide")
76 const ROOT_CHUNK_HANDLERS: &[RootChunkHandler] = &[
77 RootChunkHandler { ctype: mktag!(b"ftyp"), parse: read_ftyp },
78 RootChunkHandler { ctype: mktag!(b"mdat"), parse: read_mdat },
79 RootChunkHandler { ctype: mktag!(b"moov"), parse: read_moov },
82 macro_rules! read_chunk_list {
83 (root; $name: expr, $fname: ident, $handlers: ident) => {
84 fn $fname(&mut self, strmgr: &mut StreamManager, size: u64) -> DemuxerResult<()> {
86 validate!(self.depth < 32);
87 let list_end = self.src.tell() + size;
88 while self.src.tell() < list_end {
89 let ret = read_chunk_header(&mut self.src);
90 if ret.is_err() { break; }
91 let (ctype, size) = ret.unwrap();
92 if self.src.tell() + size > list_end {
95 if IGNORED_CHUNKS.contains(&ctype) {
96 self.src.skip64(size)?;
99 let handler = $handlers.iter().find(|x| x.ctype == ctype);
101 if let Some(ref handler) = handler {
102 read_size = (handler.parse)(self, strmgr, size)?;
104 println!("skipping unknown chunk {:08X} size {}", ctype, size);
107 validate!(read_size <= size);
108 self.src.skip64(size - read_size)?;
111 validate!(self.src.tell() == list_end);
115 (track; $name: expr, $fname: ident, $handlers: ident) => {
116 fn $fname(&mut self, br: &mut ByteReader, size: u64) -> DemuxerResult<()> {
118 validate!(self.depth < 32);
119 let list_end = br.tell() + size;
120 while br.tell() < list_end {
121 let ret = read_chunk_header(br);
122 if ret.is_err() { break; }
123 let (ctype, size) = ret.unwrap();
124 if br.tell() + size > list_end {
127 if IGNORED_CHUNKS.contains(&ctype) {
131 let handler = $handlers.iter().find(|x| x.ctype == ctype);
133 if let Some(ref handler) = handler {
134 read_size = (handler.parse)(self, br, size)?;
138 validate!(read_size <= size);
139 br.skip64(size - read_size)?;
142 validate!(br.tell() == list_end);
148 fn skip_chunk(_track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
153 fn read_ftyp(dmx: &mut MOVDemuxer, _strmgr: &mut StreamManager, size: u64) -> DemuxerResult<u64> {
154 dmx.src.skip64(size)?;
158 fn read_mdat(dmx: &mut MOVDemuxer, _strmgr: &mut StreamManager, size: u64) -> DemuxerResult<u64> {
159 dmx.mdat_pos = dmx.src.tell();
160 dmx.mdat_size = size;
161 dmx.src.skip64(size)?;
165 fn read_moov(dmx: &mut MOVDemuxer, strmgr: &mut StreamManager, size: u64) -> DemuxerResult<u64> {
166 dmx.read_moov(strmgr, size)?;
170 const MOOV_CHUNK_HANDLERS: &[RootChunkHandler] = &[
171 RootChunkHandler { ctype: mktag!(b"mvhd"), parse: read_mvhd },
172 RootChunkHandler { ctype: mktag!(b"ctab"), parse: read_ctab },
173 RootChunkHandler { ctype: mktag!(b"trak"), parse: read_trak },
174 RootChunkHandler { ctype: mktag!(b"meta"), parse: read_meta },
177 fn read_mvhd(dmx: &mut MOVDemuxer, _strmgr: &mut StreamManager, size: u64) -> DemuxerResult<u64> {
178 const KNOWN_MVHD_SIZE: u64 = 100;
179 let br = &mut dmx.src;
180 validate!(size >= KNOWN_MVHD_SIZE);
181 let version = br.read_byte()?;
182 validate!(version == 0);
183 let _flags = br.read_u24be()?;
184 let _ctime = br.read_u32be()?;
185 let _mtime = br.read_u32be()?;
186 let tscale = br.read_u32be()?;
187 let duration = br.read_u32be()?;
188 let _pref_rate = br.read_u32be()?;
189 let _pref_volume = br.read_u16be()?;
191 br.read_skip(36)?; // matrix
192 let _preview_time = br.read_u32be()?;
193 let _preview_duration = br.read_u32be()?;
194 let _poster_time = br.read_u32be()?;
195 let _sel_time = br.read_u32be()?;
196 let _sel_duration = br.read_u32be()?;
197 let _cur_time = br.read_u32be()?;
198 let _next_track_id = br.read_u32be()?;
199 dmx.duration = duration;
205 fn read_ctab(dmx: &mut MOVDemuxer, _strmgr: &mut StreamManager, size: u64) -> DemuxerResult<u64> {
206 let mut pal = [0; 1024];
207 let size = read_palette(&mut dmx.src, size, &mut pal)?;
208 dmx.pal = Some(Arc::new(pal));
212 fn read_meta(dmx: &mut MOVDemuxer, _strmgr: &mut StreamManager, size: u64) -> DemuxerResult<u64> {
213 dmx.src.skip64(size)?;
217 fn read_trak(dmx: &mut MOVDemuxer, strmgr: &mut StreamManager, size: u64) -> DemuxerResult<u64> {
218 let mut track = Track::new(dmx.cur_track as u32, dmx.tb_den);
219 track.read_trak(&mut dmx.src, size)?;
220 validate!(track.tkhd_found && track.stsd_found);
221 validate!(strmgr.get_stream_by_id(track.track_id).is_none());
224 std::mem::swap(&mut track.stream, &mut str);
225 if let Some(stream) = str {
226 let str_id = strmgr.add_stream(stream).unwrap();
227 track.track_str_id = str_id;
229 dmx.tracks.push(track);
233 const TRAK_CHUNK_HANDLERS: &[TrackChunkHandler] = &[
234 TrackChunkHandler { ctype: mktag!(b"clip"), parse: skip_chunk },
235 TrackChunkHandler { ctype: mktag!(b"matt"), parse: skip_chunk },
236 TrackChunkHandler { ctype: mktag!(b"edts"), parse: skip_chunk },
237 TrackChunkHandler { ctype: mktag!(b"tref"), parse: skip_chunk },
238 TrackChunkHandler { ctype: mktag!(b"load"), parse: skip_chunk },
239 TrackChunkHandler { ctype: mktag!(b"imap"), parse: skip_chunk },
240 TrackChunkHandler { ctype: mktag!(b"tkhd"), parse: read_tkhd },
241 TrackChunkHandler { ctype: mktag!(b"mdia"), parse: read_mdia },
244 fn read_tkhd(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
245 const KNOWN_TKHD_SIZE: u64 = 84;
246 validate!(size >= KNOWN_TKHD_SIZE);
247 let version = br.read_byte()?;
248 validate!(version == 0);
249 let _flags = br.read_u24be()?;
250 let _ctime = br.read_u32be()?;
251 let _mtime = br.read_u32be()?;
252 let track_id = br.read_u32be()?;
254 let _duration = br.read_u32be()?;
256 let _layer = br.read_u16be()?;
257 let _alt_group = br.read_u16be()?;
258 let _volume = br.read_u16be()?;
260 br.read_skip(36)?; // matrix
261 let width = br.read_u32be()? as usize;
262 let height = br.read_u32be()? as usize;
263 track.width = width >> 16;
264 track.height = height >> 16;
265 track.track_id = track_id;
267 track.tkhd_found = true;
271 fn read_mdia(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
272 track.stream_type = StreamType::None;
273 track.read_mdia(br, size)?;
277 const MDIA_CHUNK_HANDLERS: &[TrackChunkHandler] = &[
278 TrackChunkHandler { ctype: mktag!(b"mdhd"), parse: skip_chunk },
279 TrackChunkHandler { ctype: mktag!(b"hdlr"), parse: read_hdlr },
280 TrackChunkHandler { ctype: mktag!(b"minf"), parse: read_minf },
283 fn read_hdlr(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
284 const KNOWN_HDLR_SIZE: u64 = 24;
285 validate!(size >= KNOWN_HDLR_SIZE);
286 let version = br.read_byte()?;
287 validate!(version == 0);
288 let flags = br.read_u24be()?;
289 validate!(flags == 0);
290 let comp_type = br.read_u32be()?;
291 let comp_subtype = br.read_u32be()?;
292 let _comp_manufacturer = br.read_u32be()?;
293 let _comp_flags = br.read_u32be()?;
294 let _comp_flags_mask = br.read_u32be()?;
296 if comp_type == mktag!(b"mhlr") {
297 if comp_subtype == mktag!(b"vide") {
298 track.stream_type = StreamType::Video;
299 } else if comp_subtype == mktag!(b"soun") {
300 track.stream_type = StreamType::Audio;
302 track.stream_type = StreamType::Data;
304 } else if comp_type == mktag!(b"dhlr") {
305 track.stream_type = StreamType::Data;
307 println!("Unknown stream type");
308 track.stream_type = StreamType::Data;
314 fn read_minf(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
315 track.read_minf(br, size)?;
319 const MINF_CHUNK_HANDLERS: &[TrackChunkHandler] = &[
320 TrackChunkHandler { ctype: mktag!(b"hdlr"), parse: skip_chunk },
321 TrackChunkHandler { ctype: mktag!(b"dinf"), parse: skip_chunk },
322 TrackChunkHandler { ctype: mktag!(b"vmhd"), parse: read_vmhd },
323 TrackChunkHandler { ctype: mktag!(b"smhd"), parse: read_smhd },
324 TrackChunkHandler { ctype: mktag!(b"gmhd"), parse: read_gmhd },
325 TrackChunkHandler { ctype: mktag!(b"gmin"), parse: read_gmin },
326 TrackChunkHandler { ctype: mktag!(b"stbl"), parse: read_stbl },
329 fn read_vmhd(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
330 const KNOWN_VMHD_SIZE: u64 = 12;
331 validate!(track.stream_type == StreamType::Video);
332 validate!(size >= KNOWN_VMHD_SIZE);
333 let version = br.read_byte()?;
334 validate!(version == 0);
335 let _flags = br.read_u24be()?;
336 br.read_skip(2)?; // graphics mode
337 br.read_skip(6)?; // opcolor
341 fn read_smhd(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
342 const KNOWN_SMHD_SIZE: u64 = 8;
343 validate!(track.stream_type == StreamType::Audio);
344 validate!(size >= KNOWN_SMHD_SIZE);
345 let version = br.read_byte()?;
346 validate!(version == 0);
347 let _flags = br.read_u24be()?;
348 br.read_skip(2)?; // balance
353 fn read_gmhd(track: &mut Track, _br: &mut ByteReader, _size: u64) -> DemuxerResult<u64> {
354 validate!(track.stream_type == StreamType::Data);
358 fn read_gmin(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
359 validate!(track.stream_type == StreamType::Data);
360 const KNOWN_GMIN_SIZE: u64 = 16;
361 validate!(size >= KNOWN_GMIN_SIZE);
362 let version = br.read_byte()?;
363 validate!(version == 0);
364 let _flags = br.read_u24be()?;
365 br.read_skip(2)?; // graphics mode
366 br.read_skip(6)?; // opcolor
367 br.read_skip(2)?; // balance
372 fn read_stbl(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
373 track.read_stbl(br, size)?;
377 const STBL_CHUNK_HANDLERS: &[TrackChunkHandler] = &[
378 TrackChunkHandler { ctype: mktag!(b"stsd"), parse: read_stsd },
379 TrackChunkHandler { ctype: mktag!(b"stts"), parse: skip_chunk },
380 TrackChunkHandler { ctype: mktag!(b"stss"), parse: read_stss },
381 TrackChunkHandler { ctype: mktag!(b"stsc"), parse: read_stsc },
382 TrackChunkHandler { ctype: mktag!(b"stsz"), parse: read_stsz },
383 TrackChunkHandler { ctype: mktag!(b"stco"), parse: read_stco },
384 TrackChunkHandler { ctype: mktag!(b"stsh"), parse: skip_chunk },
387 fn read_stsd(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
388 const KNOWN_STSD_SIZE: u64 = 24;
389 validate!(size >= KNOWN_STSD_SIZE);
390 let start_pos = br.tell();
391 let version = br.read_byte()?;
392 validate!(version == 0);
393 let _flags = br.read_u24be()?;
394 let entries = br.read_u32be()?;
395 validate!(entries > 0);
396 let esize = br.read_u32be()? as u64;
397 validate!(esize + 8 <= size);
398 let mut fcc = [0u8; 4];
399 br.read_buf(&mut fcc)?;
401 let _data_ref = br.read_u16be()?;
406 match track.stream_type {
407 StreamType::Video => {
408 let _ver = br.read_u16be()?;
409 let _revision = br.read_u16le()?;
410 let _vendor = br.read_u32be()?;
411 let _temp_quality = br.read_u32be()?;
412 let _spat_quality = br.read_u32be()?;
413 let width = br.read_u16be()? as usize;
414 let height = br.read_u16be()? as usize;
415 let _hor_res = br.read_u32be()?;
416 let _vert_res = br.read_u32be()?;
417 let data_size = br.read_u32be()?;
418 validate!(data_size == 0);
419 let _frame_count = br.read_u16be()? as usize;
420 let _cname_len = br.read_byte()? as usize;
421 br.read_skip(31)?; // actual compressor name
422 let depth = br.read_u16be()?;
423 let ctable_id = br.read_u16be()?;
424 validate!((depth <= 8) || (ctable_id == 0xFFFF));
426 let max_pal_size = start_pos + size - br.tell();
427 let mut pal = [0; 1024];
428 read_palette(br, max_pal_size, &mut pal)?;
429 track.pal = Some(Arc::new(pal));
431 // todo other atoms, put as extradata
432 let cname = if let Some(name) = find_codec_from_mov_video_fourcc(&fcc) {
434 } else if let Some(name) = find_codec_from_avi_fourcc(&fcc) {
439 let format = if depth > 8 { RGB24_FORMAT } else { PAL8_FORMAT };
440 let vhdr = NAVideoInfo::new(width, height, false, format);
442 if br.tell() - start_pos + 4 < size {
443 //todo skip various common atoms
444 let edata_size = br.read_u32be()? as usize;
445 let mut buf = vec![0; edata_size];
446 br.read_buf(buf.as_mut_slice())?;
451 codec_info = NACodecInfo::new(cname, NACodecTypeInfo::Video(vhdr), edata);
453 StreamType::Audio => {
454 let _ver = br.read_u16be()?;
455 let _revision = br.read_u16le()?;
456 let _vendor = br.read_u32be()?;
457 let nchannels = br.read_u16be()?;
458 validate!(nchannels <= 64);
459 let sample_size = br.read_u16be()?;
460 validate!(sample_size <= 128);
461 let _compr_id = br.read_u16be()?;
462 let packet_size = br.read_u16be()? as usize;
463 validate!(packet_size == 0);
464 let sample_rate = br.read_u32be()?;
465 validate!(sample_rate > 0);
466 let cname = if let Some(name) = find_codec_from_mov_audio_fourcc(&fcc) {
468 } else if let (true, Some(name)) = ((fcc[0] == b'm' && fcc[1] == b's'), find_codec_from_wav_twocc(u16::from(fcc[2]) * 256 + u16::from(fcc[3]))) {
473 //todo adjust format for various PCM kinds
474 let soniton = NASoniton::new(sample_size as u8, SONITON_FLAG_SIGNED | SONITON_FLAG_BE);
476 let ahdr = NAAudioInfo::new(sample_rate >> 16, nchannels as u8, soniton, block_align);
478 codec_info = NACodecInfo::new(cname, NACodecTypeInfo::Audio(ahdr), edata);
479 track.channels = nchannels as usize;
480 track.bits = sample_size as usize;
482 StreamType::None => {
483 return Err(DemuxerError::InvalidData);
486 //todo put it all into extradata
488 codec_info = NACodecInfo::new("unknown", NACodecTypeInfo::None, edata);
491 let read_size = br.tell() - start_pos;
492 validate!(read_size <= size);
493 track.stream = Some(NAStream::new(track.stream_type, track.track_no, codec_info, 1, track.tb_den));
494 track.stsd_found = true;
498 fn read_stss(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
499 let version = br.read_byte()?;
500 validate!(version == 0);
501 let _flags = br.read_u24be()?;
502 let entries = br.read_u32be()? as usize;
503 validate!(entries < ((std::u32::MAX >> 2) - 8) as usize);
504 validate!((entries * 4 + 8) as u64 == size);
505 track.keyframes = Vec::with_capacity(entries);
506 let mut last_sample_no = 0;
507 for _ in 0..entries {
508 let sample_no = br.read_u32be()?;
509 validate!(sample_no > last_sample_no);
510 track.keyframes.push(sample_no);
511 last_sample_no = sample_no;
516 fn read_stsc(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
517 let version = br.read_byte()?;
518 validate!(version == 0);
519 let _flags = br.read_u24be()?;
520 let entries = br.read_u32be()? as usize;
521 validate!(entries < ((std::u32::MAX / 12) - 8) as usize);
522 validate!((entries * 12 + 8) as u64 == size);
523 track.sample_map = Vec::with_capacity(entries);
524 let mut last_sample_no = 0;
525 for _i in 0..entries {
526 let sample_no = br.read_u32be()?;
527 validate!(sample_no > last_sample_no);
528 let nsamples = br.read_u32be()?;
529 let _sample_desc = br.read_u32be()?;
530 track.sample_map.push((sample_no, nsamples));
531 last_sample_no = sample_no;
536 fn read_stsz(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
537 let version = br.read_byte()?;
538 validate!(version == 0);
539 let _flags = br.read_u24be()?;
540 let sample_size = br.read_u32be()?;
541 if sample_size != 0 {
542 track.sample_size = sample_size;
545 let entries = br.read_u32be()? as usize;
546 validate!((entries * 4 + 12) as u64 == size);
547 track.chunk_sizes = Vec::with_capacity(entries);
548 for _ in 0..entries {
549 let sample_size = br.read_u32be()?;
550 track.chunk_sizes.push(sample_size);
556 fn read_stco(track: &mut Track, br: &mut ByteReader, size: u64) -> DemuxerResult<u64> {
557 let version = br.read_byte()?;
558 validate!(version == 0);
559 let _flags = br.read_u24be()?;
560 let entries = br.read_u32be()? as usize;
561 validate!((entries * 4 + 8) as u64 == size);
562 track.chunk_offsets = Vec::with_capacity(entries);
563 for _i in 0..entries {
564 let sample_offset = br.read_u32be()?;
565 track.chunk_offsets.push(u64::from(sample_offset));
570 struct MOVDemuxer<'a> {
571 src: &'a mut ByteReader<'a>,
579 pal: Option<Arc<[u8; 1024]>>,
590 stream_type: StreamType,
597 chunk_sizes: Vec<u32>,
598 chunk_offsets: Vec<u64>,
599 sample_map: Vec<(u32, u32)>,
601 stream: Option<NAStream>,
606 pal: Option<Arc<[u8; 1024]>>,
610 fn new(track_no: u32, tb_den: u32) -> Self {
618 stream_type: StreamType::None,
624 keyframes: Vec::new(),
625 chunk_sizes: Vec::new(),
626 chunk_offsets: Vec::new(),
627 sample_map: Vec::new(),
638 read_chunk_list!(track; "trak", read_trak, TRAK_CHUNK_HANDLERS);
639 read_chunk_list!(track; "mdia", read_mdia, MDIA_CHUNK_HANDLERS);
640 read_chunk_list!(track; "minf", read_minf, MINF_CHUNK_HANDLERS);
641 read_chunk_list!(track; "stbl", read_stbl, STBL_CHUNK_HANDLERS);
642 fn fill_seek_index(&self, seek_index: &mut SeekIndex) {
643 if self.keyframes.len() > 0 {
644 seek_index.mode = SeekIndexMode::Present;
646 for kf_time in self.keyframes.iter() {
647 let pts = u64::from(*kf_time - 1);
648 let time = NATimeInfo::ts_to_time(pts, 1000, 1, self.tb_den);
649 let idx = (*kf_time - 1) as usize;
650 if idx < self.chunk_offsets.len() {
651 let pos = self.chunk_offsets[idx];
652 seek_index.add_entry(self.track_no as u32, SeekEntry { time, pts, pos });
656 fn calculate_chunk_size(&self, nsamp: usize) -> usize {
658 self.sample_size as usize
661 b"NONE" | b"raw " | b"twos" | b"sowt" => {
662 (nsamp * self.bits * self.channels + 7) >> 3
665 let nblocks = (nsamp + 63) >> 6;
666 nblocks * 34 * self.channels
669 (nsamp + 5) / 6 * 2 * self.channels
672 (nsamp + 5) / 6 * self.channels
674 b"in24" => nsamp * 3 * self.channels,
675 b"in32" | b"fl32" => nsamp * 4 * self.channels,
676 b"fl64" => nsamp * 8 * self.channels,
677 b"ulaw" | b"alaw" => nsamp,
678 b"ms\x00\x02" => { //MS ADPCM
679 ((nsamp - 1) / 2 + 7) * self.channels
681 b"ms\x00\x21" => { //IMA ADPCM
682 (nsamp / 2 + 4) * self.channels
684 _ => self.sample_size as usize,
688 fn get_next_chunk(&mut self) -> Option<(NATimeInfo, u64, usize)> {
689 let pts = NATimeInfo::new(Some(self.cur_sample as u64), None, None, 1, self.tb_den);
691 if self.chunk_offsets.len() == self.chunk_sizes.len() { // simple one-to-one mapping
692 if self.cur_sample >= self.chunk_sizes.len() {
695 let offset = self.chunk_offsets[self.cur_sample];
696 let size = self.chunk_sizes[self.cur_sample] as usize;
697 self.cur_sample += 1;
698 Some((pts, offset, size))
700 if self.samples_left == 0 {
701 if self.cur_chunk >= self.chunk_offsets.len() {
704 for (idx, samples) in self.sample_map.iter() {
705 if *idx as usize <= self.cur_chunk + 1 {
706 self.samples_left = *samples as usize;
711 self.last_offset = self.chunk_offsets[self.cur_chunk];
714 let offset = self.last_offset;
715 let size = self.get_size(self.cur_sample);
716 self.last_offset += size as u64;
717 if self.stream_type == StreamType::Video {
718 self.samples_left -= 1;
720 self.samples_left = 0;
722 self.cur_sample += 1;
723 Some((pts, offset, size))
726 fn get_size(&self, sample_no: usize) -> usize {
727 if self.chunk_sizes.len() > 0 {
728 self.chunk_sizes[sample_no] as usize
729 } else if self.sample_map.len() > 0 {
731 for (idx, samples) in self.sample_map.iter() {
732 if *idx as usize <= self.cur_chunk {
738 self.calculate_chunk_size(nsamp as usize)
740 self.sample_size as usize
743 fn seek(&mut self, pts: u64) {
744 self.cur_sample = pts as usize;
745 self.samples_left = 0;
746 if self.stream_type == StreamType::Audio {
747 self.cur_chunk = self.cur_sample;
748 } else if self.chunk_offsets.len() != self.chunk_sizes.len() && self.sample_map.len() > 0{
751 let mut cmap = self.sample_map.iter();
752 let mut cur_samps = 0;
753 let (mut next_idx, mut next_samples) = cmap.next().unwrap();
755 if self.cur_chunk == next_idx as usize {
756 self.samples_left = cur_samps;
757 cur_samps = next_samples as usize;
758 if let Some((new_idx, new_samples)) = cmap.next() {
760 next_samples = *new_samples;
764 if csamp >= self.cur_sample {
765 self.last_offset = self.chunk_offsets[self.cur_chunk];
771 for sample_no in csamp..self.cur_chunk {
772 self.last_offset += self.get_size(sample_no) as u64;
774 self.samples_left = self.cur_sample - csamp - cur_samps;
779 impl<'a> DemuxCore<'a> for MOVDemuxer<'a> {
780 fn open(&mut self, strmgr: &mut StreamManager, seek_index: &mut SeekIndex) -> DemuxerResult<()> {
781 self.read_root(strmgr)?;
782 validate!(self.mdat_pos > 0);
783 validate!(self.tracks.len() > 0);
784 for track in self.tracks.iter() {
785 track.fill_seek_index(seek_index);
787 self.src.seek(SeekFrom::Start(self.mdat_pos))?;
792 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket> {
793 if self.tracks.len() == 0 {
794 return Err(DemuxerError::EOF);
796 for _ in 0..self.tracks.len() {
797 if self.cur_track >= self.tracks.len() {
800 let track = &mut self.tracks[self.cur_track];
802 let first = track.cur_sample == 0;
803 if let Some((pts, offset, size)) = track.get_next_chunk() {
804 let str = strmgr.get_stream(track.track_str_id);
805 if str.is_none() { return Err(DemuxerError::InvalidData); }
806 let stream = str.unwrap();
807 self.src.seek(SeekFrom::Start(offset))?;
808 let mut pkt = self.src.read_packet(stream, pts, false, size)?;
809 if let Some(ref pal) = track.pal {
810 let side_data = NASideData::Palette(first, pal.clone());
811 pkt.add_side_data(side_data);
816 return Err(DemuxerError::EOF);
819 fn seek(&mut self, time: u64, seek_index: &SeekIndex) -> DemuxerResult<()> {
820 let ret = seek_index.find_pos(time);
822 return Err(DemuxerError::SeekError);
824 let seek_info = ret.unwrap();
825 for track in self.tracks.iter_mut() {
826 track.seek(seek_info.pts);
832 impl<'a> MOVDemuxer<'a> {
833 fn new(io: &'a mut ByteReader<'a>) -> Self {
839 tracks: Vec::with_capacity(2),
846 fn read_root(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<()> {
848 while self.src.left() != 0 {
849 let ret = read_chunk_header(&mut self.src);
850 if ret.is_err() { break; }
851 let (ctype, size) = ret.unwrap();
852 if IGNORED_CHUNKS.contains(&ctype) {
853 self.src.skip64(size)?;
856 let handler = ROOT_CHUNK_HANDLERS.iter().find(|x| x.ctype == ctype);
858 if let Some(ref handler) = handler {
859 read_size = (handler.parse)(self, strmgr, size)?;
861 println!("skipping unknown chunk {:08X} size {}", ctype, size);
864 validate!(read_size <= size);
865 self.src.skip64(size - read_size)?;
867 //todo check if all needed chunks are found
870 read_chunk_list!(root; "moov", read_moov, MOOV_CHUNK_HANDLERS);
873 pub struct MOVDemuxerCreator { }
875 impl DemuxerCreator for MOVDemuxerCreator {
876 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a> {
877 Box::new(MOVDemuxer::new(br))
879 fn get_name(&self) -> &'static str { "mov" }
888 fn test_mov_demux() {
889 let mut file = File::open("assets/Indeo/cubes.mov").unwrap();
890 let mut fr = FileReader::new_read(&mut file);
891 let mut br = ByteReader::new(&mut fr);
892 let mut dmx = MOVDemuxer::new(&mut br);
893 let mut sm = StreamManager::new();
894 let mut si = SeekIndex::new();
895 dmx.open(&mut sm, &mut si).unwrap();
898 let pktres = dmx.get_frame(&mut sm);
899 if let Err(e) = pktres {
900 if e == DemuxerError::EOF { break; }
903 let pkt = pktres.unwrap();
904 println!("Got {}", pkt);