]> git.nihav.org Git - nihav.git/blob - nihav-commonfmt/src/demuxers/avi.rs
msvideo1enc: fix inversed flags in quantisation
[nihav.git] / nihav-commonfmt / src / demuxers / avi.rs
1 use nihav_core::demuxers::*;
2 use nihav_registry::register;
3 use nihav_core::demuxers::DemuxerError::*;
4 use std::str::FromStr;
5
6 macro_rules! mktag {
7 ($a:expr, $b:expr, $c:expr, $d:expr) => ({
8 (($a as u32) << 24) | (($b as u32) << 16) | (($c as u32) << 8) | ($d as u32)
9 });
10 ($arr:expr) => ({
11 (($arr[0] as u32) << 24) | (($arr[1] as u32) << 16) | (($arr[2] as u32) << 8) | ($arr[3] as u32)
12 });
13 }
14
15 struct StreamState {
16 strm_no: u8,
17 got_strf: bool,
18 strm_type: Option<StreamType>,
19 }
20
21 impl StreamState {
22 fn new() -> Self {
23 StreamState { strm_no: 0, got_strf: true, strm_type: None }
24 }
25 fn reset(&mut self) {
26 self.strm_type = None;
27 self.got_strf = true;
28 self.strm_no += 1;
29 }
30 fn valid_state(&self) -> bool {
31 match self.strm_type {
32 None => self.got_strf,
33 _ => false,
34 }
35 }
36 }
37
38 struct PalInfo {
39 pal: Arc<[u8; 1024]>,
40 changed: bool,
41 stream_no: usize,
42 }
43
44 #[derive(Clone,Copy,Default)]
45 struct RIFFSegment {
46 pos: u64,
47 size: usize,
48 movi_pos: u64,
49 movi_size: usize,
50 }
51
52 impl RIFFSegment {
53 fn contains(&self, pos: u64) -> bool {
54 pos >= self.movi_pos && pos < self.movi_pos + (self.movi_size as u64)
55 }
56 fn get_end(&self) -> u64 {
57 self.pos + (self.size as u64)
58 }
59 }
60
61 #[allow(dead_code)]
62 struct AVIDemuxer<'a> {
63 src: &'a mut ByteReader<'a>,
64 cur_frame: Vec<u64>,
65 num_streams: u8,
66 size: usize,
67 movi_size: usize,
68 movi_pos: u64,
69 movi_orig: usize,
70 sstate: StreamState,
71 tb_num: u32,
72 tb_den: u32,
73 strm_duration: u32,
74 key_offs: Vec<u64>,
75 pal: Vec<PalInfo>,
76 odml: bool,
77 odml_idx: Vec<u64>,
78 odml_riff: Vec<RIFFSegment>,
79 }
80
81 #[derive(Debug,Clone,Copy,PartialEq)]
82 enum RIFFTag {
83 Chunk(u32),
84 List(u32,u32),
85 }
86
87 struct RIFFParser {
88 tag: RIFFTag,
89 parse: fn(&mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize>,
90 }
91
92 impl<'a> DemuxCore<'a> for AVIDemuxer<'a> {
93 fn open(&mut self, strmgr: &mut StreamManager, seek_index: &mut SeekIndex) -> DemuxerResult<()> {
94 self.read_header(strmgr, seek_index)?;
95 Ok(())
96 }
97
98 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket> {
99 if self.movi_size == 0 {
100 if !self.odml {
101 return Err(EOF);
102 }
103 self.try_next_odml_chunk()?;
104 }
105 let mut tag: [u8; 4] = [0; 4];
106 loop {
107 if (self.src.tell() & 1) == 1 {
108 self.src.read_skip(1)?;
109 self.movi_size -= 1;
110 if self.movi_size == 0 {
111 if !self.odml {
112 return Err(EOF);
113 }
114 self.try_next_odml_chunk()?;
115 }
116 }
117 let is_keyframe = self.key_offs.binary_search(&self.src.tell()).is_ok();
118 self.src.read_buf(&mut tag)?;
119 let size = self.src.read_u32le()? as usize;
120 if mktag!(tag) == mktag!(b"JUNK") {
121 self.movi_size -= size + 8;
122 self.src.read_skip(size)?;
123 if self.movi_size == 0 {
124 if !self.odml {
125 return Err(EOF);
126 }
127 self.try_next_odml_chunk()?;
128 }
129 continue;
130 }
131 if mktag!(tag) == mktag!(b"LIST") {
132 self.movi_size -= 12;
133 self.src.read_skip(4)?;
134 if self.movi_size == 0 {
135 if !self.odml {
136 return Err(EOF);
137 }
138 self.try_next_odml_chunk()?;
139 }
140 continue;
141 }
142 if (tag[0] == b'i' && tag[1] == b'x') || (&tag == b"idx1") {
143 let idx_pos = self.src.tell() - 8;
144 if !self.odml {
145 return Err(EOF);
146 }
147 self.src.read_skip(size)?;
148 if idx_pos > self.movi_pos {
149 self.try_next_odml_chunk()?;
150 } else {
151 self.movi_pos = self.src.tell();
152 }
153 continue;
154 }
155 if tag[0] < b'0' || tag[0] > b'9' || tag[1] < b'0' || tag[1] > b'9' {
156 return Err(InvalidData);
157 }
158 let stream_no = (tag[0] - b'0') * 10 + (tag[1] - b'0');
159 if tag[2] == b'p' && tag[3] == b'c' {
160 self.parse_palette_change(stream_no as usize, size)?;
161 self.movi_size -= size;
162 if self.movi_size == 0 {
163 if !self.odml {
164 return Err(EOF);
165 }
166 self.try_next_odml_chunk()?;
167 }
168 continue;
169 }
170 let stream = strmgr.get_stream(stream_no as usize);
171 if stream.is_none() {
172 self.src.read_skip(size)?;
173 self.movi_size -= size + 8;
174 continue;
175 }
176 let stream = stream.unwrap();
177 if size == 0 {
178 self.movi_size -= 8;
179 if self.movi_size == 0 {
180 if !self.odml {
181 return Err(EOF);
182 }
183 self.try_next_odml_chunk()?;
184 }
185 continue;
186 }
187 let (tb_num, _) = stream.get_timebase();
188 let mut ts = stream.make_ts(Some(self.cur_frame[stream_no as usize]), None, None);
189 if stream.get_media_type() == StreamType::Audio && tb_num == 1 && stream.get_info().get_name() == "pcm" {
190 ts.pts = None;
191 }
192 let mut pkt = self.src.read_packet(stream, ts, is_keyframe, size)?;
193 for pe in self.pal.iter_mut() {
194 if pe.stream_no == (stream_no as usize) {
195 pkt.add_side_data(NASideData::Palette(pe.changed, pe.pal.clone()));
196 pe.changed = false;
197 break;
198 }
199 }
200 self.cur_frame[stream_no as usize] += 1;
201 self.movi_size -= size + 8;
202
203 return Ok(pkt);
204 }
205 }
206
207 fn seek(&mut self, time: NATimePoint, seek_index: &SeekIndex) -> DemuxerResult<()> {
208 let ret = seek_index.find_pos(time);
209 if ret.is_none() {
210 return Err(DemuxerError::SeekError);
211 }
212 let seek_info = ret.unwrap();
213
214 if self.odml && ((seek_info.pos < self.movi_pos) || (seek_info.pos > self.movi_pos + (self.movi_orig as u64))) {
215 let mut found = false;
216 for riff_seg in self.odml_riff.iter() {
217 if riff_seg.contains(seek_info.pos) {
218 found = true;
219 self.movi_pos = riff_seg.movi_pos;
220 self.movi_orig = riff_seg.movi_size;
221 self.movi_size = riff_seg.movi_size;
222 break;
223 }
224 }
225 if !found {
226 let riff_seg = self.odml_riff.last().unwrap();
227 self.src.seek(SeekFrom::Start(riff_seg.get_end()))?;
228 loop {
229 let ret = self.try_next_odml_chunk();
230 if ret.is_err() {
231 return Err(DemuxerError::SeekError);
232 }
233 let riff_seg = self.odml_riff.last().unwrap();
234 if riff_seg.contains(seek_info.pos) {
235 self.movi_pos = riff_seg.movi_pos;
236 self.movi_orig = riff_seg.movi_size;
237 self.movi_size = riff_seg.movi_size;
238 break;
239 }
240 self.src.seek(SeekFrom::Start(riff_seg.get_end()))?;
241 }
242 }
243 }
244 if seek_info.pos < self.movi_pos { return Err(DemuxerError::SeekError); }
245 let skip_size = (seek_info.pos - self.movi_pos) as usize;
246 if skip_size > self.movi_orig { return Err(DemuxerError::SeekError); }
247 self.movi_size = self.movi_orig - skip_size;
248
249 self.cur_frame[seek_info.str_id as usize] = seek_info.pts;
250 self.src.seek(SeekFrom::Start(seek_info.pos))?;
251
252 Ok(())
253 }
254 fn get_duration(&self) -> u64 { 0 }
255 }
256
257 impl<'a> NAOptionHandler for AVIDemuxer<'a> {
258 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
259 fn set_options(&mut self, _options: &[NAOption]) { }
260 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
261 }
262
263 impl<'a> AVIDemuxer<'a> {
264 fn new(io: &'a mut ByteReader<'a>) -> Self {
265 AVIDemuxer {
266 cur_frame: Vec::new(),
267 num_streams: 0,
268 src: io,
269 size: 0,
270 movi_size: 0,
271 movi_pos: 0,
272 movi_orig: 0,
273 sstate: StreamState::new(),
274 tb_num: 0,
275 tb_den: 0,
276 strm_duration: 0,
277 key_offs: Vec::new(),
278 pal: Vec::new(),
279 odml: false,
280 odml_idx: Vec::new(),
281 odml_riff: Vec::with_capacity(1),
282 }
283 }
284
285 fn parse_chunk(&mut self, strmgr: &mut StreamManager, end_tag: RIFFTag, csize: usize, depth: u16) -> DemuxerResult<(usize, bool)> {
286 if csize < 8 { return Err(InvalidData); }
287 if depth > 42 { return Err(InvalidData); }
288
289 let tag = self.src.read_u32be()?;
290 let size = self.src.read_u32le()? as usize;
291 if size > csize { return Err(InvalidData); }
292 if RIFFTag::Chunk(tag) == end_tag {
293 return Ok((size, true));
294 }
295 let is_list = is_list_tag(tag);
296 let ltag = if is_list { self.src.read_u32be()? } else { 0 };
297 if RIFFTag::List(tag, ltag) == end_tag {
298 return Ok((size, true));
299 }
300
301 for chunk in CHUNKS.iter() {
302 if RIFFTag::Chunk(tag) == chunk.tag {
303 let psize = (chunk.parse)(self, strmgr, size)?;
304 if psize != size { return Err(InvalidData); }
305 if (psize & 1) == 1 { self.src.read_skip(1)?; }
306 return Ok((size + 8, false));
307 }
308 if RIFFTag::List(tag, ltag) == chunk.tag {
309 let mut rest_size = size - 4;
310 let psize = (chunk.parse)(self, strmgr, rest_size)?;
311 if psize > rest_size { return Err(InvalidData); }
312 rest_size -= psize;
313 while rest_size > 0 {
314 let (psize, _) = self.parse_chunk(strmgr, end_tag, rest_size, depth+1)?;
315 if psize > rest_size { return Err(InvalidData); }
316 rest_size -= psize;
317 if ((psize & 1) == 1) && (rest_size > 0) {
318 rest_size -= 1;
319 }
320 }
321
322 return Ok((size + 8, false));
323 }
324 }
325 if !is_list {
326 self.src.read_skip(size)?;
327 } else {
328 if size < 4 { return Err(InvalidData); }
329 self.src.read_skip(size - 4)?;
330 }
331 if (size & 1) == 1 { self.src.read_skip(1)?; }
332 Ok((size + 8, false))
333 }
334
335 fn read_header(&mut self, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex) -> DemuxerResult<()> {
336 let riff_tag = self.src.read_u32be()?;
337 let size = self.src.read_u32le()? as usize;
338 self.odml_riff.push(RIFFSegment { pos: self.src.tell() - 8, size: size + 8, movi_pos: 0, movi_size: 0});
339 let avi_tag = self.src.read_u32be()?;
340 let mut matches = false;
341 for rt in RIFF_TAGS.iter() {
342 if rt[0] == riff_tag && rt[1] == avi_tag {
343 matches = true;
344 break;
345 }
346 }
347 if !matches {
348 return Err(InvalidData);
349 }
350 self.size = size;
351 let mut rest_size = size;
352 loop {
353 let (csz, end) = self.parse_chunk(strmgr, RIFFTag::List(mktag!(b"LIST"), mktag!(b"movi")), rest_size,0)?;
354 if end {
355 self.movi_size = csz - 4;
356 self.movi_orig = self.movi_size;
357 self.movi_pos = self.src.tell();
358
359 self.odml_riff[0].movi_pos = self.movi_pos;
360 self.odml_riff[0].movi_size = self.movi_size;
361 break;
362 }
363 rest_size -= csz;
364 }
365 if !seek_idx.skip_index {
366 if !self.odml {
367 self.src.read_skip(self.movi_size)?;
368 while rest_size > 0 {
369 let ret = self.parse_chunk(strmgr, RIFFTag::Chunk(mktag!(b"idx1")), rest_size,0);
370 if ret.is_err() { break; }
371 let (csz, end) = ret.unwrap();
372 if end {
373 let _res = parse_idx1(self.src, strmgr, seek_idx, csz, self.movi_pos, &mut self.key_offs);
374 break;
375 }
376 rest_size -= csz;
377 }
378 } else {
379 let mut start = 0;
380 let mut last_strm_no = 255;
381 for &offset in self.odml_idx.iter() {
382 if self.src.seek(SeekFrom::Start(offset)).is_err() {
383 break;
384 }
385 let ret = self.src.read_tag();
386 if ret.is_err() { break; }
387 let tag = ret.unwrap();
388 let ret = self.src.read_u32le();
389 if ret.is_err() { break; }
390 let size = ret.unwrap() as usize;
391 if &tag[..2] != b"ix" || tag[2] < b'0' || tag[2] > b'9' || tag[3] < b'0' || tag[3] > b'9'{
392 break;
393 }
394 let stream_no = ((tag[2] - b'0') * 10 + (tag[3] - b'0')) as usize;
395
396 if last_strm_no != stream_no {
397 start = 0;
398 last_strm_no = stream_no;
399 }
400 let ret = parse_odml_ix(self.src, strmgr, seek_idx, stream_no, size, start);
401 if let Ok(new_start) = ret {
402 start = new_start;
403 } else {
404 break;
405 }
406 }
407 }
408 }
409 if self.movi_pos != 0 {
410 self.src.seek(SeekFrom::Start(self.movi_pos))?;
411 } else {
412 return Err(InvalidData);
413 }
414 if !self.sstate.valid_state() || self.sstate.strm_no != self.num_streams {
415 return Err(InvalidData);
416 }
417 Ok(())
418 }
419
420 fn read_extradata(&mut self, size: usize) -> DemuxerResult<Option<Vec<u8>>> {
421 if size == 0 { return Ok(None); }
422 let mut edvec: Vec<u8> = vec![0; size];
423 self.src.read_buf(&mut edvec)?;
424 Ok(Some(edvec))
425 }
426
427 fn parse_palette_change(&mut self, stream_no: usize, size: usize) -> DemuxerResult<()> {
428 for pe in self.pal.iter_mut() {
429 if pe.stream_no == stream_no {
430 let start_clr = self.src.read_byte()? as usize;
431 let len = self.src.read_byte()? as usize;
432 let _flags = self.src.read_u16le()?;
433 validate!(start_clr + len <= 256);
434 validate!(len * 4 + 4 == size);
435 let mut newpal = *pe.pal;
436 for i in start_clr..(start_clr + len) {
437 newpal[i * 4] = self.src.read_byte()?;
438 newpal[i * 4 + 1] = self.src.read_byte()?;
439 newpal[i * 4 + 2] = self.src.read_byte()?;
440 newpal[i * 4 + 3] = 0;
441 self.src.read_byte()?; // flags
442 }
443 pe.pal = Arc::new(newpal);
444 pe.changed = true;
445 return Ok(());
446 }
447 }
448 self.src.read_skip(size)?;
449 Ok(())
450 }
451 fn try_next_odml_chunk(&mut self) -> DemuxerResult<()> {
452 let last_seg = self.odml_riff.last().unwrap();
453 if self.src.tell() < last_seg.get_end() {
454 for riff_seg in self.odml_riff.iter() {
455 if riff_seg.pos >= self.src.tell() {
456 self.src.seek(SeekFrom::Start(riff_seg.movi_pos))?;
457 self.movi_pos = riff_seg.movi_pos;
458 self.movi_size = riff_seg.movi_size;
459 return Ok(());
460 }
461 }
462 }
463 self.src.seek(SeekFrom::Start(last_seg.get_end()))?;
464
465 let riff_pos = self.src.tell();
466 let ret = self.src.read_tag();
467 if let Ok([b'R', b'I', b'F', b'F']) = ret {
468 } else {
469 return Err(DemuxerError::EOF);
470 }
471 let riff_size = self.src.read_u32le()? as usize;
472 let tag = self.src.read_tag()?;
473 validate!(&tag == b"AVIX");
474 let tag = self.src.read_tag()?;
475 validate!(&tag == b"LIST");
476 let list_size = self.src.read_u32le()? as usize;
477 validate!(list_size >= 4);
478 let tag = self.src.read_tag()?;
479 validate!(&tag == b"movi");
480 self.odml_riff.push(RIFFSegment{ pos: riff_pos, size: riff_size + 8, movi_pos: riff_pos + 24, movi_size: list_size - 4});
481 self.movi_pos = riff_pos + 24;
482 self.movi_size = list_size - 4;
483 self.movi_orig = self.movi_size;
484
485 Ok(())
486 }
487 }
488
489 const RIFF_TAGS: &[[u32; 2]] = &[
490 [ mktag!(b"RIFF"), mktag!(b"AVI ") ],
491 [ mktag!(b"RIFF"), mktag!(b"AVIX") ],
492 [ mktag!(b"ON2 "), mktag!(b"ON2f") ],
493 ];
494
495 const CHUNKS: &[RIFFParser] = &[
496 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"hdrl")), parse: parse_hdrl },
497 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"strl")), parse: parse_strl },
498 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"avih")), parse: parse_avih },
499 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"ON2h")), parse: parse_avih },
500 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"strf")), parse: parse_strf },
501 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"strh")), parse: parse_strh },
502 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"indx")), parse: parse_indx },
503 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"JUNK")), parse: parse_junk },
504 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"odml")), parse: parse_odml },
505 ];
506
507 fn is_list_tag(tag: u32) -> bool {
508 for chunk in CHUNKS.iter() {
509 if let RIFFTag::List(ltag, _) = chunk.tag {
510 if tag == ltag {
511 return true;
512 }
513 }
514 }
515 false
516 }
517
518 #[allow(unused_variables)]
519 fn parse_hdrl(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
520 Ok(0)
521 }
522
523 #[allow(unused_variables)]
524 fn parse_strl(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
525 Ok(0)
526 }
527
528 fn parse_odml(dmx: &mut AVIDemuxer, _strmgr: &mut StreamManager, _size: usize) -> DemuxerResult<usize> {
529 dmx.odml = true;
530 Ok(0)
531 }
532
533 #[allow(unused_variables)]
534 fn parse_strh(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
535 if size < 0x38 { return Err(InvalidData); }
536 let tag = dmx.src.read_u32be()?; //stream type
537 let fcc = dmx.src.read_u32be()?; //handler(fourcc)
538 dmx.src.read_u32le()?; //flags
539 dmx.src.read_skip(2)?; //priority
540 dmx.src.read_skip(2)?; //language
541 dmx.src.read_skip(4)?; //initial frames
542 dmx.tb_num = dmx.src.read_u32le()?; //scale
543 dmx.tb_den = dmx.src.read_u32le()?; //rate
544 dmx.src.read_skip(4)?; //start
545 dmx.strm_duration = dmx.src.read_u32le()?;
546 dmx.src.read_skip(4)?; //buf size
547 dmx.src.read_skip(4)?; //quality
548 dmx.src.read_skip(4)?; //sample size
549 let a = dmx.src.read_u16le()?;
550 let b = dmx.src.read_u16le()?;
551 let c = dmx.src.read_u16le()?;
552 let d = dmx.src.read_u16le()?;
553
554 dmx.src.read_skip(size - 0x38)?;
555
556 if !dmx.sstate.valid_state() || dmx.sstate.strm_no >= dmx.num_streams {
557 return Err(InvalidData);
558 }
559 if tag == mktag!(b"vids") {
560 dmx.sstate.strm_type = Some(StreamType::Video);
561 } else if tag == mktag!(b"auds") {
562 dmx.sstate.strm_type = Some(StreamType::Audio);
563 } else {
564 dmx.sstate.strm_type = Some(StreamType::Data);
565 }
566 dmx.sstate.got_strf = false;
567
568 Ok(size)
569 }
570
571 fn parse_strf(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
572 if dmx.sstate.strm_type.is_none() { return Err(InvalidData); }
573 match dmx.sstate.strm_type.unwrap() {
574 StreamType::Video => parse_strf_vids(dmx, strmgr, size),
575 StreamType::Audio => parse_strf_auds(dmx, strmgr, size),
576 _ => parse_strf_xxxx(dmx, strmgr, size),
577 }
578 }
579
580 #[allow(unused_variables)]
581 fn parse_strf_vids(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
582 if size < 40 { return Err(InvalidData); }
583 let bi_size = dmx.src.read_u32le()?;
584 if (bi_size as usize) < 40 { return Err(InvalidData); }
585 let width = dmx.src.read_u32le()?;
586 let height = dmx.src.read_u32le()? as i32;
587 let planes = dmx.src.read_u16le()?;
588 let bitcount = dmx.src.read_u16le()?;
589 let mut compression: [u8; 4] = [0; 4];
590 dmx.src.read_buf(&mut compression)?;
591 let img_size = dmx.src.read_u32le()?;
592 let xdpi = dmx.src.read_u32le()?;
593 let ydpi = dmx.src.read_u32le()?;
594 let colors = dmx.src.read_u32le()?;
595 validate!(colors <= 256);
596 let imp_colors = dmx.src.read_u32le()?;
597
598 let flip = height < 0;
599 let format = if bitcount > 8 { RGB24_FORMAT } else { PAL8_FORMAT };
600 let mut vhdr = NAVideoInfo::new(width as usize, if flip { -height as usize } else { height as usize}, flip, format);
601 vhdr.bits = (planes as u8) * (bitcount as u8);
602 let cname = if find_raw_rgb_fmt(&compression, planes, bitcount, flip, &mut vhdr) {
603 "rawvideo-ms"
604 } else if find_raw_yuv_fmt(&compression, &mut vhdr) {
605 "rawvideo"
606 } else {
607 match register::find_codec_from_avi_fourcc(&compression) {
608 None => "unknown",
609 Some(name) => name,
610 }
611 };
612 let vci = NACodecTypeInfo::Video(vhdr);
613 let edata = dmx.read_extradata(size - 40)?;
614 if colors > 0 {
615 if let Some(ref buf) = edata {
616 let mut pal = [0u8; 1024];
617 for (dpal, spal) in pal.chunks_mut(4).take(colors as usize).zip(buf.chunks(4)) {
618 dpal[0] = spal[2];
619 dpal[1] = spal[1];
620 dpal[2] = spal[0];
621 dpal[3] = 0;
622 }
623 let pal = PalInfo { pal: Arc::new(pal), changed: true, stream_no: strmgr.get_num_streams() };
624 dmx.pal.push(pal);
625 }
626 }
627 let vinfo = NACodecInfo::new(cname, vci, edata);
628 let res = strmgr.add_stream(NAStream::new(StreamType::Video, u32::from(dmx.sstate.strm_no), vinfo, dmx.tb_num, dmx.tb_den, u64::from(dmx.strm_duration)));
629 if res.is_none() { return Err(MemoryError); }
630 dmx.sstate.reset();
631 Ok(size)
632 }
633
634 fn find_raw_rgb_fmt(compr: &[u8; 4], planes: u16, bitcount: u16, flip: bool, vhdr: &mut NAVideoInfo) -> bool {
635 match compr {
636 &[0, 0, 0, 0] | b"DIB " => {
637 if planes != 1 {
638 return false;
639 }
640 let fmt_name = match bitcount {
641 8 => "pal8",
642 16 => "bgr555",
643 24 => "bgr24",
644 32 => "bgra24",
645 _ => return false,
646 };
647 if let Ok(fmt) = NAPixelFormaton::from_str(fmt_name) {
648 vhdr.format = fmt;
649 vhdr.flipped = !flip;
650 true
651 } else {
652 false
653 }
654 },
655 _ => false,
656 }
657 }
658
659 fn find_raw_yuv_fmt(compr: &[u8; 4], vhdr: &mut NAVideoInfo) -> bool {
660 let (fmt_name, swapuv) = match compr {
661 b"UYVY" | b"UYNY" | b"UYNV" | b"2vuy" => ("uyvy", false),
662 b"I420" | b"IYUV" => ("yuv420p", false),
663 b"YV12" => ("yuv420p", true),
664 b"YVU9" => ("yuv410p", true),
665 _ => return false,
666 };
667 if let Ok(fmt) = NAPixelFormaton::from_str(fmt_name) {
668 vhdr.format = fmt;
669 if swapuv {
670 vhdr.format.comp_info.swap(1, 2);
671 }
672 true
673 } else {
674 false
675 }
676 }
677
678 #[allow(unused_variables)]
679 fn parse_strf_auds(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
680 if size < 16 { return Err(InvalidData); }
681 let w_format_tag = dmx.src.read_u16le()?;
682 let channels = dmx.src.read_u16le()?;
683 let samplespersec = dmx.src.read_u32le()?;
684 let avgbytespersec = dmx.src.read_u32le()?;
685 let block_align = dmx.src.read_u16le()?;
686 let bits_per_sample = dmx.src.read_u16le()?;
687
688 let signed = bits_per_sample > 8;
689 let soniton = NASoniton::new(bits_per_sample as u8, if signed { SONITON_FLAG_SIGNED } else { 0 });
690 let ahdr = NAAudioInfo::new(samplespersec, channels as u8, soniton, block_align as usize);
691 let edata = if size > 16 {
692 let edata_size = dmx.src.read_u16le()? as usize;
693 validate!(edata_size + 18 <= size);
694 dmx.read_extradata(size - 18)?
695 } else {
696 None
697 };
698 let cname = match register::find_codec_from_wav_twocc(w_format_tag) {
699 None => "unknown",
700 Some(name) => name,
701 };
702 let ainfo = NACodecInfo::new(cname, NACodecTypeInfo::Audio(ahdr), edata);
703 let res = strmgr.add_stream(NAStream::new(StreamType::Audio, u32::from(dmx.sstate.strm_no), ainfo, dmx.tb_num, dmx.tb_den, u64::from(dmx.strm_duration)));
704 if res.is_none() { return Err(MemoryError); }
705 dmx.sstate.reset();
706 Ok(size)
707 }
708
709 fn parse_strf_xxxx(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
710 let edata = dmx.read_extradata(size)?;
711 let info = NACodecInfo::new("unknown", NACodecTypeInfo::None, edata);
712 let res = strmgr.add_stream(NAStream::new(StreamType::Data, u32::from(dmx.sstate.strm_no), info, dmx.tb_num, dmx.tb_den, u64::from(dmx.strm_duration)));
713 if res.is_none() { return Err(MemoryError); }
714 dmx.sstate.reset();
715 Ok(size)
716 }
717
718 #[allow(unused_variables)]
719 fn parse_avih(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
720 if size < 0x38 { return Err(InvalidData); }
721 let timebase = dmx.src.read_u32le()?; //microsec per frame
722 dmx.src.read_skip(4)?; //max frame size
723 dmx.src.read_skip(4)?; //padding
724 dmx.src.read_u32le()?; //flags
725 let frames = dmx.src.read_u32le()?; //frames
726 dmx.src.read_skip(4)?; //initial frames
727 let streams = dmx.src.read_u32le()?; //streams
728 if streams > 100 { return Err(InvalidData); }
729 dmx.num_streams = streams as u8;
730
731 dmx.src.read_skip(4)?; //buf size
732 let width = dmx.src.read_u32le()?; //width
733 let height = dmx.src.read_u32le()? as i32; //height
734 dmx.src.read_skip(16)?; //reserved
735
736 dmx.cur_frame.resize(streams as usize, 0);
737 dmx.src.read_skip(size - 0x38)?;
738 Ok(size)
739 }
740
741 fn parse_indx(dmx: &mut AVIDemuxer, _strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
742 dmx.odml = true;
743 validate!(size >= 24);
744 let entry_size = dmx.src.read_u16le()? as usize;
745 if entry_size != 4 {
746 dmx.src.read_skip(size - 2)?;
747 return Ok(size);
748 }
749 let sub_type = dmx.src.read_byte()?;
750 let idx_type = dmx.src.read_byte()?;
751 validate!(sub_type == 0 && idx_type == 0);
752 let entries = dmx.src.read_u32le()? as usize;
753 validate!(size >= 24 + entries * 4 * entry_size);
754 dmx.src.read_tag()?; //chunk id
755 dmx.src.read_skip(12)?; // reserved
756 for _ in 0..entries {
757 let offset = dmx.src.read_u64le()?;
758 let _idx_len = dmx.src.read_u32le()?;
759 let _nframes = dmx.src.read_u32le()?;
760 dmx.odml_idx.push(offset);
761 }
762 dmx.src.read_skip(size - 24 - entries * 4 * entry_size)?;
763 Ok(size)
764 }
765
766 #[allow(unused_variables)]
767 fn parse_junk(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
768 dmx.src.read_skip(size)?;
769 Ok(size)
770 }
771
772 #[allow(clippy::verbose_bit_mask)]
773 fn parse_idx1(src: &mut ByteReader, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex, size: usize, movi_pos: u64, key_offs: &mut Vec<u64>) -> DemuxerResult<usize> {
774 validate!((size & 15) == 0);
775 let mut tag = [0u8; 4];
776 let num_entries = size >> 4;
777 let mut counter = [0u64; 100];
778 let mut add_offset = 0;
779 let mut set_offset = false;
780 for _ in 0..num_entries {
781 src.read_buf(&mut tag)?;
782 let flags = src.read_u32le()?;
783 let mut offset = src.read_u32le()? as u64;
784 let _length = src.read_u32le()?;
785
786 if !set_offset && offset < movi_pos {
787 add_offset = movi_pos - offset;
788 }
789 set_offset = true;
790
791 offset += add_offset;
792
793 if tag[0] < b'0' || tag[0] > b'9' || tag[1] < b'0' || tag[1] > b'9' {
794 continue;
795 }
796 let stream_no = ((tag[0] - b'0') * 10 + (tag[1] - b'0')) as usize;
797
798 if (flags & 0x10) != 0 {
799 if let Some(stream) = strmgr.get_stream(stream_no) {
800 if stream.get_media_type() == StreamType::Video {
801 let (tb_num, tb_den) = stream.get_timebase();
802 let pts = counter[stream_no];
803 let time = NATimeInfo::ts_to_time(pts, 1000, tb_num, tb_den);
804 validate!(offset >= movi_pos);
805 seek_idx.add_entry(stream_no as u32, SeekEntry { time, pts, pos: offset });
806 }
807 key_offs.push(offset);
808 }
809 }
810 counter[stream_no] += 1;
811 }
812 key_offs.sort_unstable();
813 Ok(size)
814 }
815
816 fn parse_odml_ix(src: &mut ByteReader, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex, stream_no: usize, size: usize, start: u64) -> DemuxerResult<u64> {
817 validate!(size >= 24);
818 let entry_size = src.read_u16le()? as usize;
819 if entry_size != 2 {
820 return Err(DemuxerError::NotImplemented);
821 }
822 let sub_type = src.read_byte()?;
823 let idx_type = src.read_byte()?;
824 validate!(sub_type == 0 && idx_type == 1);
825 let entries = src.read_u32le()? as usize;
826 validate!(size >= 24 + entries * 4 * entry_size);
827 src.read_tag()?; //chunk id
828 let base_offset = src.read_u64le()?;
829 src.read_u32le()?; //reserved
830 if let Some(stream) = strmgr.get_stream(stream_no) {
831 if stream.get_media_type() == StreamType::Video {
832 let (tb_num, tb_den) = stream.get_timebase();
833
834 for i in 0..entries {
835 let offset = src.read_u32le()?;
836 validate!(offset >= 8);
837 let _size = src.read_u32le()?;
838
839 let pts = start + (i as u64);
840 let time = NATimeInfo::ts_to_time(pts, 1000, tb_num, tb_den);
841 seek_idx.add_entry(stream_no as u32, SeekEntry { time, pts, pos: base_offset + u64::from(offset - 8) });
842 }
843
844 Ok(start + (entries as u64))
845 } else {
846 Ok(0)
847 }
848 } else {
849 Ok(0)
850 }
851 }
852
853 pub struct AVIDemuxerCreator { }
854
855 impl DemuxerCreator for AVIDemuxerCreator {
856 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a> {
857 Box::new(AVIDemuxer::new(br))
858 }
859 fn get_name(&self) -> &'static str { "avi" }
860 }
861
862 #[cfg(test)]
863 mod test {
864 use super::*;
865 use std::fs::File;
866
867 #[test]
868 fn test_avi_demux() {
869 //test sample: https://samples.mplayerhq.hu/V-codecs/RT21/320x240/laser05.avi
870 let mut file = File::open("assets/Indeo/laser05.avi").unwrap();
871 let mut fr = FileReader::new_read(&mut file);
872 let mut br = ByteReader::new(&mut fr);
873 let mut dmx = AVIDemuxer::new(&mut br);
874 let mut sm = StreamManager::new();
875 let mut si = SeekIndex::new();
876 dmx.open(&mut sm, &mut si).unwrap();
877
878 loop {
879 let pktres = dmx.get_frame(&mut sm);
880 if let Err(e) = pktres {
881 if e == DemuxerError::EOF { break; }
882 panic!("error");
883 }
884 let pkt = pktres.unwrap();
885 println!("Got {}", pkt);
886 }
887 }
888 }