2 use nihav_core::demuxers::DemuxerError::*;
8 ($a:expr, $b:expr, $c:expr, $d:expr) => ({
9 (($a as u32) << 24) | (($b as u32) << 16) | (($c as u32) << 8) | ($d as u32)
12 (($arr[0] as u32) << 24) | (($arr[1] as u32) << 16) | (($arr[2] as u32) << 8) | ($arr[3] as u32)
16 const RM_SIPRO_BLOCK_SIZES: [usize; 4] = [ 29, 19, 37, 20 ];
17 const RM_SIPRO_SWAPS: [[u8; 2]; 38] = [
18 [ 0, 63 ], [ 1, 22 ], [ 2, 44 ], [ 3, 90 ],
19 [ 5, 81 ], [ 7, 31 ], [ 8, 86 ], [ 9, 58 ],
20 [ 10, 36 ], [ 12, 68 ], [ 13, 39 ], [ 14, 73 ],
21 [ 15, 53 ], [ 16, 69 ], [ 17, 57 ], [ 19, 88 ],
22 [ 20, 34 ], [ 21, 71 ], [ 24, 46 ], [ 25, 94 ],
23 [ 26, 54 ], [ 28, 75 ], [ 29, 50 ], [ 32, 70 ],
24 [ 33, 92 ], [ 35, 74 ], [ 38, 85 ], [ 40, 56 ],
25 [ 42, 87 ], [ 43, 65 ], [ 45, 59 ], [ 48, 79 ],
26 [ 49, 93 ], [ 51, 89 ], [ 55, 95 ], [ 61, 76 ],
27 [ 67, 83 ], [ 77, 80 ]
30 struct RMVideoStream {
47 self.frame.truncate(0);
51 fn start_slice(&mut self, num_slices: usize, frame_size: usize, data: &[u8]) {
52 self.hdr_size = num_slices * 8 + 1;
53 self.frame.resize(frame_size + self.hdr_size, 0);
54 self.frame[0] = (num_slices - 1) as u8;
56 self.add_slice(1, data).unwrap();
58 fn add_slice(&mut self, slice_no: usize, data: &[u8]) -> DemuxerResult<()> {
59 validate!(self.hdr_size + self.frame_pos + data.len() <= self.frame.len());
60 self.write_slice_info(slice_no);
61 let dslice = &mut self.frame[self.hdr_size + self.frame_pos..][..data.len()];
62 dslice.copy_from_slice(data);
63 self.frame_pos += data.len();
66 fn write_slice_info(&mut self, slice_no: usize) {
67 let off = 1 + (slice_no - 1) * 8;
68 self.frame[off + 0] = 0;
69 self.frame[off + 1] = 0;
70 self.frame[off + 2] = 0;
71 self.frame[off + 3] = 1;
72 self.frame[off + 4] = (self.frame_pos >> 24) as u8;
73 self.frame[off + 5] = (self.frame_pos >> 16) as u8;
74 self.frame[off + 6] = (self.frame_pos >> 8) as u8;
75 self.frame[off + 7] = (self.frame_pos >> 0) as u8;
77 fn get_frame_data(&mut self) -> Vec<u8> {
78 let mut v: Vec<u8> = Vec::new();
79 mem::swap(&mut v, &mut self.frame);
85 #[derive(Clone,Copy,PartialEq)]
94 struct RMAudioStream {
96 iinfo: Option<InterleaveInfo>,
101 const RM_ILEAVE_INT0: u32 = mktag!(b"Int0");
102 const RM_ILEAVE_INT4: u32 = mktag!(b"Int4");
103 const RM_ILEAVE_GENR: u32 = mktag!(b"genr");
104 const RM_ILEAVE_SIPR: u32 = mktag!(b"sipr");
105 const RM_ILEAVE_VBRF: u32 = mktag!(b"vbrf");
106 const RM_ILEAVE_VBRS: u32 = mktag!(b"vbrs");
109 fn new(iinfo: Option<InterleaveInfo>) -> Self {
112 if let Some(info) = iinfo {
113 deint = match info.id {
114 RM_ILEAVE_INT0 => Deinterleaver::None,
115 RM_ILEAVE_INT4 => Deinterleaver::RA28_8,
116 RM_ILEAVE_GENR => Deinterleaver::Generic,
117 RM_ILEAVE_SIPR => Deinterleaver::Sipro,
118 RM_ILEAVE_VBRF => Deinterleaver::VBR,
119 RM_ILEAVE_VBRS => Deinterleaver::VBR,
120 _ => {println!("unknown deint {:X}", info.id); Deinterleaver::None },
123 Deinterleaver::None => { buf = Vec::new(); },
124 Deinterleaver::RA28_8 |
125 Deinterleaver::Generic |
126 Deinterleaver::Sipro => {
127 let bsize = (info.frame_size as usize) * (info.factor as usize);
128 buf = vec![0; bsize];
130 Deinterleaver::VBR => {
135 deint = Deinterleaver::None;
138 RMAudioStream { deint, iinfo, buf, sub_packet: 0 }
140 fn read_apackets(&mut self, queued_packets: &mut Vec<NAPacket>, src: &mut ByteReader, stream: NAStreamRef, ts: u32, keyframe: bool, payload_size: usize) -> DemuxerResult<NAPacket> {
141 let (tb_num, tb_den) = stream.get_timebase();
142 let ts = NATimeInfo::new(Some(ts as u64), None, None, tb_num, tb_den);
148 Deinterleaver::None => { return src.read_packet(stream, ts, keyframe, payload_size); },
149 Deinterleaver::RA28_8 => {
150 let iinfo = self.iinfo.unwrap();
151 let factor = iinfo.factor as usize;
152 let halffact = factor >> 1;
153 let fsize = iinfo.frame_size as usize;
154 let bsize = iinfo.block_size as usize;
155 let ppos = self.sub_packet;
156 for sb in 0..halffact {
157 let mut dst = &mut self.buf[sb * 2 * fsize + ppos * bsize..][..bsize];
158 src.read_buf(&mut dst)?;
160 self.sub_packet += 1;
161 if self.sub_packet == factor {
163 return Ok(NAPacket::new(stream, ts, true, self.buf.clone()));
165 return Err(DemuxerError::TryAgain);
168 Deinterleaver::Generic => {
169 let iinfo = self.iinfo.unwrap();
170 let factor = iinfo.factor as usize;
171 let fsize = iinfo.frame_size as usize;
172 let bsize = iinfo.block_size as usize;
173 let factor2 = fsize / bsize;
174 let ppos = self.sub_packet;
176 for sb in 0..factor2 {
177 let sb_pos = factor * sb + ((factor + 1) >> 1) * (ppos & 1) + (ppos >> 1);
178 let mut dst = &mut self.buf[bsize * sb_pos..][..bsize];
179 src.read_buf(&mut dst)?;
182 Deinterleaver::Sipro => {
183 let iinfo = self.iinfo.unwrap();
184 let fsize = iinfo.frame_size as usize;
185 let ppos = self.sub_packet;
187 let mut dst = &mut self.buf[fsize * ppos..][..fsize];
188 src.read_buf(&mut dst)?;
190 Deinterleaver::VBR => {
191 validate!(payload_size >= 5);
192 let hdrsizesize = src.read_u16be()?;
193 let num_entries = (hdrsizesize / 16) as usize;
194 validate!(payload_size >= num_entries * 3 + 2);
195 let mut sizes: Vec<usize> = Vec::with_capacity(num_entries);
196 let mut tot_size = 0;
197 for _ in 0..num_entries {
198 let sz = src.read_u16be()? as usize;
202 validate!(tot_size + num_entries * 2 + 2 == payload_size);
203 let pkt_ts = NATimeInfo::new(None, None, None, tb_num, tb_den);
204 let mut first = true;
205 for size in sizes.iter() {
206 let cur_ts = if first { ts } else { pkt_ts };
208 let pkt = src.read_packet(stream.clone(), cur_ts, true, *size)?;
209 queued_packets.push(pkt);
211 queued_packets.reverse();
212 let pkt0 = queued_packets.pop().unwrap();
217 let iinfo = self.iinfo.unwrap();
218 let factor = iinfo.factor as usize;
219 let fsize = if iinfo.block_size != 0 { iinfo.block_size } else { iinfo.frame_size } as usize;
221 self.sub_packet += 1;
222 if self.sub_packet < factor {
223 return Err(DemuxerError::TryAgain);
228 if self.deint == Deinterleaver::Sipro {
229 sipro_restore(&mut self.buf, factor, iinfo.frame_size as usize);
232 let mut frames_iter = self.buf.chunks(fsize);
233 let pkt0 = frames_iter.next().unwrap();
235 let pkt_ts = NATimeInfo::new(None, None, None, tb_num, tb_den);
236 for pkts in frames_iter {
237 let pkt = NAPacket::new(stream.clone(), pkt_ts, true, pkts.to_vec());
238 queued_packets.push(pkt);
240 queued_packets.reverse();
241 Ok(NAPacket::new(stream, ts, true, pkt0.to_vec()))
245 fn sipro_restore(buf: &mut [u8], factor: usize, fsize: usize) {
246 let stride = factor * fsize * 2 / 96;
248 let mut sidx = (RM_SIPRO_SWAPS[i][0] as usize) * stride;
249 let mut didx = (RM_SIPRO_SWAPS[i][1] as usize) * stride;
251 let in0 = buf[sidx >> 1];
252 let in1 = buf[didx >> 1];
253 let nib0 = (in0 >> ((sidx & 1) * 4)) & 0xF;
254 let nib1 = (in1 >> ((didx & 1) * 4)) & 0xF;
256 buf[didx >> 1] = (nib0 << (4 * (didx & 1))) | (in1 & (0xF << (4 * (!didx & 1))));
257 buf[sidx >> 1] = (nib1 << (4 * (sidx & 1))) | (in0 & (0xF << (4 * (!sidx & 1))));
265 struct SubstreamInfo {
272 sub_info: Vec<SubstreamInfo>,
279 sub_info: Vec::new(),
283 fn add_stream(&mut self, stream_no: u32) {
284 let ssinfo = SubstreamInfo { id: stream_no, map: Vec::new(), str_ids: Vec::new() };
285 self.sub_info.push(ssinfo);
287 fn get_substream_no(&self) -> u32 {
290 fn find_idx(&self, stream_no: u32) -> Option<usize> {
291 self.sub_info.iter().position(|x| x.id == stream_no)
293 fn add_map_rule(&mut self, map_ss: u16) {
294 let idx = self.sub_info.len() - 1;
295 self.sub_info[idx].map.push(map_ss);
297 fn add_substream(&mut self) {
298 let idx = self.sub_info.len() - 1;
299 self.sub_info[idx].str_ids.push(self.sstr_id);
302 fn is_mlti_stream(&self, stream_no: u32) -> bool {
303 self.find_idx(stream_no).is_some()
305 fn find_substream(&self, stream_no: u32, grp: u16) -> Option<u32> {
306 if let Some(idx) = self.find_idx(stream_no) {
307 if (grp as usize) < self.sub_info[idx].map.len() {
308 let sub_id = self.sub_info[idx].map[grp as usize] as usize;
309 if sub_id < self.sub_info[idx].str_ids.len() {
310 return Some(self.sub_info[idx].str_ids[sub_id]);
319 Audio(RMAudioStream),
320 Video(RMVideoStream),
325 struct CommonStreamData {
326 streams: Vec<RMStreamType>,
328 mlti_mapper: MLTIMapper,
331 impl CommonStreamData {
336 mlti_mapper: MLTIMapper::new(),
339 fn get_stream_id(&self, str_no: u32, pkt_grp: u16) -> u32 {
340 if !self.mlti_mapper.is_mlti_stream(str_no) {
343 self.mlti_mapper.find_substream(str_no, pkt_grp).unwrap()
346 fn find_stream(&self, stream_id: u32) -> Option<usize> {
347 self.str_ids.iter().position(|x| *x == stream_id)
351 struct RealMediaDemuxer<'a> {
352 src: &'a mut ByteReader<'a>,
360 str_data: CommonStreamData,
362 data_chunks: Vec<(u64, u32, u16)>,
363 cur_data_chunk: usize,
365 queued_pkts: Vec<NAPacket>,
369 fn find_codec_name(registry: &[(&[u8;4], &'static str)], fcc: u32) -> &'static str {
370 for &(fourcc, name) in registry {
371 if mktag!(fourcc) == fcc { return name; }
376 fn read_14or30(src: &mut ByteReader) -> DemuxerResult<(bool, u32)> {
377 let tmp = src.read_u16be()?;
378 let flag = (tmp & 0x8000) != 0;
379 if (tmp & 0x4000) == 0x4000 {
380 Ok((flag, ((tmp & 0x3FFF) as u32)))
382 let val = ((tmp as u32) << 16) | (src.read_u16be()? as u32);
383 Ok((flag, val & 0x3FFFFFFF))
387 fn read_video_buf(src: &mut ByteReader, stream: NAStreamRef, ts: u32, keyframe: bool, frame_size: usize) -> DemuxerResult<NAPacket> {
388 let size = (frame_size as usize) + 9;
389 let mut vec: Vec<u8> = vec![0; size];
390 //v[0] = 0; // 1 slice
392 src.read_buf(&mut vec[9..])?;
394 let (tb_num, tb_den) = stream.get_timebase();
395 let ts = NATimeInfo::new(Some(ts as u64), None, None, tb_num, tb_den);
396 Ok(NAPacket::new(stream, ts, keyframe, vec))
399 fn read_multiple_frame(src: &mut ByteReader, stream: NAStreamRef, keyframe: bool, skip_mtype: bool) -> DemuxerResult<NAPacket> {
401 let mtype = src.read_byte()?;
402 validate!(mtype == 0xC0);
404 let (_, frame_size) = read_14or30(src)?;
405 let (_, timestamp) = read_14or30(src)?;
406 let _seq_no = src.read_byte()?;
407 //println!(" multiple frame size {} ts {} seq {}", frame_size, timestamp, seq_no);
409 read_video_buf(src, stream, timestamp, keyframe, frame_size as usize)
412 struct RMDemuxCommon {}
415 fn parse_stream_info(str_data: &mut CommonStreamData, strmgr: &mut StreamManager, stream_no: u32, edata: &[u8], duration: u32) -> DemuxerResult<bool> {
416 let mut is_mlti = false;
417 let mut mr = MemoryReader::new_read(edata);
418 let mut src = ByteReader::new(&mut mr);
419 let tag = src.read_u32be()?;
420 let tag2 = src.peek_u32be()?;
421 //println!("tag1 {:X} tag2 {:X}", tag, tag2);
422 if tag == mktag!('.', 'r', 'a', 0xFD) {
423 Self::parse_audio_stream(strmgr, &mut str_data.streams, stream_no, &mut src, edata, duration)?;
424 } else if ((tag2 == mktag!('V', 'I', 'D', 'O')) || (tag2 == mktag!('I', 'M', 'A', 'G'))) && ((tag as usize) <= edata.len()) {
425 Self::parse_video_stream(strmgr, &mut str_data.streams, stream_no, &mut src, edata, tag2, duration)?;
426 } else if tag == mktag!(b"LSD:") {
427 let extradata = Some(edata.to_owned());
429 src.read_skip(4)?; //version
430 let channels = src.read_u16be()?;
431 let samp_size = src.read_u16be()?;
432 let sample_rate = src.read_u32be()?;
434 println!("LSD sr {}, {} ch", sample_rate, channels);
435 let soniton = NASoniton::new(samp_size as u8, SONITON_FLAG_SIGNED);
436 let ahdr = NAAudioInfo::new(sample_rate, channels as u8, soniton, 1);
437 let nainfo = NACodecInfo::new("ralf", NACodecTypeInfo::Audio(ahdr), extradata);
438 let res = strmgr.add_stream(NAStream::new(StreamType::Audio, stream_no as u32, nainfo, 1, 1000, u64::from(duration)));
439 if res.is_none() { return Err(MemoryError); }
440 let astr = RMAudioStream::new(None);
441 str_data.streams.push(RMStreamType::Audio(astr));
442 } else if tag == mktag!(b"MLTI") {
444 let num_rules = src.read_u16be()? as usize;
446 str_data.mlti_mapper.add_stream(stream_no);
447 for _ in 0..num_rules {
448 let substr = src.read_u16be()?;
449 max_sub = max_sub.max(substr);
450 str_data.mlti_mapper.add_map_rule(substr);
452 let num_substreams = src.read_u16be()? as usize;
453 validate!(num_substreams > (max_sub as usize));
454 for _ in 0..num_substreams {
455 let hdr_size = src.read_u32be()? as usize;
456 validate!(hdr_size > 8);
457 let pos = src.tell() as usize;
458 src.read_skip(hdr_size)?;
459 str_data.mlti_mapper.add_substream();
461 let hdrsrc = &edata[pos..][..hdr_size];
462 let mut mr = MemoryReader::new_read(hdrsrc);
463 let mut hsrc = ByteReader::new(&mut mr);
465 let tag = hsrc.read_u32be()?;
466 let tag2 = hsrc.peek_u32be()?;
467 let stream_no = str_data.mlti_mapper.get_substream_no();
468 //todo check that all substreams are of the same type");
469 if tag == mktag!('.', 'r', 'a', 0xFD) {
470 Self::parse_audio_stream(strmgr, &mut str_data.streams, stream_no, &mut hsrc, hdrsrc, duration)?;
471 } else if (tag2 == mktag!('V', 'I', 'D', 'O')) && ((tag as usize) <= hdr_size) {
472 Self::parse_video_stream(strmgr, &mut str_data.streams, stream_no, &mut hsrc, hdrsrc, tag2, duration)?;
474 println!("unknown MLTI substream {:08X} / {:08X}", tag, tag2);
475 return Err(DemuxerError::InvalidData);
477 str_data.str_ids.push(stream_no);
481 str_data.streams.push(RMStreamType::Logical);
485 fn parse_audio_stream(strmgr: &mut StreamManager, streams: &mut Vec<RMStreamType>, stream_no: u32, src: &mut ByteReader, edata_: &[u8], duration: u32) -> DemuxerResult<()> {
486 let ver = src.read_u16be()?;
487 let ainfo = match ver {
498 println!("unknown version {}", ver);
499 return Err(DemuxerError::InvalidData);
502 println!(" got ainfo {:?}", ainfo);
503 let cname = find_codec_name(RM_AUDIO_CODEC_REGISTER, ainfo.fcc);
504 let blk_size = if ainfo.fcc != mktag!(b"sipr") {
505 ainfo.granularity as usize
507 validate!(ainfo.flavor <= 3);
508 RM_SIPRO_BLOCK_SIZES[ainfo.flavor as usize]
510 let srate = ainfo.sample_rate;
511 let soniton = NASoniton::new(ainfo.sample_size as u8, SONITON_FLAG_SIGNED);
512 let ahdr = NAAudioInfo::new(srate, ainfo.channels as u8, soniton, blk_size);
513 let extradata = if ainfo.edata_size == 0 {
516 let eslice = &edata_[(src.tell() as usize)..];
517 Some(eslice.to_vec())
519 let duration = if duration == 0 { ainfo.get_duration(1000) } else { u64::from(duration) };
520 let nainfo = NACodecInfo::new(cname, NACodecTypeInfo::Audio(ahdr), extradata);
521 let res = strmgr.add_stream(NAStream::new(StreamType::Audio, stream_no as u32, nainfo, 1, 1000, duration));
522 if res.is_none() { return Err(MemoryError); }
524 let astr = RMAudioStream::new(ainfo.ileave_info);
525 streams.push(RMStreamType::Audio(astr));
528 #[allow(unused_variables)]
529 fn parse_video_stream(strmgr: &mut StreamManager, streams: &mut Vec<RMStreamType>, stream_no: u32, src: &mut ByteReader, edata_: &[u8], tag2: u32, duration: u32) -> DemuxerResult<()> {
531 let fcc = src.read_u32be()?;
532 let width = src.read_u16be()? as usize;
533 let height = src.read_u16be()? as usize;
534 let bpp = src.read_u16be()?;
535 let pad_w = src.read_u16be()?;
536 let pad_h = src.read_u16be()?;
538 if tag2 == mktag!('V', 'I', 'D', 'O') {
539 _fps = src.read_u32be()?;
543 let extradata: Option<Vec<u8>>;
545 let eslice = &edata_[(src.tell() as usize)..];
546 extradata = Some(eslice.to_vec());
550 let cname = find_codec_name(RM_VIDEO_CODEC_REGISTER, fcc);
552 let vhdr = NAVideoInfo::new(width, height, false, RGB24_FORMAT);
553 let vinfo = NACodecInfo::new(cname, NACodecTypeInfo::Video(vhdr), extradata);
554 let res = strmgr.add_stream(NAStream::new(StreamType::Video, stream_no as u32, vinfo, 1, 1000, u64::from(duration)));
555 if res.is_none() { return Err(DemuxerError::MemoryError); }
557 let vstr = RMVideoStream::new();
558 streams.push(RMStreamType::Video(vstr));
561 #[allow(unused_variables)]
562 fn parse_packet_payload(src: &mut ByteReader, rmstream: &mut RMStreamType, stream: NAStreamRef, slice_buf: &mut Vec<u8>, queued_pkts: &mut Vec<NAPacket>, keyframe: bool, ts: u32, payload_size: usize) -> DemuxerResult<NAPacket> {
564 RMStreamType::Video(ref mut vstr) => {
566 let pos = src.tell();
567 let b0 = src.read_byte()?;
569 0 => { // partial frame
570 let b1 = src.read_byte()?;
571 let hdr1 = ((b0 as u16) << 8) | (b1 as u16);
572 let num_pkts = ((hdr1 >> 7) & 0x7F) as usize;
573 let packet_num = hdr1 & 0x7F;
574 let (_, frame_size) = read_14or30(src)?;
575 let (_, off) = read_14or30(src)?;
576 let seq_no = src.read_byte()?;
577 //println!(" mode 0 pkt {}/{} off {}/{} seq {}", packet_num, num_pkts, off, frame_size, seq_no);
578 let hdr_skip = (src.tell() - pos) as usize;
580 let slice_size = (payload_size - hdr_skip) as usize;
581 slice_buf.resize(slice_size, 0);
582 src.read_buf(slice_buf.as_mut_slice())?;
584 vstr.start_slice(num_pkts, frame_size as usize, slice_buf.as_slice());
586 vstr.add_slice(packet_num as usize, slice_buf.as_slice())?;
588 if (packet_num as usize) < num_pkts {
589 return Err(DemuxerError::TryAgain);
591 //todo: check if full frame is received
592 let (tb_num, tb_den) = stream.get_timebase();
593 let ts = NATimeInfo::new(Some(ts as u64), None, None, tb_num, tb_den);
594 let pkt = NAPacket::new(stream, ts, keyframe, vstr.get_frame_data());
597 1 => { // whole frame
598 let seq_no = src.read_byte()?;
599 //println!(" mode 1 seq {}", seq_no);
600 read_video_buf(src, stream, ts, keyframe, payload_size - 2)
602 2 => { // last partial frame
603 let b1 = src.read_byte()?;
604 let hdr1 = ((b0 as u16) << 8) | (b1 as u16);
605 let num_pkts = ((hdr1 >> 7) & 0x7F) as usize;
606 let packet_num = hdr1 & 0x7F;
607 let (_, frame_size) = read_14or30(src)?;
608 let (_, tail_size) = read_14or30(src)?;
609 let seq_no = src.read_byte()?;
610 //println!(" mode 2 pkt {}/{} tail {}/{} seq {}", packet_num, num_pkts, tail_size, frame_size, seq_no);
611 slice_buf.resize(tail_size as usize, 0);
612 src.read_buf(slice_buf.as_mut_slice())?;
613 if packet_num == 1 && frame_size == tail_size {
614 vstr.start_slice(num_pkts, frame_size as usize, slice_buf.as_slice());
616 vstr.add_slice(packet_num as usize, slice_buf.as_slice())?;
619 while src.tell() < pos + (payload_size as u64) {
620 let res = read_multiple_frame(src, stream.clone(), false, false);
621 if res.is_err() { break; }
622 queued_pkts.push(res.unwrap());
624 queued_pkts.reverse();
625 let (tb_num, tb_den) = stream.get_timebase();
626 let ts = NATimeInfo::new(Some(ts as u64), None, None, tb_num, tb_den);
627 let pkt = NAPacket::new(stream, ts, keyframe, vstr.get_frame_data());
630 _ => { // multiple frames
631 //println!(" mode 3");
632 let res = read_multiple_frame(src, stream.clone(), keyframe, true);
633 if res.is_err() { return res; }
634 while src.tell() < pos + (payload_size as u64) {
635 let res = read_multiple_frame(src, stream.clone(), false, false);
636 if res.is_err() { break; }
637 queued_pkts.push(res.unwrap());
639 queued_pkts.reverse();
644 RMStreamType::Audio(ref mut astr) => {
645 astr.read_apackets(queued_pkts, src, stream, ts, keyframe, payload_size)
648 src.read_skip(payload_size)?;
649 Err(DemuxerError::InvalidData)
655 impl<'a> DemuxCore<'a> for RealMediaDemuxer<'a> {
656 fn open(&mut self, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex) -> DemuxerResult<()> {
657 self.read_header(strmgr, seek_idx)?;
661 #[allow(unused_variables)]
662 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket> {
663 if !self.queued_pkts.is_empty() {
664 let pkt = self.queued_pkts.pop().unwrap();
668 if (self.cur_packet >= self.num_packets) || (self.src.tell() >= self.data_end) {
669 self.cur_data_chunk += 1;
670 if self.cur_data_chunk < self.data_chunks.len() {
671 let (pos, _, _) = self.data_chunks[self.cur_data_chunk];
672 self.src.seek(SeekFrom::Start(pos))?;
673 let res = read_chunk(self.src);
674 if let Ok((id, size, ver)) = res {
675 self.data_pos = self.src.tell();
677 self.data_end = self.data_pos + (size as u64);
678 if self.parse_data_start().is_ok() {
683 return Err(DemuxerError::EOF);
686 let pkt_start = self.src.tell();
687 let ver = self.src.read_u16be()?;
689 let len = self.src.read_u16be()? as usize;
690 let str_no = self.src.read_u16be()? as u32;
691 let ts = self.src.read_u32be()?;
695 pkt_grp = self.src.read_byte()? as u16;
696 flags = self.src.read_byte()?;
698 //asm_rule = self.src.read_u16be()?;
699 //asm_flags = self.src.read_byte()?;
700 self.src.read_skip(2)?;
702 self.src.read_skip(1)?;
705 let hdr_size = self.src.tell() - pkt_start;
706 //println!("packet @{:X} size {} for {} ts {} grp {} flags {:X}", pkt_start, len, str_no, ts, pkt_grp, flags);
707 self.cur_packet += 1;
709 let payload_size = len - (hdr_size as usize);
711 let stream_id = self.str_data.get_stream_id(str_no as u32, pkt_grp);
712 let sr = self.str_data.find_stream(stream_id);
714 //println!("stream {} not found", str_no);
715 self.src.read_skip(payload_size)?;
716 return Err(DemuxerError::InvalidData);
718 let str_id = sr.unwrap();
720 let streamres = strmgr.get_stream_by_id(stream_id);
721 if streamres.is_none() {
722 self.src.read_skip(payload_size)?;
725 let stream = streamres.unwrap();
726 //println!(" stream {}", str_id);
727 if strmgr.is_ignored_id(stream_id) {
728 self.src.read_skip(payload_size)?;
731 //todo skip unwanted packet
732 let keyframe = (flags & KEYFRAME_FLAG) != 0;
734 let ret = RMDemuxCommon::parse_packet_payload(&mut self.src, &mut self.str_data.streams[str_id], stream, &mut self.slice_buf, &mut self.queued_pkts, keyframe, ts, payload_size);
735 if let Err(DemuxerError::TryAgain) = ret {
743 #[allow(unused_variables)]
744 fn seek(&mut self, time: NATimePoint, seek_idx: &SeekIndex) -> DemuxerResult<()> {
745 self.queued_pkts.clear();
746 let ret = seek_idx.find_pos(time);
748 return Err(DemuxerError::SeekError);
750 let ret = ret.unwrap();
751 let seek_pos = ret.pos;
752 for (pos, size, ver) in self.data_chunks.iter() {
753 if seek_pos < *pos { continue; }
754 let end = *pos + (*size as u64);
757 self.data_pos = seek_pos;
758 self.data_ver = *ver;
760 self.src.seek(SeekFrom::Start(seek_pos))?;
764 Err(DemuxerError::SeekError)
767 fn get_duration(&self) -> u64 { 0 }
770 impl<'a> NAOptionHandler for RealMediaDemuxer<'a> {
771 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
772 fn set_options(&mut self, _options: &[NAOption]) { }
773 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
776 fn read_chunk(src: &mut ByteReader) -> DemuxerResult<(u32, u32, u16)> {
777 let id = src.read_u32be()?;
778 if id == 0 { return Ok((0, 0, 0)); }
779 let size = src.read_u32be()?;
781 let ver = src.read_u16be()?;
783 return Ok((id, 0x0FFFFFFF, ver));
785 validate!(size >= 10);
786 let ver = src.read_u16be()?;
791 #[derive(Clone,Copy,Debug)]
792 struct InterleaveInfo {
799 #[derive(Clone,Copy,Debug)]
800 struct RealAudioInfo {
808 bytes_per_minute: u32,
811 ileave_info: Option<InterleaveInfo>
815 fn get_duration(&self, base: u32) -> u64 {
816 if self.bytes_per_minute != 0 {
817 u64::from(self.total_bytes) * 60 * u64::from(base) / u64::from(self.bytes_per_minute)
824 fn skip_ra_metadata(src: &mut ByteReader) -> DemuxerResult<()> {
825 let title_len = src.read_byte()? as usize;
826 src.read_skip(title_len)?;
827 let author_len = src.read_byte()? as usize;
828 src.read_skip(author_len)?;
829 let copywrong_len = src.read_byte()? as usize;
830 src.read_skip(copywrong_len)?;
831 let comment_len = src.read_byte()? as usize;
832 src.read_skip(comment_len)?;
836 #[allow(unused_variables)]
837 fn parse_aformat3(src: &mut ByteReader) -> DemuxerResult<RealAudioInfo> {
838 let start = src.tell();
839 let header_len = src.read_u16be()?;
840 validate!(header_len >= 24);
841 let flavor = src.read_u16be()?;
842 let granularity = src.read_u32be()?;
843 let bytes_per_minute = src.read_u32be()?;
844 let total_bytes = src.read_u32be()?;
846 skip_ra_metadata(src)?;
848 let _can_copy = src.read_byte()?;
849 let fcc_len = src.read_byte()?;
850 validate!(fcc_len == 4);
851 let fcc = src.read_u32be()?;
853 let end = src.tell();
854 validate!(end - start <= (header_len as u64) + 2);
858 sample_rate: 8000, sample_size: 16, channels: 1, channel_mask: 0,
859 granularity, bytes_per_minute,
860 total_bytes, edata_size: 0,
865 #[allow(unused_variables)]
866 fn parse_aformat4(src: &mut ByteReader) -> DemuxerResult<RealAudioInfo> {
867 let start = src.tell();
868 src.read_skip(2)?; // zeroes
869 let id = src.read_u32be()?;
870 validate!(id == mktag!(b".ra4"));
871 let data_size = src.read_u32be()?;
872 let _ver4 = src.read_u16be()?; // should be 4
873 let header_size = src.read_u32be()?;
874 let flavor = src.read_u16be()?;
875 let granularity = src.read_u32be()?;
876 let total_bytes = src.read_u32be()?;
877 let bytes_per_minute = src.read_u32be()?;
878 let _bytes_per_minute2 = src.read_u32be()?;
879 let ileave_factor = src.read_u16be()?;
880 let ileave_block_size = src.read_u16be()?;
881 let _user_data = src.read_u16be()?;
882 let sample_rate = src.read_u32be()?;
883 let sample_size = src.read_u32be()?;
884 let channels = src.read_u16be()?;
885 let interleaver_id_len = src.read_byte()?;
886 validate!(interleaver_id_len == 4);
887 let interleaver_id = src.read_u32be()?;
888 let fcc_len = src.read_byte()?;
889 validate!(fcc_len == 4);
890 let fcc = src.read_u32be()?;
891 let is_interleaved = src.read_byte()?;
892 let _can_copy = src.read_byte()?;
893 let _stream_type = src.read_byte()?;
895 skip_ra_metadata(src)?;
897 let end = src.tell();
898 validate!(end - start <= (header_size as u64) + 10);
900 let ileave_info = if is_interleaved != 0 {
901 Some(InterleaveInfo {
902 id: interleaver_id, factor: ileave_factor, block_size: granularity as u16,
903 frame_size: ileave_block_size,
911 sample_rate, sample_size: sample_size as u16, channels, channel_mask: 0,
912 granularity, bytes_per_minute,
913 total_bytes: total_bytes & 0xFFFFFF, edata_size: 0,
918 #[allow(unused_variables)]
919 fn parse_aformat5(src: &mut ByteReader) -> DemuxerResult<RealAudioInfo> {
920 let start = src.tell();
921 src.read_skip(2)?; // zeroes
922 let id = src.read_u32be()?;
923 validate!((id == mktag!(b".ra5")) || (id == mktag!(b".ra4")));
924 let data_size = src.read_u32be()?;
925 let _ver5 = src.read_u16be()?; // should be 5
926 let header_size = src.read_u32be()?;
927 let flavor = src.read_u16be()?;
928 let granularity = src.read_u32be()?;
929 let total_bytes = src.read_u32be()?;
930 let bytes_per_minute = src.read_u32be()?;
931 let _bytes_per_minute2 = src.read_u32be()?;
932 let ileave_factor = src.read_u16be()?;
933 let frame_size = src.read_u16be()?;
934 let ileave_block_size = src.read_u16be()?;
935 let user_data = src.read_u32be()?;
936 let _sample_rate1 = src.read_u16be()?;
937 let sample_rate = src.read_u32be()?;
938 let sample_size = src.read_u32be()?;
939 let channels = src.read_u16be()?;
940 let interleaver_id = src.read_u32be()?;
941 let fcc = src.read_u32be()?;
942 let is_interleaved = src.read_byte()?;
943 let _can_copy = src.read_byte()?;
944 let _stream_type = src.read_byte()?;
945 let has_ileave_pattern = src.read_byte()?;
946 if has_ileave_pattern != 0 {
947 unimplemented!("ra5 interleave pattern");
949 let mut edata_size = src.read_u32be()?;
950 let end = src.tell();
951 if id == mktag!(b".ra5") {
952 validate!(end - start <= (header_size as u64) + 10);
953 // src.read_skip(((end - start) as usize) - (header_size as usize) - 10)?;
955 validate!(end - start <= (header_size as u64) + 15);
958 let ileave_info = if is_interleaved != 0 {
959 Some(InterleaveInfo {
960 id: interleaver_id, factor: ileave_factor, block_size: ileave_block_size, frame_size,
965 if (fcc == mktag!(b"raac")) || (fcc == mktag!(b"racp")) {
966 validate!(edata_size > 1);
973 sample_rate, sample_size: sample_size as u16, channels, channel_mask: 0,
974 granularity, bytes_per_minute,
975 total_bytes: total_bytes & 0xFFFFFF, edata_size,
980 const RMVB_HDR_SIZE: u32 = 18;
981 const RMVB_PROP_SIZE: u32 = 50;
982 const KEYFRAME_FLAG: u8 = 0x02;
984 impl<'a> RealMediaDemuxer<'a> {
985 fn new(io: &'a mut ByteReader<'a>) -> Self {
994 str_data: CommonStreamData::new(),
995 data_chunks: Vec::new(),
997 queued_pkts: Vec::new(),
998 slice_buf: Vec::new(),
1001 #[allow(unused_variables)]
1002 fn read_header(&mut self, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex) -> DemuxerResult<()> {
1003 let (id, size, ver) = read_chunk(self.src)?;
1004 validate!((id == mktag!(b".RMF")) || (id == mktag!(b".RMP")));
1005 validate!(size >= RMVB_HDR_SIZE);
1006 let fver = self.src.read_u32be()?;
1007 validate!(fver <= 1);
1008 let num_hdr = self.src.read_u32be()? as usize;
1009 validate!(num_hdr >= 1);
1010 if size > RMVB_HDR_SIZE {
1011 self.src.read_skip((size - RMVB_HDR_SIZE) as usize)?;
1014 let (id, size, ver) = read_chunk(self.src)?;
1015 let prop_size = if ver == 0 { RMVB_PROP_SIZE } else { RMVB_PROP_SIZE + 4 };
1016 validate!(size >= prop_size);
1017 validate!((ver == 0) || (ver == 2));
1018 let maxbr = self.src.read_u32be()?;
1019 let avgbr = self.src.read_u32be()?;
1020 let maxps = self.src.read_u32be()?;
1021 let avgps = self.src.read_u32be()?;
1022 let num_pkt = self.src.read_u32be()? as usize;
1023 let duration = self.src.read_u32be()?;
1024 let preroll = self.src.read_u32be()?;
1026 self.src.read_skip(4)?;
1028 let idx_off = self.src.read_u32be()?;
1029 let data_off = self.src.read_u32be()?;
1030 let num_streams = self.src.read_u16be()? as usize;
1031 let flags = self.src.read_u16be()?;
1032 if size > prop_size {
1033 self.src.read_skip((size - prop_size) as usize)?;
1036 for _ in 0..num_hdr {
1037 if self.src.is_eof() {
1041 let res = self.parse_chunk(strmgr, seek_idx);
1043 Ok(last) => { if last { break; } },
1044 Err(DemuxerError::IOError) => { break; },
1046 if self.data_chunks.is_empty() { // data is not found, report error
1052 //println!("now @ {:X} / {}", self.src.tell(), self.data_pos);
1053 validate!(!self.data_chunks.is_empty());
1054 self.cur_data_chunk = 0;
1055 let (pos, size, ver) = self.data_chunks[self.cur_data_chunk];
1056 self.data_pos = pos;
1057 self.data_ver = ver;
1058 self.data_end = pos + (size as u64);
1059 self.src.seek(SeekFrom::Start(self.data_pos + 10))?;
1060 self.parse_data_start()?;
1063 fn parse_data_start(&mut self) -> DemuxerResult<()> {
1064 let num_packets = self.src.read_u32be()?;
1065 if self.data_ver == 2 {
1066 self.src.read_skip(12)?; // zeroes?
1068 let next_data_hdr = self.src.read_u32be()?;
1069 self.num_packets = if num_packets > 0 { num_packets } else { 0xFFFFFF };
1070 self.cur_packet = 0;
1071 self.next_data = next_data_hdr as u64;
1074 fn parse_chunk(&mut self, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex) -> DemuxerResult<bool> {
1075 let (id, size, ver) = read_chunk(self.src)?;
1076 let end_pos = self.src.tell() - 10 + (size as u64);
1078 validate!((ver == 0) || (ver == 2));
1079 if id == mktag!(b"CONT") { self.parse_content_desc()?; }
1080 else if id == mktag!(b"MDPR") { self.parse_mdpr(strmgr)?; }
1081 else if id == mktag!(b"DATA") {
1082 self.data_chunks.push((self.src.tell() - 10, size, ver));
1084 else if id == mktag!(b"INDX") {
1085 if !seek_idx.skip_index {
1086 self.parse_index(seek_idx, (size as usize) - 10, ver)?;
1089 else if id == 0 { return Ok(true); }
1090 else { println!("unknown chunk type {:08X}", id); }
1092 let cpos = self.src.tell();
1094 self.src.read_skip((end_pos - cpos) as usize)?;
1098 #[allow(unused_variables)]
1099 fn parse_content_desc(&mut self) -> DemuxerResult<()> {
1100 let title_len = self.src.read_u16be()? as usize;
1101 self.src.read_skip(title_len)?;
1102 let author_len = self.src.read_u16be()? as usize;
1103 self.src.read_skip(author_len)?;
1104 let copywrong_len = self.src.read_u16be()? as usize;
1105 self.src.read_skip(copywrong_len)?;
1106 let comment_len = self.src.read_u16be()? as usize;
1107 self.src.read_skip(comment_len)?;
1110 #[allow(unused_variables)]
1111 fn parse_mdpr(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<()> {
1112 let stream_no = self.src.read_u16be()? as u32;
1113 //todo check stream_no for duplicates
1114 let maxbr = self.src.read_u32be()?;
1115 let avgbr = self.src.read_u32be()?;
1116 let maxps = self.src.read_u32be()?;
1117 let avgps = self.src.read_u32be()?;
1118 let start = self.src.read_u32be()?;
1119 let preroll = self.src.read_u32be()?;
1120 let duration = self.src.read_u32be()?;
1121 let sname_size = self.src.read_byte()? as usize;
1122 let sname = read_string_size(self.src, sname_size)?;
1123 //println!("str #{} sname = {} pkts {}/{} start {} preroll {}", stream_no, sname, maxps, avgps, start, preroll);
1124 let mime_size = self.src.read_byte()? as usize;
1125 let mime = read_string_size(self.src, mime_size)?;
1126 //println!("mime = {}", mime);
1127 let edata_size = self.src.read_u32be()? as usize;
1128 let edata: Option<Vec<u8>> = if edata_size == 0 { None } else {
1129 let mut edvec: Vec<u8> = vec![0; edata_size];
1130 self.src.read_buf(&mut edvec)?;
1133 let mut is_mlti = false;
1135 if let Some(edata_) = edata {
1136 is_mlti = RMDemuxCommon::parse_stream_info(&mut self.str_data, strmgr, stream_no, &edata_, duration)?;
1139 self.str_data.streams.push(RMStreamType::Unknown);
1142 self.str_data.str_ids.push(stream_no);
1147 fn parse_index(&mut self, seek_idx: &mut SeekIndex, chunk_size: usize, ver: u16) -> DemuxerResult<()> {
1148 if ver != 0 && ver != 2 { return Ok(()); }
1149 let num_entries = self.src.read_u32be()? as usize;
1150 let str_id = self.src.read_u16be()? as u32;
1151 let _next_idx = self.src.read_u32be()?;
1153 self.src.read_u32be()?;
1156 validate!(chunk_size == num_entries * 14 + 10);
1158 validate!(chunk_size == num_entries * 18 + 14);
1160 if num_entries == 0 { return Ok(()); }
1162 seek_idx.add_stream(str_id);
1163 let idx = seek_idx.get_stream_index(str_id).unwrap();
1164 for _ in 0..num_entries {
1165 let iver = self.src.read_u16be()?;
1166 validate!(iver == ver);
1167 let ts = self.src.read_u32be()? as u64;
1169 self.src.read_u32be()?;
1171 let pos = self.src.read_u32be()? as u64;
1172 let _pkt_no = self.src.read_u32be()?;
1173 idx.add_entry(SeekEntry { time: ts, pts: 0, pos });
1176 seek_idx.mode = SeekIndexMode::Present;
1181 fn read_string_size(src: &mut ByteReader, size: usize) -> DemuxerResult<String> {
1182 let mut vec: Vec<u8> = Vec::new();
1184 let c = src.read_byte()?;
1187 let str = String::from_utf8(vec);
1188 if let Ok(res) = str {
1195 struct RealAudioDemuxer<'a> {
1196 src: &'a mut ByteReader<'a>,
1197 stream: Option<RMAudioStream>,
1201 queued_pkts: Vec<NAPacket>,
1204 impl<'a> DemuxCore<'a> for RealAudioDemuxer<'a> {
1205 #[allow(unused_variables)]
1206 fn open(&mut self, strmgr: &mut StreamManager, _seek_idx: &mut SeekIndex) -> DemuxerResult<()> {
1207 let magic = self.src.read_u32be()?;
1208 validate!(magic == mktag!(b".ra\xFD"));
1209 let ver = self.src.read_u16be()?;
1210 let ainfo = match ver {
1212 parse_aformat3(&mut self.src)?
1215 parse_aformat4(&mut self.src)?
1218 parse_aformat5(&mut self.src)?
1221 println!("unknown version {}", ver);
1222 return Err(DemuxerError::InvalidData);
1225 println!(" got ainfo {:?}", ainfo);
1226 let cname = find_codec_name(RM_AUDIO_CODEC_REGISTER, ainfo.fcc);
1227 let blk_size = if ainfo.fcc != mktag!(b"sipr") {
1228 ainfo.granularity as usize
1230 validate!(ainfo.flavor <= 3);
1231 RM_SIPRO_BLOCK_SIZES[ainfo.flavor as usize]
1233 let srate = ainfo.sample_rate;
1234 let soniton = NASoniton::new(ainfo.sample_size as u8, SONITON_FLAG_SIGNED);
1235 let ahdr = NAAudioInfo::new(srate, ainfo.channels as u8, soniton, blk_size);
1236 let extradata = if ainfo.edata_size == 0 {
1239 let mut dta: Vec<u8> = vec![0; ainfo.edata_size as usize];
1240 self.src.read_buf(dta.as_mut_slice())?;
1243 let nainfo = NACodecInfo::new(cname, NACodecTypeInfo::Audio(ahdr), extradata);
1244 let res = strmgr.add_stream(NAStream::new(StreamType::Audio, 0, nainfo, 1, srate, ainfo.get_duration(ainfo.sample_rate)));
1245 if res.is_none() { return Err(MemoryError); }
1247 let astr = RMAudioStream::new(ainfo.ileave_info);
1248 self.data_start = self.src.tell();
1249 self.data_end = if ainfo.total_bytes > 0 { self.src.tell() + (ainfo.total_bytes as u64) } else { 0 };
1250 self.blk_size = blk_size;
1251 self.stream = Some(astr);
1256 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket> {
1257 if !self.queued_pkts.is_empty() {
1258 let pkt = self.queued_pkts.pop().unwrap();
1261 if (self.data_end != 0) && (self.src.tell() >= self.data_end) {
1262 return Err(DemuxerError::EOF);
1264 let streamres = strmgr.get_stream_by_id(0);
1265 let stream = streamres.unwrap();
1266 if let Some(ref mut astr) = self.stream {
1268 let ret = astr.read_apackets(&mut self.queued_pkts, &mut self.src, stream.clone(), 0, false, self.blk_size);
1269 if let Err(DemuxerError::TryAgain) = ret {
1275 Err(DemuxerError::NoSuchInput)
1278 #[allow(unused_variables)]
1279 fn seek(&mut self, time: NATimePoint, seek_idx: &SeekIndex) -> DemuxerResult<()> {
1283 fn get_duration(&self) -> u64 { 0 }
1286 impl<'a> NAOptionHandler for RealAudioDemuxer<'a> {
1287 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
1288 fn set_options(&mut self, _options: &[NAOption]) { }
1289 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
1292 impl<'a> RealAudioDemuxer<'a> {
1293 fn new(io: &'a mut ByteReader<'a>) -> Self {
1300 queued_pkts: Vec::new(),
1307 StreamProperties(usize),
1308 Packet { ts: u32, str: u32, flags: u32, len: usize, checksum: u32 },
1309 IntValue(Vec<u8>, u32),
1310 BinaryData(Vec<u8>, Vec<u8>),
1311 StringData(Vec<u8>, Vec<u8>),
1318 fn read_string(src: &mut ByteReader) -> DemuxerResult<Vec<u8>> {
1319 let len = src.read_u32be()? as usize;
1320 let mut val = vec![0; len];
1321 src.read_buf(val.as_mut_slice())?;
1325 fn read(src: &mut ByteReader) -> DemuxerResult<Self> {
1326 let code = src.read_byte()?;
1329 let val = src.read_u32be()? as usize;
1330 Ok(IVRRecord::StreamProperties(val))
1333 let ts = src.read_u32be()?;
1334 let str = src.read_u16be()? as u32;
1335 let flags = src.read_u32be()?;
1336 let len = src.read_u32be()? as usize;
1337 let chk = src.read_u32be()?;
1338 validate!((len > 0) && (len < (1 << 24)));
1339 Ok(IVRRecord::Packet { ts, str, flags, len, checksum: chk })
1342 let name = Self::read_string(src)?;
1343 let len = src.read_u32be()?;
1344 validate!(len == 4);
1345 let val = src.read_u32be()?;
1346 Ok(IVRRecord::IntValue(name, val))
1349 let name = Self::read_string(src)?;
1350 let len = src.read_u32be()? as usize;
1351 let mut val = vec![0; len];
1352 src.read_buf(val.as_mut_slice())?;
1353 Ok(IVRRecord::BinaryData(name, val))
1356 let name = Self::read_string(src)?;
1357 let val = Self::read_string(src)?;
1358 Ok(IVRRecord::StringData(name, val))
1360 6 => Ok(IVRRecord::HeaderEnd),
1362 src.read_skip(8)?; // always zero?
1363 Ok(IVRRecord::DataEnd)
1366 src.read_skip(8)?; // always zero?
1367 Ok(IVRRecord::DataStart)
1369 _ => Ok(IVRRecord::Invalid(code)),
1372 fn is_data_start(&self) -> bool {
1374 IVRRecord::DataStart => true,
1380 impl fmt::Display for IVRRecord {
1381 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1383 IVRRecord::Invalid(typ) => write!(f, "Invalid({:02X})", typ),
1384 IVRRecord::StreamProperties(num) =>
1385 write!(f, "({} stream properties)", num),
1386 IVRRecord::Packet { ts, str, flags, len, checksum } =>
1387 write!(f, "paket({}, {}, {:X}, {}, {})", ts, str, flags, len, checksum),
1388 IVRRecord::IntValue(ref name, val) =>
1389 write!(f, "({} = {})", String::from_utf8_lossy(name), val),
1390 IVRRecord::BinaryData(ref name, ref val) =>
1391 write!(f, "({} = {} bytes)", String::from_utf8_lossy(name), val.len()),
1392 IVRRecord::StringData(ref name, ref val) =>
1393 write!(f, "({} = {})", String::from_utf8_lossy(name), String::from_utf8_lossy(val)),
1394 IVRRecord::HeaderEnd => write!(f, "header end"),
1395 IVRRecord::DataEnd => write!(f, "data end"),
1396 IVRRecord::DataStart => write!(f, "data start"),
1401 struct RecordDemuxer {
1405 remap_ids: Vec<u32>,
1408 impl RecordDemuxer {
1409 fn new(pos: u64, start_str: u32) -> Self {
1414 remap_ids: Vec::new(),
1417 fn parse_header(&mut self, src: &mut ByteReader, strmgr: &mut StreamManager, str_data: &mut CommonStreamData) -> DemuxerResult<()> {
1418 src.seek(SeekFrom::Start(self.cur_pos))?;
1419 let magic = src.read_u32be()?;
1420 validate!(magic == mktag!(b".REC"));
1421 let _smth = src.read_byte()?;
1422 let num_entries = src.read_u32be()? as usize;
1423 for _ in 0..num_entries {
1424 let _rec = IVRRecord::read(src)?;
1425 //println!(" header rec {}", _rec);
1427 let mut has_seek_table = false;
1428 let mut cur_str_no = 0;
1430 let rec = IVRRecord::read(src)?;
1432 IVRRecord::HeaderEnd => { break; },
1433 IVRRecord::StreamProperties(num) => {
1434 let stream_no = cur_str_no + self.start_str;
1436 let mut parsed = false;
1437 let mut real_stream_no = 0;
1438 let mut duration = 0;
1440 let rec = IVRRecord::read(src)?;
1441 //println!(" strm property {}", rec);
1443 IVRRecord::IntValue(ref name, val) => {
1444 if name == b"StreamNumber\0" {
1445 real_stream_no = val;
1447 if name == b"Duration\0" {
1451 IVRRecord::BinaryData(ref name, ref val) => {
1452 if name == b"OpaqueData\0" {
1454 let is_mlti = RMDemuxCommon::parse_stream_info(str_data, strmgr, stream_no, val, duration)?;
1456 str_data.str_ids.push(stream_no);
1461 IVRRecord::StringData(ref name, ref val) => {
1462 if (name == b"SeekType\0") && (val != b"None\0") {
1463 has_seek_table = true;
1466 _ => { return Err(DemuxerError::InvalidData); }
1470 str_data.streams.push(RMStreamType::Unknown);
1471 str_data.str_ids.push(stream_no);
1473 self.remap_ids.push(real_stream_no);
1475 _ => {println!(" unexpected {}", rec); return Err(DemuxerError::InvalidData); }
1478 println!(" now @ {:X}", src.tell());
1479 let off0 = src.read_u32be()? as u64;
1480 let _off1 = src.read_u32be()?;
1481 let _off2 = src.read_u32be()?;
1482 validate!(off0 + self.start_pos == src.tell());
1483 println!(" has seek tab: {}", has_seek_table);
1486 let data_off = src.read_u32be()? as u64;
1487 println!(" new off {:X}", data_off);
1488 let pos = src.tell();
1489 validate!(data_off + self.start_pos > pos);
1490 src.read_skip((data_off + self.start_pos - pos) as usize)?;
1491 let rec = IVRRecord::read(src)?;
1492 validate!(rec.is_data_start());
1494 let ntype = src.peek_byte()?;
1495 validate!((ntype == 2) || (ntype == 7)); // packet or data end, no start
1498 self.cur_pos = src.tell();
1502 fn get_packet(&mut self, src: &mut ByteReader, str_data: &mut CommonStreamData, strmgr: &StreamManager, queued_pkts: &mut Vec<NAPacket>, slice_buf: &mut Vec<u8>) -> DemuxerResult<NAPacket> {
1503 src.seek(SeekFrom::Start(self.cur_pos))?;
1505 let rec = IVRRecord::read(src)?;
1507 IVRRecord::Packet { ts, str, flags, len, .. } => {
1508 let payload_size = len;
1509 let sr = self.remap_ids.iter().position(|x| *x == str);
1510 validate!(sr.is_some());
1511 let str_no = self.start_str + (sr.unwrap() as u32);
1512 let pkt_grp = ((flags >> 8) & 0xFF) as u16;
1513 let stream_id = str_data.get_stream_id(str_no as u32, pkt_grp);
1514 let sr = str_data.find_stream(stream_id);
1516 src.read_skip(payload_size)?;
1517 return Err(DemuxerError::InvalidData);
1519 let str_id = sr.unwrap();
1521 let streamres = strmgr.get_stream_by_id(stream_id);
1522 if streamres.is_none() {
1523 src.read_skip(payload_size)?;
1526 let stream = streamres.unwrap();
1527 if strmgr.is_ignored_id(stream_id) {
1528 src.read_skip(payload_size)?;
1531 let keyframe = false;
1532 let ret = RMDemuxCommon::parse_packet_payload(src, &mut str_data.streams[str_id], stream, slice_buf, queued_pkts, keyframe, ts, payload_size);
1533 if let Err(DemuxerError::TryAgain) = ret {
1536 self.cur_pos = src.tell();
1540 IVRRecord::DataEnd => return Err(DemuxerError::EOF),
1541 _ => return Err(DemuxerError::InvalidData),
1547 struct RealIVRDemuxer<'a> {
1548 src: &'a mut ByteReader<'a>,
1549 recs: Vec<RecordDemuxer>,
1551 queued_pkts: Vec<NAPacket>,
1553 str_data: CommonStreamData,
1556 impl<'a> DemuxCore<'a> for RealIVRDemuxer<'a> {
1557 #[allow(unused_variables)]
1558 fn open(&mut self, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex) -> DemuxerResult<()> {
1559 let magic = self.src.peek_u32be()?;
1560 if magic == mktag!(b".REC") {
1561 let mut rec = RecordDemuxer::new(0, 0);
1562 rec.parse_header(&mut self.src, strmgr, &mut self.str_data)?;
1563 self.recs.push(rec);
1564 } else if magic == mktag!(b".R1M") {
1565 println!("R1M kind");
1566 self.src.read_skip(4)?; // magic
1567 self.src.read_skip(3)?; // always 0, 1, 1 ?
1568 let _name = IVRRecord::read_string(&mut self.src)?;
1569 self.src.read_skip(1)?; // always 0?
1570 let len1 = self.src.read_u32be()? as u64;
1571 let off1 = self.src.read_u64be()?;
1572 let cpos = self.src.tell();
1573 validate!(off1 == len1 + cpos - 8);
1574 self.src.read_skip((off1 - cpos) as usize)?;
1576 let typ = self.src.read_byte()?;
1577 println!(" at {:X} type {:02X}", self.src.tell(), typ);
1580 let len = self.src.read_u32be()?;
1581 self.src.read_skip(len as usize)?;
1584 let len = self.src.read_u32be()? as u64;
1585 let pos = self.src.tell();
1587 let num_streams = self.str_data.streams.len() as u32;
1588 let mut rec = RecordDemuxer::new(pos + 12, num_streams);
1589 rec.parse_header(&mut self.src, strmgr, &mut self.str_data)?;
1590 self.recs.push(rec);
1592 self.src.seek(SeekFrom::Start(pos + len))?;
1595 let mut buf: [u8; 2] = [0; 2];
1596 self.src.peek_buf(&mut buf)?;
1597 if (buf[0] == b'J') && (buf[1] == b'M') { // RJMx markers at the end of file
1600 return Err(DemuxerError::InvalidData);
1603 _ => { return Err(DemuxerError::InvalidData); },
1607 return Err(DemuxerError::InvalidData);
1613 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket> {
1614 if !self.queued_pkts.is_empty() {
1615 let pkt = self.queued_pkts.pop().unwrap();
1619 if self.cur_rec >= self.recs.len() { return Err(DemuxerError::EOF); }
1620 let res = self.recs[self.cur_rec].get_packet(&mut self.src, &mut self.str_data, strmgr, &mut self.queued_pkts, &mut self.slice_buf);
1621 if let Err(DemuxerError::EOF) = res {
1629 #[allow(unused_variables)]
1630 fn seek(&mut self, time: NATimePoint, seek_idx: &SeekIndex) -> DemuxerResult<()> {
1634 fn get_duration(&self) -> u64 { 0 }
1637 impl<'a> NAOptionHandler for RealIVRDemuxer<'a> {
1638 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
1639 fn set_options(&mut self, _options: &[NAOption]) { }
1640 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
1643 impl<'a> RealIVRDemuxer<'a> {
1644 fn new(io: &'a mut ByteReader<'a>) -> Self {
1649 queued_pkts: Vec::new(),
1650 slice_buf: Vec::new(),
1651 str_data: CommonStreamData::new(),
1656 static RM_VIDEO_CODEC_REGISTER: &[(&[u8;4], &str)] = &[
1657 (b"RV10", "realvideo1"),
1658 (b"RV20", "realvideo2"),
1659 (b"RVTR", "realvideo2"),
1660 (b"RV30", "realvideo3"),
1661 (b"RV40", "realvideo4"),
1662 (b"RV60", "realvideo6"),
1663 (b"CLV1", "clearvideo_rm"),
1666 static RM_AUDIO_CODEC_REGISTER: &[(&[u8;4], &str)] = &[
1667 (b"lpcJ", "ra14.4"),
1668 (b"28_8", "ra28.8"),
1672 (b"atrc", "atrac3"),
1678 pub struct RealMediaDemuxerCreator { }
1680 impl DemuxerCreator for RealMediaDemuxerCreator {
1681 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a> {
1682 Box::new(RealMediaDemuxer::new(br))
1684 fn get_name(&self) -> &'static str { "realmedia" }
1687 pub struct RealAudioDemuxerCreator { }
1689 impl DemuxerCreator for RealAudioDemuxerCreator {
1690 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a> {
1691 Box::new(RealAudioDemuxer::new(br))
1693 fn get_name(&self) -> &'static str { "realaudio" }
1696 pub struct RealIVRDemuxerCreator { }
1698 impl DemuxerCreator for RealIVRDemuxerCreator {
1699 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a> {
1700 Box::new(RealIVRDemuxer::new(br))
1702 fn get_name(&self) -> &'static str { "real_ivr" }
1711 fn test_rm_demux() {
1713 File::open("assets/RV/rv10_dnet_640x352_realvideo_encoder_4.0.rm").unwrap();
1714 // File::open("assets/RV/rv20_cook_640x352_realproducer_plus_8.51.rm").unwrap();
1715 // File::open("assets/RV/rv20_svt_atrc_640x352_realproducer_plus_8.51.rm").unwrap();
1716 // File::open("assets/RV/rv30_atrc_384x208_realproducer_plus_8.51.rm").unwrap();
1717 // File::open("assets/RV/rv30_chroma_drift.rm").unwrap();
1718 // File::open("assets/RV/rv30_weighted_mc.rm").unwrap();
1719 // File::open("assets/RV/rv40_weighted_mc.rmvb").unwrap();
1720 // File::open("assets/RV/rv40_weighted_mc_2.rmvb").unwrap();
1721 // File::open("assets/RV/clv1_sipr_384x208_realvideo_encoder_4.0.rm").unwrap();
1722 // File::open("assets/RV/luckynight.rmvb").unwrap();
1723 // File::open("assets/RV/rv40_ralf.rmvb").unwrap();
1724 let mut fr = FileReader::new_read(&mut file);
1725 let mut br = ByteReader::new(&mut fr);
1726 let mut dmx = RealMediaDemuxer::new(&mut br);
1727 let mut sm = StreamManager::new();
1728 let mut si = SeekIndex::new();
1729 dmx.open(&mut sm, &mut si).unwrap();
1732 let pktres = dmx.get_frame(&mut sm);
1733 if let Err(e) = pktres {
1734 if e == DemuxerError::EOF { break; }
1737 let pkt = pktres.unwrap();
1738 println!("Got {}", pkt);
1740 //panic!("the end");
1743 fn test_ra_demux() {
1745 // File::open("assets/RV/welcome288.ra").unwrap();
1746 File::open("assets/RV/diemusik.ra").unwrap();
1747 let mut fr = FileReader::new_read(&mut file);
1748 let mut br = ByteReader::new(&mut fr);
1749 let mut dmx = RealAudioDemuxer::new(&mut br);
1750 let mut sm = StreamManager::new();
1751 let mut si = SeekIndex::new();
1752 dmx.open(&mut sm, &mut si).unwrap();
1755 let pktres = dmx.get_frame(&mut sm);
1756 if let Err(e) = pktres {
1757 if e == DemuxerError::EOF { break; }
1760 let pkt = pktres.unwrap();
1761 println!("Got {}", pkt);
1765 fn test_ivr_demux() {
1767 File::open("assets/RV/Opener_rm_hi.ivr").unwrap();
1768 // File::open("assets/RV/SherwinWilliamsCommercial.ivr").unwrap();
1769 let mut fr = FileReader::new_read(&mut file);
1770 let mut br = ByteReader::new(&mut fr);
1771 let mut dmx = RealIVRDemuxer::new(&mut br);
1772 let mut sm = StreamManager::new();
1773 let mut si = SeekIndex::new();
1774 dmx.open(&mut sm, &mut si).unwrap();
1777 let pktres = dmx.get_frame(&mut sm);
1778 if let Err(e) = pktres {
1779 if e == DemuxerError::EOF { break; }
1782 let pkt = pktres.unwrap();
1783 println!("Got {}", pkt);