1 use nihav_core::frame::*;
2 use nihav_core::formats;
3 use nihav_core::formats::{NAChannelType, NAChannelMap};
4 use nihav_core::codecs::*;
5 use nihav_core::io::byteio::*;
7 struct GremlinVideoDecoder {
25 const PREAMBLE_SIZE: usize = 4096;
28 fn new() -> Self { Bits8 { queue: 0, fill: 0 } }
29 fn read_2bits(&mut self, br: &mut ByteReader) -> ByteIOResult<u8> {
31 self.queue = br.read_byte()?;
34 let res = self.queue >> 6;
42 fn new() -> Self { Bits32 { queue: 0, fill: 0 } }
43 fn fill(&mut self, br: &mut ByteReader) -> ByteIOResult<()> {
44 self.queue = br.read_u32le()?;
48 fn read_bits(&mut self, br: &mut ByteReader, nbits: u8) -> ByteIOResult<u32> {
49 let res = self.queue & ((1 << nbits) - 1);
53 self.queue |= u32::from(br.read_u16le()?) << self.fill;
60 impl GremlinVideoDecoder {
63 info: NACodecInfoRef::default(), pal: [0; 768], frame: Vec::new(),
64 scale_v: false, scale_h: false
68 fn lz_copy(&mut self, idx: usize, offset: isize, len: usize) -> DecoderResult<()> {
69 if idx + len > self.frame.len() { return Err(DecoderError::InvalidData); }
71 let c = self.frame[idx - 1];
72 for i in 0..len { self.frame[idx + i] = c; }
73 } else if offset < 0 {
74 let start = idx - (-offset as usize);
75 for i in 0..len { self.frame[idx + i] = self.frame[start + i]; }
77 if idx + (offset as usize) + len > self.frame.len() { return Err(DecoderError::InvalidData); }
78 let start = idx + (offset as usize);
79 for i in 0..len { self.frame[idx + i] = self.frame[start + i]; }
84 fn rescale(&mut self, w: usize, h: usize, scale_v: bool, scale_h: bool) {
85 if (self.scale_v == scale_v) && (self.scale_h == scale_h) { return; }
87 if self.scale_h && self.scale_v {
92 self.frame[PREAMBLE_SIZE + x + y * w] = self.frame[PREAMBLE_SIZE + x/2 + (y/2) * (w/2)];
95 } else if self.scale_h {
99 self.frame[PREAMBLE_SIZE + x + y * w] = self.frame[PREAMBLE_SIZE + x + (y/2) * w];
102 } else if self.scale_v {
107 self.frame[PREAMBLE_SIZE + x + y * w] = self.frame[PREAMBLE_SIZE + x/2 + y * (w/2)];
112 if scale_h && scale_v {
115 self.frame[PREAMBLE_SIZE + x + y * (w/2)] = self.frame[PREAMBLE_SIZE + x*2 + y*2 * w];
121 self.frame[PREAMBLE_SIZE + x + y * w] = self.frame[PREAMBLE_SIZE + x + y*2 * w];
127 self.frame[PREAMBLE_SIZE + x + y * w] = self.frame[PREAMBLE_SIZE + x*2 + y * w];
132 self.scale_v = scale_v;
133 self.scale_h = scale_h;
136 fn output_frame(&mut self, bufinfo: &mut NABufferType, w: usize, h: usize) {
137 let bufo = bufinfo.get_vbuf();
138 let mut buf = bufo.unwrap();
139 let paloff = buf.get_offset(1);
140 let stride = buf.get_stride(0);
141 let data = buf.get_data_mut().unwrap();
142 let dst = data.as_mut_slice();
143 let mut sidx = PREAMBLE_SIZE;
146 dst[paloff..][..768].copy_from_slice(&self.pal);
147 if !self.scale_v && !self.scale_h {
149 dst[didx..][..w].copy_from_slice(&self.frame[sidx..][..w]);
156 dst[didx..][..w].copy_from_slice(&self.frame[sidx..][..w]);
158 for x in 0..w { dst[didx + x] = self.frame[sidx + x/2]; }
160 if !self.scale_h || ((y & 1) == 1) {
161 sidx += if !self.scale_v { w } else { w/2 };
168 fn decode_method2(&mut self, br: &mut ByteReader) -> DecoderResult<()> {
169 let mut bits = Bits8::new();
171 let mut size = self.info.get_properties().get_video_info().unwrap().get_width() *
172 self.info.get_properties().get_video_info().unwrap().get_height();
173 let mut idx = PREAMBLE_SIZE;
174 if self.frame[8] != 0 {
176 for i in 0..16 { self.frame[c * 16 + i] = c as u8; }
180 let tag = bits.read_2bits(br)?;
182 self.frame[idx] = br.read_byte()?;
186 let b = br.read_byte()?;
187 let len = ((b & 0xF) as usize) + 3;
188 let bot = (b >> 4) as isize;
189 let off = ((br.read_byte()? as isize) << 4) + bot - 4096;
190 validate!(len <= size);
192 self.lz_copy(idx, off, len)?;
195 let len = (br.read_byte()? as usize) + 2;
196 validate!(len <= size);
206 fn decode_method5(&mut self, br: &mut ByteReader, skip: usize) -> DecoderResult<()> {
207 let mut bits = Bits8::new();
209 let mut size = self.info.get_properties().get_video_info().unwrap().get_width() *
210 self.info.get_properties().get_video_info().unwrap().get_height();
211 let mut idx = PREAMBLE_SIZE;
212 validate!(size >= skip);
216 let tag = bits.read_2bits(br)?;
218 self.frame[idx] = br.read_byte()?;
222 let b = br.read_byte()?;
223 let len = ((b & 0xF) as usize) + 3;
224 let bot = (b >> 4) as isize;
225 let off = ((br.read_byte()? as isize) << 4) + bot - 4096;
226 validate!(len <= size);
228 self.lz_copy(idx, off, len)?;
231 let b = br.read_byte()?;
233 let len: usize = (if b != 0xFF { b as usize } else { br.read_u16le()? as usize }) + 1;
234 validate!(len <= size);
238 let b = br.read_byte()?;
239 let len = ((b & 0x3) as usize) + 2;
240 let off = -((b >> 2) as isize) - 1;
241 validate!(len <= size);
243 self.lz_copy(idx, off, len)?;
250 #[allow(clippy::identity_op)]
251 fn decode_method68(&mut self, br: &mut ByteReader,
252 skip: usize, use8: bool) -> DecoderResult<()> {
253 let mut bits = Bits32::new();
255 let mut size = self.info.get_properties().get_video_info().unwrap().get_width() *
256 self.info.get_properties().get_video_info().unwrap().get_height();
257 let mut idx = PREAMBLE_SIZE;
258 validate!(size >= skip);
263 let tag = bits.read_bits(br, 2)?;
265 let b = bits.read_bits(br, 1)?;
267 self.frame[idx] = br.read_byte()?;
271 let mut len: usize = 2;
275 let val = bits.read_bits(br, lbits)?;
277 if val != ((1 << lbits) - 1) { break; }
278 validate!(lbits < 16);
280 validate!(len <= size);
281 for i in 0..len { self.frame[idx + i] = br.read_byte()?; }
285 } else if tag == 1 { //skip
286 let b = bits.read_bits(br, 1)?;
289 len = (bits.read_bits(br, 4)? as usize) + 2;
291 let bb = br.read_byte()?;
292 if (bb & 0x80) == 0 {
293 len = (bb as usize) + 18;
295 let top = ((bb & 0x7F) as usize) << 8;
296 len = top + (br.read_byte()? as usize) + 146;
299 validate!(len <= size);
303 let subtag = bits.read_bits(br, 2)? as usize;
305 let top = (bits.read_bits(br, 4)? as usize) << 8;
306 let offs = top + (br.read_byte()? as usize);
307 if (subtag != 0) || (offs <= 0xF80) {
308 let len = (subtag as usize) + 3;
309 self.lz_copy(idx, (offs as isize) - 4096, len)?;
312 if offs == 0xFFF { return Ok(()); }
313 let real_off = ((offs >> 4) & 0x7) + 1;
314 let len = ((offs & 0xF) + 2) * 2;
315 validate!(len <= size);
317 let c1 = self.frame[idx - real_off];
318 let c2 = self.frame[idx - real_off + 1];
320 self.frame[idx + i*2 + 0] = c1;
321 self.frame[idx + i*2 + 1] = c2;
326 let b = br.read_byte()?;
327 let off = ((b & 0x7F) as usize) + 1;
328 let len = if (b & 0x80) == 0 { 2 } else { 3 };
329 validate!(len <= size);
331 self.lz_copy(idx, -(off as isize), len)?;
338 let b = br.read_byte()?;
339 if (b & 0xC0) == 0xC0 {
340 len = ((b & 0x3F) as usize) + 8;
341 let q = bits.read_bits(br, 4)? as isize;
342 off = (q << 8) + (br.read_byte()? as isize) + 1;
346 len = ((b >> 4) as usize) + 6;
347 ofs1 = (b & 0xF) as isize;
349 len = ((b & 0x3F) as usize) + 14;
350 ofs1 = bits.read_bits(br, 4)? as isize;
352 off = (ofs1 << 8) + (br.read_byte()? as isize) - 4096;
355 let b = br.read_byte()?;
357 len = (br.read_byte()? as usize) + 21;
359 len = ((b >> 4) as usize) + 6;
361 let ofs1 = (b & 0xF) as isize;
362 off = (ofs1 << 8) + (br.read_byte()? as isize) - 4096;
364 validate!(len <= size);
366 self.lz_copy(idx, off, len)?;
374 impl NADecoder for GremlinVideoDecoder {
375 fn init(&mut self, _supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()> {
376 if let NACodecTypeInfo::Video(vinfo) = info.get_properties() {
377 let w = vinfo.get_width();
378 let h = vinfo.get_height();
379 if !vinfo.get_format().is_paletted() { return Err(DecoderError::NotImplemented); }
380 let fmt = PAL8_FORMAT;
381 let myinfo = NACodecTypeInfo::Video(NAVideoInfo::new(w, h, false, fmt));
382 self.info = NACodecInfo::new_ref(info.get_name(), myinfo, info.get_extradata()).into_ref();
384 self.frame.resize(PREAMBLE_SIZE + w * h, 0);
388 self.frame[i * 2048 + j * 8 + k] = j as u8;
392 let edata = info.get_extradata().unwrap();
393 validate!(edata.len() == 768);
396 let cc = edata[c * 3 + i];
397 self.pal[c * 3 + i] = (cc << 2) | (cc >> 4);
402 Err(DecoderError::InvalidData)
405 fn decode(&mut self, _supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
406 let src = pkt.get_buffer();
407 let mut mr = MemoryReader::new_read(&src);
408 let mut br = ByteReader::new(&mut mr);
409 let flags = br.read_u32le()?;
410 let w = self.info.get_properties().get_video_info().unwrap().get_width();
411 let h = self.info.get_properties().get_video_info().unwrap().get_height();
413 let cmethod = flags & 0xF;
414 let is_intra = (flags & 0x40) != 0;
415 let scale_v = (flags & 0x10) != 0;
416 let scale_h = (flags & 0x20) != 0;
418 self.rescale(w, h, scale_v, scale_h);
420 if (cmethod == 0) || (cmethod == 1) {
423 let b = br.read_byte()?;
424 self.pal[c * 3 + i] = (b << 2) | (b >> 4);
428 for i in PREAMBLE_SIZE..self.frame.len() { self.frame[i] = 0x00; }
430 let mut frm = NAFrame::new_from_pkt(pkt, self.info.clone(), NABufferType::None);
431 frm.set_keyframe(false);
432 frm.set_frame_type(FrameType::Skip);
433 return Ok(frm.into_ref())
434 } else if cmethod == 3 {
435 let mut frm = NAFrame::new_from_pkt(pkt, self.info.clone(), NABufferType::None);
436 frm.set_keyframe(false);
437 frm.set_frame_type(FrameType::Skip);
438 return Ok(frm.into_ref())
439 } else if cmethod == 2 {
440 self.decode_method2(&mut br)?;
441 } else if cmethod == 5 {
442 self.decode_method5(&mut br, (flags >> 8) as usize)?;
443 } else if cmethod == 6 {
444 self.decode_method68(&mut br, (flags >> 8) as usize, false)?;
445 } else if cmethod == 8 {
446 self.decode_method68(&mut br, (flags >> 8) as usize, true)?;
448 return Err(DecoderError::NotImplemented);
451 let mut bufinfo = alloc_video_buffer(self.info.get_properties().get_video_info().unwrap(), 0)?;
453 self.output_frame(&mut bufinfo, w, h);
455 let mut frm = NAFrame::new_from_pkt(pkt, self.info.clone(), bufinfo);
456 frm.set_keyframe(is_intra);
457 frm.set_frame_type(if is_intra { FrameType::I } else { FrameType::P });
460 fn flush(&mut self) {
464 impl NAOptionHandler for GremlinVideoDecoder {
465 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
466 fn set_options(&mut self, _options: &[NAOption]) { }
467 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
470 pub fn get_decoder_video() -> Box<dyn NADecoder + Send> {
471 Box::new(GremlinVideoDecoder::new())
474 struct GremlinAudioDecoder {
477 delta_tab: [i16; 256],
482 impl GremlinAudioDecoder {
484 let mut delta_tab: [i16; 256] = [0; 256];
492 delta_tab[i * 2 + 1] = delta;
493 delta_tab[i * 2 + 2] = -delta;
495 delta_tab[255] = 32767;//delta + (code >> 5);
496 GremlinAudioDecoder {
497 ainfo: NAAudioInfo::new(0, 1, formats::SND_S16_FORMAT, 0),
498 chmap: NAChannelMap::new(),
506 const CHMAP_MONO: [NAChannelType; 1] = [NAChannelType::C];
507 const CHMAP_STEREO: [NAChannelType; 2] = [NAChannelType::L, NAChannelType::R];
509 fn get_default_chmap(nch: u8) -> NAChannelMap {
510 let mut chmap = NAChannelMap::new();
512 1 => chmap.add_channels(&CHMAP_MONO),
513 2 => chmap.add_channels(&CHMAP_STEREO),
519 impl NADecoder for GremlinAudioDecoder {
520 fn init(&mut self, _supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()> {
521 if let NACodecTypeInfo::Audio(ainfo) = info.get_properties() {
522 self.ainfo = NAAudioInfo::new(ainfo.get_sample_rate(), ainfo.get_channels(), formats::SND_S16P_FORMAT, ainfo.get_block_len());
523 self.chmap = get_default_chmap(ainfo.get_channels());
524 if self.chmap.num_channels() == 0 { return Err(DecoderError::InvalidData); }
527 Err(DecoderError::InvalidData)
530 fn decode(&mut self, _supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
531 let info = pkt.get_stream().get_info();
532 if let NACodecTypeInfo::Audio(_) = info.get_properties() {
533 let pktbuf = pkt.get_buffer();
534 let samples = pktbuf.len() / self.chmap.num_channels();
535 let abuf = alloc_audio_buffer(self.ainfo, samples, self.chmap.clone())?;
536 let mut adata = abuf.get_abuf_i16().unwrap();
537 let off1 = adata.get_offset(1);
538 let buf = adata.get_data_mut().unwrap();
539 if self.chmap.num_channels() == 2 {
540 for (i, e) in pktbuf.chunks(2).enumerate() {
541 self.state0 = self.state0.wrapping_add(self.delta_tab[e[0] as usize]);
542 buf[i] = self.state0;
543 self.state1 = self.state1.wrapping_add(self.delta_tab[e[1] as usize]);
544 buf[off1 + i] = self.state1;
547 for (i, e) in pktbuf.iter().enumerate() {
548 self.state0 += self.delta_tab[*e as usize];
549 buf[i] = self.state0;
552 let mut frm = NAFrame::new_from_pkt(pkt, info, abuf);
553 frm.set_duration(Some(samples as u64));
554 frm.set_keyframe(false);
557 Err(DecoderError::InvalidData)
560 fn flush(&mut self) {
564 impl NAOptionHandler for GremlinAudioDecoder {
565 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
566 fn set_options(&mut self, _options: &[NAOption]) { }
567 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
570 pub fn get_decoder_audio() -> Box<dyn NADecoder + Send> {
571 Box::new(GremlinAudioDecoder::new())
576 use nihav_core::codecs::RegisteredDecoders;
577 use nihav_core::demuxers::RegisteredDemuxers;
578 use nihav_codec_support::test::dec_video::*;
579 use crate::game_register_all_decoders;
580 use crate::game_register_all_demuxers;
583 fn test_gdv_video() {
584 let mut dmx_reg = RegisteredDemuxers::new();
585 game_register_all_demuxers(&mut dmx_reg);
586 let mut dec_reg = RegisteredDecoders::new();
587 game_register_all_decoders(&mut dec_reg);
589 test_decoding("gdv", "gdv-video", "assets/Game/intro1.gdv", Some(10), &dmx_reg, &dec_reg,
590 ExpectedTestResult::MD5([0x7ea302bf, 0xc3e210cf, 0x6e341376, 0x9e976056]));
593 fn test_gdv_audio() {
594 let mut dmx_reg = RegisteredDemuxers::new();
595 game_register_all_demuxers(&mut dmx_reg);
596 let mut dec_reg = RegisteredDecoders::new();
597 game_register_all_decoders(&mut dec_reg);
599 test_decoding("gdv", "gdv-audio", "assets/Game/intro1.gdv", None, &dmx_reg, &dec_reg,
600 ExpectedTestResult::MD5([0xd41d8cd9, 0x8f00b204, 0xe9800998, 0xecf8427e]));