]> git.nihav.org Git - nihav.git/blame_incremental - nihav-realmedia/src/demuxers/realmedia.rs
add FLAC packetiser and raw stream demuxer
[nihav.git] / nihav-realmedia / src / demuxers / realmedia.rs
... / ...
CommitLineData
1use super::*;
2use nihav_core::demuxers::DemuxerError::*;
3use std::io::SeekFrom;
4use std::mem;
5use std::fmt;
6
7macro_rules! mktag {
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)
10 });
11 ($arr:expr) => ({
12 (($arr[0] as u32) << 24) | (($arr[1] as u32) << 16) | (($arr[2] as u32) << 8) | ($arr[3] as u32)
13 });
14}
15
16const RM_SIPRO_BLOCK_SIZES: [usize; 4] = [ 29, 19, 37, 20 ];
17const 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 ]
28];
29
30struct RMVideoStream {
31 frame: Vec<u8>,
32 hdr_size: usize,
33 frame_size: usize,
34 frame_pos: usize,
35}
36
37impl RMVideoStream {
38 fn new() -> Self {
39 RMVideoStream {
40 frame: Vec::new(),
41 hdr_size: 0,
42 frame_size: 0,
43 frame_pos: 0,
44 }
45 }
46 fn flush(&mut self) {
47 self.frame.clear();
48 self.frame_size = 0;
49 self.frame_pos = 0;
50 }
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;
55 self.frame_pos = 0;
56 self.add_slice(1, data).unwrap();
57 }
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();
64 Ok(())
65 }
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;
76 }
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);
80 self.flush();
81 v
82 }
83}
84
85#[derive(Clone,Copy,PartialEq)]
86enum Deinterleaver {
87 None,
88 RA28_8,
89 Generic,
90 Sipro,
91 VBR,
92}
93
94struct RMAudioStream {
95 deint: Deinterleaver,
96 iinfo: Option<InterleaveInfo>,
97 buf: Vec<u8>,
98 sub_packet: usize,
99}
100
101const RM_ILEAVE_INT0: u32 = mktag!(b"Int0");
102const RM_ILEAVE_INT4: u32 = mktag!(b"Int4");
103const RM_ILEAVE_GENR: u32 = mktag!(b"genr");
104const RM_ILEAVE_SIPR: u32 = mktag!(b"sipr");
105const RM_ILEAVE_VBRF: u32 = mktag!(b"vbrf");
106const RM_ILEAVE_VBRS: u32 = mktag!(b"vbrs");
107
108impl RMAudioStream {
109 fn new(iinfo: Option<InterleaveInfo>) -> Self {
110 let deint;
111 let buf: Vec<u8>;
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 },
121 };
122 match deint {
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];
129 },
130 Deinterleaver::VBR => {
131 buf = Vec::new();
132 },
133 };
134 } else {
135 deint = Deinterleaver::None;
136 buf = Vec::new();
137 }
138 RMAudioStream { deint, iinfo, buf, sub_packet: 0 }
139 }
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);
143
144 if keyframe {
145 self.sub_packet = 0;
146 }
147 match self.deint {
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)?;
159 }
160 self.sub_packet += 1;
161 if self.sub_packet == factor {
162 self.sub_packet = 0;
163 return Ok(NAPacket::new(stream, ts, true, self.buf.clone()));
164 } else {
165 return Err(DemuxerError::TryAgain);
166 }
167 },
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;
175
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)?;
180 }
181 },
182 Deinterleaver::Sipro => {
183 let iinfo = self.iinfo.unwrap();
184 let fsize = iinfo.frame_size as usize;
185 let ppos = self.sub_packet;
186
187 let mut dst = &mut self.buf[fsize * ppos..][..fsize];
188 src.read_buf(&mut dst)?;
189 },
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;
199 tot_size += sz;
200 sizes.push(sz);
201 }
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 };
207 first = false;
208 let pkt = src.read_packet(stream.clone(), cur_ts, true, *size)?;
209 queued_packets.push(pkt);
210 }
211 queued_packets.reverse();
212 let pkt0 = queued_packets.pop().unwrap();
213 return Ok(pkt0);
214 },
215 };
216
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;
220
221 self.sub_packet += 1;
222 if self.sub_packet < factor {
223 return Err(DemuxerError::TryAgain);
224 }
225
226 self.sub_packet = 0;
227
228 if self.deint == Deinterleaver::Sipro {
229 sipro_restore(&mut self.buf, factor, iinfo.frame_size as usize);
230 }
231
232 let mut frames_iter = self.buf.chunks(fsize);
233 let pkt0 = frames_iter.next().unwrap();
234
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);
239 }
240 queued_packets.reverse();
241 Ok(NAPacket::new(stream, ts, true, pkt0.to_vec()))
242 }
243}
244
245fn sipro_restore(buf: &mut [u8], factor: usize, fsize: usize) {
246 let stride = factor * fsize * 2 / 96;
247 for i in 0..38 {
248 let mut sidx = (RM_SIPRO_SWAPS[i][0] as usize) * stride;
249 let mut didx = (RM_SIPRO_SWAPS[i][1] as usize) * stride;
250 for _ in 0..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;
255
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))));
258
259 sidx += 1;
260 didx += 1;
261 }
262 }
263}
264
265struct SubstreamInfo {
266 id: u32,
267 map: Vec<u16>,
268 str_ids: Vec<u32>,
269}
270
271struct MLTIMapper {
272 sub_info: Vec<SubstreamInfo>,
273 sstr_id: u32,
274}
275
276impl MLTIMapper {
277 fn new() -> Self {
278 MLTIMapper {
279 sub_info: Vec::new(),
280 sstr_id: 0x10000,
281 }
282 }
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);
286 }
287 fn get_substream_no(&self) -> u32 {
288 self.sstr_id - 1
289 }
290 fn find_idx(&self, stream_no: u32) -> Option<usize> {
291 self.sub_info.iter().position(|x| x.id == stream_no)
292 }
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);
296 }
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);
300 self.sstr_id += 1;
301 }
302 fn is_mlti_stream(&self, stream_no: u32) -> bool {
303 self.find_idx(stream_no).is_some()
304 }
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]);
311 }
312 }
313 }
314 None
315 }
316}
317
318enum RMStreamType {
319 Audio(RMAudioStream),
320 Video(RMVideoStream),
321 Logical,
322 Unknown,
323}
324
325struct CommonStreamData {
326 streams: Vec<RMStreamType>,
327 str_ids: Vec<u32>,
328 mlti_mapper: MLTIMapper,
329}
330
331impl CommonStreamData {
332 fn new() -> Self {
333 CommonStreamData {
334 streams: Vec::new(),
335 str_ids: Vec::new(),
336 mlti_mapper: MLTIMapper::new(),
337 }
338 }
339 fn get_stream_id(&self, str_no: u32, pkt_grp: u16) -> u32 {
340 if !self.mlti_mapper.is_mlti_stream(str_no) {
341 str_no
342 } else {
343 self.mlti_mapper.find_substream(str_no, pkt_grp).unwrap()
344 }
345 }
346 fn find_stream(&self, stream_id: u32) -> Option<usize> {
347 self.str_ids.iter().position(|x| *x == stream_id)
348 }
349}
350
351struct RealMediaDemuxer<'a> {
352 src: &'a mut ByteReader<'a>,
353 data_pos: u64,
354 data_end: u64,
355 next_data: u64,
356 data_ver: u16,
357 num_packets: u32,
358 cur_packet: u32,
359
360 str_data: CommonStreamData,
361
362 data_chunks: Vec<(u64, u32, u16)>,
363 cur_data_chunk: usize,
364
365 queued_pkts: Vec<NAPacket>,
366 slice_buf: Vec<u8>,
367}
368
369fn 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; }
372 }
373 "unknown"
374}
375
376fn 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)))
381 } else {
382 let val = ((tmp as u32) << 16) | (src.read_u16be()? as u32);
383 Ok((flag, val & 0x3FFFFFFF))
384 }
385}
386
387fn 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
391 vec[4] = 1;
392 src.read_buf(&mut vec[9..])?;
393
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))
397}
398
399fn read_multiple_frame(src: &mut ByteReader, stream: NAStreamRef, keyframe: bool, skip_mtype: bool) -> DemuxerResult<NAPacket> {
400 if !skip_mtype {
401 let mtype = src.read_byte()?;
402 validate!(mtype == 0xC0);
403 }
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);
408
409 read_video_buf(src, stream, timestamp, keyframe, frame_size as usize)
410}
411
412struct RMDemuxCommon {}
413
414impl 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());
428
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()?;
433
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") {
443 is_mlti = true;
444 let num_rules = src.read_u16be()? as usize;
445 let mut max_sub = 0;
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);
451 }
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();
460 {
461 let hdrsrc = &edata[pos..][..hdr_size];
462 let mut mr = MemoryReader::new_read(hdrsrc);
463 let mut hsrc = ByteReader::new(&mut mr);
464
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)?;
473 } else {
474println!("unknown MLTI substream {:08X} / {:08X}", tag, tag2);
475 return Err(DemuxerError::InvalidData);
476 }
477 str_data.str_ids.push(stream_no);
478 }
479 }
480 } else {
481 str_data.streams.push(RMStreamType::Logical);
482 }
483 Ok(is_mlti)
484 }
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 {
488 3 => {
489 parse_aformat3(src)?
490 },
491 4 => {
492 parse_aformat4(src)?
493 },
494 5 => {
495 parse_aformat5(src)?
496 },
497 _ => {
498 println!("unknown version {}", ver);
499 return Err(DemuxerError::InvalidData);
500 },
501 };
502println!(" 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
506 } else {
507 validate!(ainfo.flavor <= 3);
508 RM_SIPRO_BLOCK_SIZES[ainfo.flavor as usize]
509 };
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 {
514 None
515 } else {
516 let eslice = &edata_[(src.tell() as usize)..];
517 Some(eslice.to_vec())
518 };
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); }
523
524 let astr = RMAudioStream::new(ainfo.ileave_info);
525 streams.push(RMStreamType::Audio(astr));
526 Ok(())
527 }
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<()> {
530 src.read_skip(4)?;
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()?;
537 let _fps;
538 if tag2 == mktag!('V', 'I', 'D', 'O') {
539 _fps = src.read_u32be()?;
540 } else {
541 _fps = 0x10000;
542 }
543 let extradata: Option<Vec<u8>>;
544 if src.left() > 0 {
545 let eslice = &edata_[(src.tell() as usize)..];
546 extradata = Some(eslice.to_vec());
547 } else {
548 extradata = None;
549 }
550 let cname = find_codec_name(RM_VIDEO_CODEC_REGISTER, fcc);
551
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); }
556
557 let vstr = RMVideoStream::new();
558 streams.push(RMStreamType::Video(vstr));
559 Ok(())
560 }
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> {
563 match rmstream {
564 RMStreamType::Video(ref mut vstr) => {
565
566 let pos = src.tell();
567 let b0 = src.read_byte()?;
568 match b0 >> 6 {
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;
579
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())?;
583 if packet_num == 1 {
584 vstr.start_slice(num_pkts, frame_size as usize, slice_buf.as_slice());
585 } else {
586 vstr.add_slice(packet_num as usize, slice_buf.as_slice())?;
587 }
588 if (packet_num as usize) < num_pkts {
589 return Err(DemuxerError::TryAgain);
590 }
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());
595 Ok(pkt)
596 },
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)
601 },
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());
615 } else {
616 vstr.add_slice(packet_num as usize, slice_buf.as_slice())?;
617 }
618
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());
623 }
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());
628 Ok(pkt)
629 },
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());
638 }
639 queued_pkts.reverse();
640 res
641 },
642 }
643 },
644 RMStreamType::Audio(ref mut astr) => {
645 astr.read_apackets(queued_pkts, src, stream, ts, keyframe, payload_size)
646 },
647 _ => {
648 src.read_skip(payload_size)?;
649 Err(DemuxerError::InvalidData)
650 },
651 }
652 }
653}
654
655impl<'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)?;
658 Ok(())
659 }
660
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();
665 return Ok(pkt);
666 }
667 loop {
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();
676 self.data_ver = ver;
677 self.data_end = self.data_pos + (size as u64);
678 if self.parse_data_start().is_ok() {
679 continue;
680 }
681 }
682 }
683 return Err(DemuxerError::EOF);
684 }
685
686 let pkt_start = self.src.tell();
687 let ver = self.src.read_u16be()?;
688 validate!(ver <= 1);
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()?;
692 let pkt_grp;
693 let flags;
694 if ver == 0 {
695 pkt_grp = self.src.read_byte()? as u16;
696 flags = self.src.read_byte()?;
697 } else {
698 //asm_rule = self.src.read_u16be()?;
699 //asm_flags = self.src.read_byte()?;
700 self.src.read_skip(2)?;
701 pkt_grp = 0;
702 self.src.read_skip(1)?;
703 flags = 0;
704 }
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;
708
709 let payload_size = len - (hdr_size as usize);
710
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);
713 if sr.is_none() {
714//println!("stream {} not found", str_no);
715 self.src.read_skip(payload_size)?;
716 return Err(DemuxerError::InvalidData);
717 }
718 let str_id = sr.unwrap();
719
720 let streamres = strmgr.get_stream_by_id(stream_id);
721 if streamres.is_none() {
722 self.src.read_skip(payload_size)?;
723 continue;
724 }
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)?;
729 continue;
730 }
731 //todo skip unwanted packet
732 let keyframe = (flags & KEYFRAME_FLAG) != 0;
733
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 {
736 continue;
737 } else {
738 return ret;
739 }
740 }
741 }
742
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);
747 if ret.is_none() {
748 return Err(DemuxerError::SeekError);
749 }
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);
755 if seek_pos < end {
756 self.cur_packet = 0;
757 self.data_pos = seek_pos;
758 self.data_ver = *ver;
759 self.data_end = end;
760 self.src.seek(SeekFrom::Start(seek_pos))?;
761 return Ok(());
762 }
763 }
764 Err(DemuxerError::SeekError)
765 }
766
767 fn get_duration(&self) -> u64 { 0 }
768}
769
770impl<'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 }
774}
775
776fn read_chunk(src: &mut ByteReader) -> DemuxerResult<(u32, u32, u16)> {
777 let id = src.read_u32be()?;
778if id == 0 { return Ok((0, 0, 0)); }
779 let size = src.read_u32be()?;
780if size == 0 {
781 let ver = src.read_u16be()?;
782 validate!(ver <= 2);
783 return Ok((id, 0x0FFFFFFF, ver));
784}
785 validate!(size >= 10);
786 let ver = src.read_u16be()?;
787 validate!(ver <= 2);
788 Ok((id, size, ver))
789}
790
791#[derive(Clone,Copy,Debug)]
792struct InterleaveInfo {
793 id: u32,
794 factor: u16,
795 block_size: u16,
796 frame_size: u16,
797}
798
799#[derive(Clone,Copy,Debug)]
800struct RealAudioInfo {
801 fcc: u32,
802 sample_rate: u32,
803 sample_size: u16,
804 flavor: u16,
805 channels: u16,
806 channel_mask: u32,
807 granularity: u32,
808 bytes_per_minute: u32,
809 total_bytes: u32,
810 edata_size: u32,
811 ileave_info: Option<InterleaveInfo>
812}
813
814impl RealAudioInfo {
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)
818 } else {
819 0
820 }
821 }
822}
823
824fn 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)?;
833 Ok(())
834}
835
836#[allow(unused_variables)]
837fn 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()?;
845
846 skip_ra_metadata(src)?;
847
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()?;
852
853 let end = src.tell();
854 validate!(end - start <= (header_len as u64) + 2);
855
856 Ok(RealAudioInfo {
857 fcc, flavor,
858 sample_rate: 8000, sample_size: 16, channels: 1, channel_mask: 0,
859 granularity, bytes_per_minute,
860 total_bytes, edata_size: 0,
861 ileave_info: None,
862 })
863}
864
865#[allow(unused_variables)]
866fn 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()?;
894
895 skip_ra_metadata(src)?;
896
897 let end = src.tell();
898 validate!(end - start <= (header_size as u64) + 10);
899
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,
904 })
905 } else {
906 None
907 };
908
909 Ok(RealAudioInfo {
910 fcc, flavor,
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,
914 ileave_info,
915 })
916}
917
918#[allow(unused_variables)]
919fn 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 {
947unimplemented!("ra5 interleave pattern");
948 }
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)?;
954 } else {
955 validate!(end - start <= (header_size as u64) + 15);
956 }
957
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,
961 })
962 } else {
963 None
964 };
965 if (fcc == mktag!(b"raac")) || (fcc == mktag!(b"racp")) {
966 validate!(edata_size > 1);
967 edata_size -= 1;
968 src.read_skip(1)?;
969 }
970
971 Ok(RealAudioInfo {
972 fcc, flavor,
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,
976 ileave_info,
977 })
978}
979
980const RMVB_HDR_SIZE: u32 = 18;
981const RMVB_PROP_SIZE: u32 = 50;
982const KEYFRAME_FLAG: u8 = 0x02;
983
984impl<'a> RealMediaDemuxer<'a> {
985 fn new(io: &'a mut ByteReader<'a>) -> Self {
986 RealMediaDemuxer {
987 src: io,
988 data_pos: 0,
989 data_end: 0,
990 next_data: 0,
991 data_ver: 0,
992 num_packets: 0,
993 cur_packet: 0,
994 str_data: CommonStreamData::new(),
995 data_chunks: Vec::new(),
996 cur_data_chunk: 0,
997 queued_pkts: Vec::new(),
998 slice_buf: Vec::new(),
999 }
1000 }
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)?;
1012 }
1013
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()?;
1025 if ver == 2 {
1026 self.src.read_skip(4)?;
1027 }
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)?;
1034 }
1035
1036 for _ in 0..num_hdr {
1037 if self.src.is_eof() {
1038 //warn maybe?
1039 break;
1040 }
1041 let res = self.parse_chunk(strmgr, seek_idx);
1042 match res {
1043 Ok(last) => { if last { break; } },
1044 Err(DemuxerError::IOError) => { break; },
1045 Err(etype) => {
1046 if self.data_chunks.is_empty() { // data is not found, report error
1047 return Err(etype);
1048 }
1049 },
1050 };
1051 }
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()?;
1061 Ok(())
1062 }
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?
1067 }
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;
1072 Ok(())
1073 }
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);
1077
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));
1083 }
1084 else if id == mktag!(b"INDX") {
1085 if !seek_idx.skip_index {
1086 self.parse_index(seek_idx, (size as usize) - 10, ver)?;
1087 }
1088 }
1089 else if id == 0 { return Ok(true); }
1090 else { println!("unknown chunk type {:08X}", id); }
1091
1092 let cpos = self.src.tell();
1093 if cpos < end_pos {
1094 self.src.read_skip((end_pos - cpos) as usize)?;
1095 }
1096 Ok(false)
1097 }
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)?;
1108 Ok(())
1109 }
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)?;
1131 Some(edvec)
1132 };
1133 let mut is_mlti = false;
1134 if edata_size > 8 {
1135 if let Some(edata_) = edata {
1136 is_mlti = RMDemuxCommon::parse_stream_info(&mut self.str_data, strmgr, stream_no, &edata_, duration)?;
1137 }
1138 } else {
1139 self.str_data.streams.push(RMStreamType::Unknown);
1140 }
1141 if !is_mlti {
1142 self.str_data.str_ids.push(stream_no);
1143 }
1144
1145 Ok(())
1146 }
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()?;
1152 if ver == 2 {
1153 self.src.read_u32be()?;
1154 }
1155 if ver == 0 {
1156 validate!(chunk_size == num_entries * 14 + 10);
1157 } else {
1158 validate!(chunk_size == num_entries * 18 + 14);
1159 }
1160 if num_entries == 0 { return Ok(()); }
1161
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;
1168 if ver == 2 {
1169 self.src.read_u32be()?;
1170 }
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 });
1174 }
1175 idx.filled = true;
1176 seek_idx.mode = SeekIndexMode::Present;
1177 Ok(())
1178 }
1179}
1180
1181fn read_string_size(src: &mut ByteReader, size: usize) -> DemuxerResult<String> {
1182 let mut vec: Vec<u8> = Vec::new();
1183 for _ in 0..size {
1184 let c = src.read_byte()?;
1185 vec.push(c);
1186 }
1187 let str = String::from_utf8(vec);
1188 if let Ok(res) = str {
1189 Ok(res)
1190 } else {
1191 Ok(String::new())
1192 }
1193}
1194
1195struct RealAudioDemuxer<'a> {
1196 src: &'a mut ByteReader<'a>,
1197 stream: Option<RMAudioStream>,
1198 data_start: u64,
1199 data_end: u64,
1200 blk_size: usize,
1201 queued_pkts: Vec<NAPacket>,
1202}
1203
1204impl<'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 {
1211 3 => {
1212 parse_aformat3(&mut self.src)?
1213 },
1214 4 => {
1215 parse_aformat4(&mut self.src)?
1216 },
1217 5 => {
1218 parse_aformat5(&mut self.src)?
1219 },
1220 _ => {
1221 println!("unknown version {}", ver);
1222 return Err(DemuxerError::InvalidData);
1223 },
1224 };
1225println!(" 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
1229 } else {
1230 validate!(ainfo.flavor <= 3);
1231 RM_SIPRO_BLOCK_SIZES[ainfo.flavor as usize]
1232 };
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 {
1237 None
1238 } else {
1239 let mut dta: Vec<u8> = vec![0; ainfo.edata_size as usize];
1240 self.src.read_buf(dta.as_mut_slice())?;
1241 Some(dta)
1242 };
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); }
1246
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);
1252
1253 Ok(())
1254 }
1255
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();
1259 return Ok(pkt);
1260 }
1261 if (self.data_end != 0) && (self.src.tell() >= self.data_end) {
1262 return Err(DemuxerError::EOF);
1263 }
1264 let streamres = strmgr.get_stream_by_id(0);
1265 let stream = streamres.unwrap();
1266 if let Some(ref mut astr) = self.stream {
1267 loop {
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 {
1270 continue;
1271 }
1272 return ret;
1273 }
1274 }
1275 Err(DemuxerError::NoSuchInput)
1276 }
1277
1278 #[allow(unused_variables)]
1279 fn seek(&mut self, time: NATimePoint, seek_idx: &SeekIndex) -> DemuxerResult<()> {
1280 Err(NotImplemented)
1281 }
1282
1283 fn get_duration(&self) -> u64 { 0 }
1284}
1285
1286impl<'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 }
1290}
1291
1292impl<'a> RealAudioDemuxer<'a> {
1293 fn new(io: &'a mut ByteReader<'a>) -> Self {
1294 RealAudioDemuxer {
1295 src: io,
1296 data_start: 0,
1297 data_end: 0,
1298 blk_size: 0,
1299 stream: None,
1300 queued_pkts: Vec::new(),
1301 }
1302 }
1303}
1304
1305enum IVRRecord {
1306 Invalid(u8),
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>),
1312 HeaderEnd,
1313 DataStart,
1314 DataEnd,
1315}
1316
1317impl IVRRecord {
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())?;
1322 Ok(val)
1323 }
1324
1325 fn read(src: &mut ByteReader) -> DemuxerResult<Self> {
1326 let code = src.read_byte()?;
1327 match code {
1328 1 => {
1329 let val = src.read_u32be()? as usize;
1330 Ok(IVRRecord::StreamProperties(val))
1331 },
1332 2 => {
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 })
1340 },
1341 3 => {
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))
1347 },
1348 4 => {
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))
1354 },
1355 5 => {
1356 let name = Self::read_string(src)?;
1357 let val = Self::read_string(src)?;
1358 Ok(IVRRecord::StringData(name, val))
1359 },
1360 6 => Ok(IVRRecord::HeaderEnd),
1361 7 => {
1362 src.read_skip(8)?; // always zero?
1363 Ok(IVRRecord::DataEnd)
1364 },
1365 8 => {
1366 src.read_skip(8)?; // always zero?
1367 Ok(IVRRecord::DataStart)
1368 },
1369 _ => Ok(IVRRecord::Invalid(code)),
1370 }
1371 }
1372 fn is_data_start(&self) -> bool {
1373 match *self {
1374 IVRRecord::DataStart => true,
1375 _ => false,
1376 }
1377 }
1378}
1379
1380impl fmt::Display for IVRRecord {
1381 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1382 match *self {
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"),
1397 }
1398 }
1399}
1400
1401struct RecordDemuxer {
1402 start_pos: u64,
1403 cur_pos: u64,
1404 start_str: u32,
1405 remap_ids: Vec<u32>,
1406}
1407
1408impl RecordDemuxer {
1409 fn new(pos: u64, start_str: u32) -> Self {
1410 RecordDemuxer {
1411 start_pos: pos,
1412 cur_pos: pos,
1413 start_str,
1414 remap_ids: Vec::new(),
1415 }
1416 }
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);
1426 }
1427 let mut has_seek_table = false;
1428 let mut cur_str_no = 0;
1429 loop {
1430 let rec = IVRRecord::read(src)?;
1431 match rec {
1432 IVRRecord::HeaderEnd => { break; },
1433 IVRRecord::StreamProperties(num) => {
1434 let stream_no = cur_str_no + self.start_str;
1435 cur_str_no += 1;
1436 let mut parsed = false;
1437 let mut real_stream_no = 0;
1438 let mut duration = 0;
1439 for _ in 0..num {
1440 let rec = IVRRecord::read(src)?;
1441//println!(" strm property {}", rec);
1442 match rec {
1443 IVRRecord::IntValue(ref name, val) => {
1444 if name == b"StreamNumber\0" {
1445 real_stream_no = val;
1446 }
1447 if name == b"Duration\0" {
1448 duration = val;
1449 }
1450 },
1451 IVRRecord::BinaryData(ref name, ref val) => {
1452 if name == b"OpaqueData\0" {
1453 validate!(!parsed);
1454 let is_mlti = RMDemuxCommon::parse_stream_info(str_data, strmgr, stream_no, val, duration)?;
1455 if !is_mlti {
1456 str_data.str_ids.push(stream_no);
1457 }
1458 parsed = true;
1459 }
1460 },
1461 IVRRecord::StringData(ref name, ref val) => {
1462 if (name == b"SeekType\0") && (val != b"None\0") {
1463 has_seek_table = true;
1464 }
1465 },
1466 _ => { return Err(DemuxerError::InvalidData); }
1467 };
1468 }
1469 if !parsed {
1470 str_data.streams.push(RMStreamType::Unknown);
1471 str_data.str_ids.push(stream_no);
1472 }
1473 self.remap_ids.push(real_stream_no);
1474 },
1475 _ => {println!(" unexpected {}", rec); return Err(DemuxerError::InvalidData); }
1476 };
1477 }
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);
1484 if has_seek_table {
1485 src.read_skip(4)?;
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());
1493 } else {
1494 let ntype = src.peek_byte()?;
1495 validate!((ntype == 2) || (ntype == 7)); // packet or data end, no start
1496 }
1497
1498 self.cur_pos = src.tell();
1499
1500 Ok(())
1501 }
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))?;
1504 loop {
1505 let rec = IVRRecord::read(src)?;
1506 match rec {
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);
1515 if sr.is_none() {
1516 src.read_skip(payload_size)?;
1517 return Err(DemuxerError::InvalidData);
1518 }
1519 let str_id = sr.unwrap();
1520
1521 let streamres = strmgr.get_stream_by_id(stream_id);
1522 if streamres.is_none() {
1523 src.read_skip(payload_size)?;
1524 continue;
1525 }
1526 let stream = streamres.unwrap();
1527 if strmgr.is_ignored_id(stream_id) {
1528 src.read_skip(payload_size)?;
1529 continue;
1530 }
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 {
1534 continue;
1535 } else {
1536 self.cur_pos = src.tell();
1537 return ret;
1538 }
1539 },
1540 IVRRecord::DataEnd => return Err(DemuxerError::EOF),
1541 _ => return Err(DemuxerError::InvalidData),
1542 }
1543 }
1544 }
1545}
1546
1547struct RealIVRDemuxer<'a> {
1548 src: &'a mut ByteReader<'a>,
1549 recs: Vec<RecordDemuxer>,
1550 cur_rec: usize,
1551 queued_pkts: Vec<NAPacket>,
1552 slice_buf: Vec<u8>,
1553 str_data: CommonStreamData,
1554}
1555
1556impl<'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") {
1565println!("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)?;
1575 loop {
1576 let typ = self.src.read_byte()?;
1577 println!(" at {:X} type {:02X}", self.src.tell(), typ);
1578 match typ {
1579 1 => {
1580 let len = self.src.read_u32be()?;
1581 self.src.read_skip(len as usize)?;
1582 },
1583 2 => {
1584 let len = self.src.read_u32be()? as u64;
1585 let pos = self.src.tell();
1586 if len > 0x20 {
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);
1591 }
1592 self.src.seek(SeekFrom::Start(pos + len))?;
1593 },
1594 b'R' => {
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
1598 break;
1599 } else {
1600 return Err(DemuxerError::InvalidData);
1601 }
1602 },
1603 _ => { return Err(DemuxerError::InvalidData); },
1604 };
1605 }
1606 } else {
1607 return Err(DemuxerError::InvalidData);
1608 }
1609
1610 Ok(())
1611 }
1612
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();
1616 return Ok(pkt);
1617 }
1618 loop {
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 {
1622 self.cur_rec += 1;
1623 } else {
1624 return res;
1625 }
1626 }
1627 }
1628
1629 #[allow(unused_variables)]
1630 fn seek(&mut self, time: NATimePoint, seek_idx: &SeekIndex) -> DemuxerResult<()> {
1631 Err(NotImplemented)
1632 }
1633
1634 fn get_duration(&self) -> u64 { 0 }
1635}
1636
1637impl<'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 }
1641}
1642
1643impl<'a> RealIVRDemuxer<'a> {
1644 fn new(io: &'a mut ByteReader<'a>) -> Self {
1645 RealIVRDemuxer {
1646 src: io,
1647 recs: Vec::new(),
1648 cur_rec: 0,
1649 queued_pkts: Vec::new(),
1650 slice_buf: Vec::new(),
1651 str_data: CommonStreamData::new(),
1652 }
1653 }
1654}
1655
1656static 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"),
1664];
1665
1666static RM_AUDIO_CODEC_REGISTER: &[(&[u8;4], &str)] = &[
1667 (b"lpcJ", "ra14.4"),
1668 (b"28_8", "ra28.8"),
1669 (b"cook", "cook"),
1670 (b"dnet", "ac3"),
1671 (b"sipr", "sipro"),
1672 (b"atrc", "atrac3"),
1673 (b"LSD:", "ralf"),
1674 (b"raac", "aac"),
1675 (b"racp", "aac"),
1676];
1677
1678pub struct RealMediaDemuxerCreator { }
1679
1680impl 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))
1683 }
1684 fn get_name(&self) -> &'static str { "realmedia" }
1685}
1686
1687pub struct RealAudioDemuxerCreator { }
1688
1689impl 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))
1692 }
1693 fn get_name(&self) -> &'static str { "realaudio" }
1694}
1695
1696pub struct RealIVRDemuxerCreator { }
1697
1698impl 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))
1701 }
1702 fn get_name(&self) -> &'static str { "real_ivr" }
1703}
1704
1705#[cfg(test)]
1706mod test {
1707 use super::*;
1708 use std::fs::File;
1709
1710 #[test]
1711 fn test_rm_demux() {
1712 let mut file =
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();
1730
1731 loop {
1732 let pktres = dmx.get_frame(&mut sm);
1733 if let Err(e) = pktres {
1734 if e == DemuxerError::EOF { break; }
1735 panic!("error");
1736 }
1737 let pkt = pktres.unwrap();
1738 println!("Got {}", pkt);
1739 }
1740//panic!("the end");
1741 }
1742 #[test]
1743 fn test_ra_demux() {
1744 let mut file =
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();
1753
1754 loop {
1755 let pktres = dmx.get_frame(&mut sm);
1756 if let Err(e) = pktres {
1757 if e == DemuxerError::EOF { break; }
1758 panic!("error");
1759 }
1760 let pkt = pktres.unwrap();
1761 println!("Got {}", pkt);
1762 }
1763 }
1764 #[test]
1765 fn test_ivr_demux() {
1766 let mut file =
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();
1775
1776 loop {
1777 let pktres = dmx.get_frame(&mut sm);
1778 if let Err(e) = pktres {
1779 if e == DemuxerError::EOF { break; }
1780 panic!("error");
1781 }
1782 let pkt = pktres.unwrap();
1783 println!("Got {}", pkt);
1784 }
1785 }
1786}