]> git.nihav.org Git - nihav.git/blob - nihav-commonfmt/src/demuxers/avi.rs
avi: fix handling of palette change chunk with 256 colours
[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 len = if len == 0 { 256 } else { len };
433 let _flags = self.src.read_u16le()?;
434 validate!(start_clr + len <= 256);
435 validate!(len * 4 + 4 == size);
436 let mut newpal = *pe.pal;
437 for i in start_clr..(start_clr + len) {
438 newpal[i * 4] = self.src.read_byte()?;
439 newpal[i * 4 + 1] = self.src.read_byte()?;
440 newpal[i * 4 + 2] = self.src.read_byte()?;
441 newpal[i * 4 + 3] = 0;
442 self.src.read_byte()?; // flags
443 }
444 pe.pal = Arc::new(newpal);
445 pe.changed = true;
446 return Ok(());
447 }
448 }
449 self.src.read_skip(size)?;
450 Ok(())
451 }
452 fn try_next_odml_chunk(&mut self) -> DemuxerResult<()> {
453 let last_seg = self.odml_riff.last().unwrap();
454 if self.src.tell() < last_seg.get_end() {
455 for riff_seg in self.odml_riff.iter() {
456 if riff_seg.pos >= self.src.tell() {
457 self.src.seek(SeekFrom::Start(riff_seg.movi_pos))?;
458 self.movi_pos = riff_seg.movi_pos;
459 self.movi_size = riff_seg.movi_size;
460 return Ok(());
461 }
462 }
463 }
464 self.src.seek(SeekFrom::Start(last_seg.get_end()))?;
465
466 let riff_pos = self.src.tell();
467 let ret = self.src.read_tag();
468 if let Ok([b'R', b'I', b'F', b'F']) = ret {
469 } else {
470 return Err(DemuxerError::EOF);
471 }
472 let riff_size = self.src.read_u32le()? as usize;
473 let tag = self.src.read_tag()?;
474 validate!(&tag == b"AVIX");
475 let tag = self.src.read_tag()?;
476 validate!(&tag == b"LIST");
477 let list_size = self.src.read_u32le()? as usize;
478 validate!(list_size >= 4);
479 let tag = self.src.read_tag()?;
480 validate!(&tag == b"movi");
481 self.odml_riff.push(RIFFSegment{ pos: riff_pos, size: riff_size + 8, movi_pos: riff_pos + 24, movi_size: list_size - 4});
482 self.movi_pos = riff_pos + 24;
483 self.movi_size = list_size - 4;
484 self.movi_orig = self.movi_size;
485
486 Ok(())
487 }
488 }
489
490 const RIFF_TAGS: &[[u32; 2]] = &[
491 [ mktag!(b"RIFF"), mktag!(b"AVI ") ],
492 [ mktag!(b"RIFF"), mktag!(b"AVIX") ],
493 [ mktag!(b"ON2 "), mktag!(b"ON2f") ],
494 ];
495
496 const CHUNKS: &[RIFFParser] = &[
497 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"hdrl")), parse: parse_hdrl },
498 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"strl")), parse: parse_strl },
499 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"avih")), parse: parse_avih },
500 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"ON2h")), parse: parse_avih },
501 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"strf")), parse: parse_strf },
502 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"strh")), parse: parse_strh },
503 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"indx")), parse: parse_indx },
504 RIFFParser { tag: RIFFTag::Chunk(mktag!(b"JUNK")), parse: parse_junk },
505 RIFFParser { tag: RIFFTag::List(mktag!(b"LIST"), mktag!(b"odml")), parse: parse_odml },
506 ];
507
508 fn is_list_tag(tag: u32) -> bool {
509 for chunk in CHUNKS.iter() {
510 if let RIFFTag::List(ltag, _) = chunk.tag {
511 if tag == ltag {
512 return true;
513 }
514 }
515 }
516 false
517 }
518
519 #[allow(unused_variables)]
520 fn parse_hdrl(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
521 Ok(0)
522 }
523
524 #[allow(unused_variables)]
525 fn parse_strl(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
526 Ok(0)
527 }
528
529 fn parse_odml(dmx: &mut AVIDemuxer, _strmgr: &mut StreamManager, _size: usize) -> DemuxerResult<usize> {
530 dmx.odml = true;
531 Ok(0)
532 }
533
534 #[allow(unused_variables)]
535 fn parse_strh(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
536 if size < 0x38 { return Err(InvalidData); }
537 let tag = dmx.src.read_u32be()?; //stream type
538 let fcc = dmx.src.read_u32be()?; //handler(fourcc)
539 dmx.src.read_u32le()?; //flags
540 dmx.src.read_skip(2)?; //priority
541 dmx.src.read_skip(2)?; //language
542 dmx.src.read_skip(4)?; //initial frames
543 dmx.tb_num = dmx.src.read_u32le()?; //scale
544 dmx.tb_den = dmx.src.read_u32le()?; //rate
545 dmx.src.read_skip(4)?; //start
546 dmx.strm_duration = dmx.src.read_u32le()?;
547 dmx.src.read_skip(4)?; //buf size
548 dmx.src.read_skip(4)?; //quality
549 dmx.src.read_skip(4)?; //sample size
550 let a = dmx.src.read_u16le()?;
551 let b = dmx.src.read_u16le()?;
552 let c = dmx.src.read_u16le()?;
553 let d = dmx.src.read_u16le()?;
554
555 dmx.src.read_skip(size - 0x38)?;
556
557 if !dmx.sstate.valid_state() || dmx.sstate.strm_no >= dmx.num_streams {
558 return Err(InvalidData);
559 }
560 if tag == mktag!(b"vids") {
561 dmx.sstate.strm_type = Some(StreamType::Video);
562 } else if tag == mktag!(b"auds") {
563 dmx.sstate.strm_type = Some(StreamType::Audio);
564 } else {
565 dmx.sstate.strm_type = Some(StreamType::Data);
566 }
567 dmx.sstate.got_strf = false;
568
569 Ok(size)
570 }
571
572 fn parse_strf(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
573 if dmx.sstate.strm_type.is_none() { return Err(InvalidData); }
574 match dmx.sstate.strm_type.unwrap() {
575 StreamType::Video => parse_strf_vids(dmx, strmgr, size),
576 StreamType::Audio => parse_strf_auds(dmx, strmgr, size),
577 _ => parse_strf_xxxx(dmx, strmgr, size),
578 }
579 }
580
581 #[allow(unused_variables)]
582 fn parse_strf_vids(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
583 if size < 40 { return Err(InvalidData); }
584 let bi_size = dmx.src.read_u32le()?;
585 if (bi_size as usize) < 40 { return Err(InvalidData); }
586 let width = dmx.src.read_u32le()?;
587 let height = dmx.src.read_u32le()? as i32;
588 let planes = dmx.src.read_u16le()?;
589 let bitcount = dmx.src.read_u16le()?;
590 let mut compression: [u8; 4] = [0; 4];
591 dmx.src.read_buf(&mut compression)?;
592 let img_size = dmx.src.read_u32le()?;
593 let xdpi = dmx.src.read_u32le()?;
594 let ydpi = dmx.src.read_u32le()?;
595 let colors = dmx.src.read_u32le()?;
596 validate!(colors <= 256);
597 let imp_colors = dmx.src.read_u32le()?;
598
599 let flip = height < 0;
600 let format = if bitcount > 8 { RGB24_FORMAT } else { PAL8_FORMAT };
601 let mut vhdr = NAVideoInfo::new(width as usize, if flip { -height as usize } else { height as usize}, flip, format);
602 vhdr.bits = (planes as u8) * (bitcount as u8);
603 let cname = if find_raw_rgb_fmt(&compression, planes, bitcount, flip, &mut vhdr) {
604 "rawvideo-ms"
605 } else if find_raw_yuv_fmt(&compression, &mut vhdr) {
606 "rawvideo"
607 } else {
608 match register::find_codec_from_avi_fourcc(&compression) {
609 None => "unknown",
610 Some(name) => name,
611 }
612 };
613 let vci = NACodecTypeInfo::Video(vhdr);
614 let edata = dmx.read_extradata(size - 40)?;
615 if colors > 0 {
616 if let Some(ref buf) = edata {
617 let mut pal = [0u8; 1024];
618 for (dpal, spal) in pal.chunks_mut(4).take(colors as usize).zip(buf.chunks(4)) {
619 dpal[0] = spal[2];
620 dpal[1] = spal[1];
621 dpal[2] = spal[0];
622 dpal[3] = 0;
623 }
624 let pal = PalInfo { pal: Arc::new(pal), changed: true, stream_no: strmgr.get_num_streams() };
625 dmx.pal.push(pal);
626 }
627 }
628 let vinfo = NACodecInfo::new(cname, vci, edata);
629 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)));
630 if res.is_none() { return Err(MemoryError); }
631 dmx.sstate.reset();
632 Ok(size)
633 }
634
635 fn find_raw_rgb_fmt(compr: &[u8; 4], planes: u16, bitcount: u16, flip: bool, vhdr: &mut NAVideoInfo) -> bool {
636 match compr {
637 &[0, 0, 0, 0] | b"DIB " => {
638 if planes != 1 {
639 return false;
640 }
641 let fmt_name = match bitcount {
642 8 => "pal8",
643 16 => "bgr555",
644 24 => "bgr24",
645 32 => "bgra24",
646 _ => return false,
647 };
648 if let Ok(fmt) = NAPixelFormaton::from_str(fmt_name) {
649 vhdr.format = fmt;
650 vhdr.flipped = !flip;
651 true
652 } else {
653 false
654 }
655 },
656 _ => false,
657 }
658 }
659
660 fn find_raw_yuv_fmt(compr: &[u8; 4], vhdr: &mut NAVideoInfo) -> bool {
661 let (fmt_name, swapuv) = match compr {
662 b"UYVY" | b"UYNY" | b"UYNV" | b"2vuy" => ("uyvy", false),
663 b"I420" | b"IYUV" => ("yuv420p", false),
664 b"YV12" => ("yuv420p", true),
665 b"YVU9" => ("yuv410p", true),
666 _ => return false,
667 };
668 if let Ok(fmt) = NAPixelFormaton::from_str(fmt_name) {
669 vhdr.format = fmt;
670 if swapuv {
671 vhdr.format.comp_info.swap(1, 2);
672 }
673 true
674 } else {
675 false
676 }
677 }
678
679 #[allow(unused_variables)]
680 fn parse_strf_auds(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
681 if size < 16 { return Err(InvalidData); }
682 let w_format_tag = dmx.src.read_u16le()?;
683 let channels = dmx.src.read_u16le()?;
684 let samplespersec = dmx.src.read_u32le()?;
685 let avgbytespersec = dmx.src.read_u32le()?;
686 let block_align = dmx.src.read_u16le()?;
687 let bits_per_sample = dmx.src.read_u16le()?;
688
689 let signed = bits_per_sample > 8;
690 let soniton = NASoniton::new(bits_per_sample as u8, if signed { SONITON_FLAG_SIGNED } else { 0 });
691 let ahdr = NAAudioInfo::new(samplespersec, channels as u8, soniton, block_align as usize);
692 let edata = if size > 16 {
693 let edata_size = dmx.src.read_u16le()? as usize;
694 validate!(edata_size + 18 <= size);
695 dmx.read_extradata(size - 18)?
696 } else {
697 None
698 };
699 let cname = match register::find_codec_from_wav_twocc(w_format_tag) {
700 None => "unknown",
701 Some(name) => name,
702 };
703 let ainfo = NACodecInfo::new(cname, NACodecTypeInfo::Audio(ahdr), edata);
704 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)));
705 if res.is_none() { return Err(MemoryError); }
706 dmx.sstate.reset();
707 Ok(size)
708 }
709
710 fn parse_strf_xxxx(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
711 let edata = dmx.read_extradata(size)?;
712 let info = NACodecInfo::new("unknown", NACodecTypeInfo::None, edata);
713 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)));
714 if res.is_none() { return Err(MemoryError); }
715 dmx.sstate.reset();
716 Ok(size)
717 }
718
719 #[allow(unused_variables)]
720 fn parse_avih(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
721 if size < 0x38 { return Err(InvalidData); }
722 let timebase = dmx.src.read_u32le()?; //microsec per frame
723 dmx.src.read_skip(4)?; //max frame size
724 dmx.src.read_skip(4)?; //padding
725 dmx.src.read_u32le()?; //flags
726 let frames = dmx.src.read_u32le()?; //frames
727 dmx.src.read_skip(4)?; //initial frames
728 let streams = dmx.src.read_u32le()?; //streams
729 if streams > 100 { return Err(InvalidData); }
730 dmx.num_streams = streams as u8;
731
732 dmx.src.read_skip(4)?; //buf size
733 let width = dmx.src.read_u32le()?; //width
734 let height = dmx.src.read_u32le()? as i32; //height
735 dmx.src.read_skip(16)?; //reserved
736
737 dmx.cur_frame.resize(streams as usize, 0);
738 dmx.src.read_skip(size - 0x38)?;
739 Ok(size)
740 }
741
742 fn parse_indx(dmx: &mut AVIDemuxer, _strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
743 dmx.odml = true;
744 validate!(size >= 24);
745 let entry_size = dmx.src.read_u16le()? as usize;
746 if entry_size != 4 {
747 dmx.src.read_skip(size - 2)?;
748 return Ok(size);
749 }
750 let sub_type = dmx.src.read_byte()?;
751 let idx_type = dmx.src.read_byte()?;
752 validate!(sub_type == 0 && idx_type == 0);
753 let entries = dmx.src.read_u32le()? as usize;
754 validate!(size >= 24 + entries * 4 * entry_size);
755 dmx.src.read_tag()?; //chunk id
756 dmx.src.read_skip(12)?; // reserved
757 for _ in 0..entries {
758 let offset = dmx.src.read_u64le()?;
759 let _idx_len = dmx.src.read_u32le()?;
760 let _nframes = dmx.src.read_u32le()?;
761 dmx.odml_idx.push(offset);
762 }
763 dmx.src.read_skip(size - 24 - entries * 4 * entry_size)?;
764 Ok(size)
765 }
766
767 #[allow(unused_variables)]
768 fn parse_junk(dmx: &mut AVIDemuxer, strmgr: &mut StreamManager, size: usize) -> DemuxerResult<usize> {
769 dmx.src.read_skip(size)?;
770 Ok(size)
771 }
772
773 #[allow(clippy::verbose_bit_mask)]
774 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> {
775 validate!((size & 15) == 0);
776 let mut tag = [0u8; 4];
777 let num_entries = size >> 4;
778 let mut counter = [0u64; 100];
779 let mut add_offset = 0;
780 let mut set_offset = false;
781 for _ in 0..num_entries {
782 src.read_buf(&mut tag)?;
783 let flags = src.read_u32le()?;
784 let mut offset = src.read_u32le()? as u64;
785 let _length = src.read_u32le()?;
786
787 if !set_offset && offset < movi_pos {
788 add_offset = movi_pos - offset;
789 }
790 set_offset = true;
791
792 offset += add_offset;
793
794 if tag[0] < b'0' || tag[0] > b'9' || tag[1] < b'0' || tag[1] > b'9' {
795 continue;
796 }
797 let stream_no = ((tag[0] - b'0') * 10 + (tag[1] - b'0')) as usize;
798
799 if (flags & 0x10) != 0 {
800 if let Some(stream) = strmgr.get_stream(stream_no) {
801 if stream.get_media_type() == StreamType::Video {
802 let (tb_num, tb_den) = stream.get_timebase();
803 let pts = counter[stream_no];
804 let time = NATimeInfo::ts_to_time(pts, 1000, tb_num, tb_den);
805 validate!(offset >= movi_pos);
806 seek_idx.add_entry(stream_no as u32, SeekEntry { time, pts, pos: offset });
807 }
808 key_offs.push(offset);
809 }
810 }
811 counter[stream_no] += 1;
812 }
813 key_offs.sort_unstable();
814 Ok(size)
815 }
816
817 fn parse_odml_ix(src: &mut ByteReader, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex, stream_no: usize, size: usize, start: u64) -> DemuxerResult<u64> {
818 validate!(size >= 24);
819 let entry_size = src.read_u16le()? as usize;
820 if entry_size != 2 {
821 return Err(DemuxerError::NotImplemented);
822 }
823 let sub_type = src.read_byte()?;
824 let idx_type = src.read_byte()?;
825 validate!(sub_type == 0 && idx_type == 1);
826 let entries = src.read_u32le()? as usize;
827 validate!(size >= 24 + entries * 4 * entry_size);
828 src.read_tag()?; //chunk id
829 let base_offset = src.read_u64le()?;
830 src.read_u32le()?; //reserved
831 if let Some(stream) = strmgr.get_stream(stream_no) {
832 if stream.get_media_type() == StreamType::Video {
833 let (tb_num, tb_den) = stream.get_timebase();
834
835 for i in 0..entries {
836 let offset = src.read_u32le()?;
837 validate!(offset >= 8);
838 let _size = src.read_u32le()?;
839
840 let pts = start + (i as u64);
841 let time = NATimeInfo::ts_to_time(pts, 1000, tb_num, tb_den);
842 seek_idx.add_entry(stream_no as u32, SeekEntry { time, pts, pos: base_offset + u64::from(offset - 8) });
843 }
844
845 Ok(start + (entries as u64))
846 } else {
847 Ok(0)
848 }
849 } else {
850 Ok(0)
851 }
852 }
853
854 pub struct AVIDemuxerCreator { }
855
856 impl DemuxerCreator for AVIDemuxerCreator {
857 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a> {
858 Box::new(AVIDemuxer::new(br))
859 }
860 fn get_name(&self) -> &'static str { "avi" }
861 }
862
863 #[cfg(test)]
864 mod test {
865 use super::*;
866 use std::fs::File;
867
868 #[test]
869 fn test_avi_demux() {
870 //test sample: https://samples.mplayerhq.hu/V-codecs/RT21/320x240/laser05.avi
871 let mut file = File::open("assets/Indeo/laser05.avi").unwrap();
872 let mut fr = FileReader::new_read(&mut file);
873 let mut br = ByteReader::new(&mut fr);
874 let mut dmx = AVIDemuxer::new(&mut br);
875 let mut sm = StreamManager::new();
876 let mut si = SeekIndex::new();
877 dmx.open(&mut sm, &mut si).unwrap();
878
879 loop {
880 let pktres = dmx.get_frame(&mut sm);
881 if let Err(e) = pktres {
882 if e == DemuxerError::EOF { break; }
883 panic!("error");
884 }
885 let pkt = pktres.unwrap();
886 println!("Got {}", pkt);
887 }
888 }
889 }