1 use nihav_core::codecs::*;
2 use nihav_core::io::byteio::*;
3 use nihav_core::io::bitreader::*;
4 use nihav_core::io::codebook::*;
7 const PAL_SIZE: usize = 768;
8 const SMK_FLAG_INTERLACED: u32 = 0x02;
9 const SMK_FLAG_SCALED: u32 = 0x04;
12 cb: Option<Codebook<u8>>,
16 fn get_tree8(br: &mut BitReader, bits: &mut [u8; 256], codes: &mut [u32; 256], syms: &mut [u8; 256], count: &mut usize, len: u8, prefix: u32) -> DecoderResult<()> {
19 codes[*count] = prefix;
20 syms[*count] = br.read(8)? as u8;
23 validate!((*count <= 256 - 2) && (len <= 31));
24 get_tree8(br, bits, codes, syms, count, len + 1, prefix)?;
25 get_tree8(br, bits, codes, syms, count, len + 1, prefix | (1 << len))?;
30 pub struct FullTableCodebookDescReader<'a> {
36 impl<'a> FullTableCodebookDescReader<'a> {
37 pub fn new(codes: &'a [u32], bits: &'a [u8], syms: &'a [u8]) -> Self {
38 Self { bits, codes, syms }
41 impl<'a> CodebookDescReader<u8> for FullTableCodebookDescReader<'a>
43 fn bits(&mut self, idx: usize) -> u8 { self.bits[idx] }
44 fn code(&mut self, idx: usize) -> u32 { self.codes[idx] }
45 fn sym (&mut self, idx: usize) -> u8 { self.syms[idx] }
46 fn len(&mut self) -> usize { self.bits.len() }
56 fn decode(&mut self, br: &mut BitReader) -> DecoderResult<()> {
57 if !br.read_bool()? { return Ok(()); }
59 let mut bits: [u8; 256] = [0; 256];
60 let mut codes: [u32; 256] = [0; 256];
61 let mut syms: [u8; 256] = [0; 256];
64 get_tree8(br, &mut bits, &mut codes, &mut syms, &mut count, 0, 0)?;
65 validate!(!br.read_bool()?);
68 let mut cr = FullTableCodebookDescReader::new(&codes[0..count], &bits[0..count], &syms[0..count]);
69 let cb = Codebook::new(&mut cr, CodebookMode::LSB)?;
72 self.defsym = syms[0];
79 struct SmackerTree16 {
84 struct SmackerTree16Builder {
85 tree_lo: SmackerTree8,
86 tree_hi: SmackerTree8,
91 const SMK_BIGTREE_NODE: u32 = 0x80000000;
92 const SMK_LAST_UNINIT: usize = 0xFFFFFFFF;
94 impl SmackerTree16Builder {
95 fn get_tree16(&mut self, br: &mut BitReader, tree: &mut SmackerTree16, depth: usize) -> DecoderResult<u32> {
96 validate!(tree.tree.len() < self.nsyms);
98 let lo = br.read_tree8(&self.tree_lo)?;
99 let hi = br.read_tree8(&self.tree_hi)?;
100 let mut sym = (((hi as u16) << 8) | (lo as u16)) as u32;
101 if sym == self.esc[0] {
102 tree.last[0] = tree.tree.len();
104 } else if sym == self.esc[1] {
105 tree.last[1] = tree.tree.len();
107 } else if sym == self.esc[2] {
108 tree.last[2] = tree.tree.len();
114 let cur_idx = tree.tree.len();
116 let lcount = self.get_tree16(br, tree, depth + 1)?;
117 let rcount = self.get_tree16(br, tree, depth + 1)?;
118 tree.tree[cur_idx] = SMK_BIGTREE_NODE | lcount;
119 Ok(lcount + rcount + 1)
128 last: [SMK_LAST_UNINIT; 3],
131 fn decode(&mut self, br: &mut BitReader, size: u32) -> DecoderResult<()> {
132 if !br.read_bool()? { return Ok(()); }
134 let mut tree_lo = SmackerTree8::new();
136 let mut tree_hi = SmackerTree8::new();
139 let mut esc: [u32; 3] = [0; 3];
140 for i in 0..esc.len() {
141 esc[i] = br.read(16)? as u32;
144 let nsyms = (((size + 3) >> 2) + 4) as usize;
145 self.tree = Vec::with_capacity(nsyms);
147 let mut tb = SmackerTree16Builder { tree_lo, tree_hi, nsyms, esc };
149 tb.get_tree16(br, self, 0)?;
150 validate!(!br.read_bool()?);
152 for i in 0..self.last.len() {
153 if self.last[i] == SMK_LAST_UNINIT {
154 self.last[i] = self.tree.len();
158 validate!(self.tree.len() <= nsyms);
161 fn reset(&mut self) {
162 for i in 0..self.last.len() {
163 self.tree[self.last[i]] = 0;
169 fn read_tree8(&mut self, tree: &SmackerTree8) -> DecoderResult<u8>;
170 fn read_bigtree(&mut self, tree: &mut SmackerTree16) -> DecoderResult<u16>;
173 impl<'a> ReadTree for BitReader<'a> {
174 fn read_tree8(&mut self, tree: &SmackerTree8) -> DecoderResult<u8> {
175 if let Some(ref cb) = tree.cb {
176 Ok(self.read_cb(cb)?)
181 fn read_bigtree(&mut self, tree: &mut SmackerTree16) -> DecoderResult<u16> {
183 while (tree.tree[pos] & SMK_BIGTREE_NODE) != 0 {
184 if self.read_bool()? {
185 pos += (tree.tree[pos] & !SMK_BIGTREE_NODE) as usize;
189 let val = tree.tree[pos];
190 if val != tree.tree[tree.last[0]] {
191 tree.tree[tree.last[2]] = tree.tree[tree.last[1]];
192 tree.tree[tree.last[1]] = tree.tree[tree.last[0]];
193 tree.tree[tree.last[0]] = val;
199 const SMK_BLOCK_RUNS: [usize; 64] = [
200 1, 2, 3, 4, 5, 6, 7, 8,
201 9, 10, 11, 12, 13, 14, 15, 16,
202 17, 18, 19, 20, 21, 22, 23, 24,
203 25, 26, 27, 28, 29, 30, 31, 32,
204 33, 34, 35, 36, 37, 38, 39, 40,
205 41, 42, 43, 44, 45, 46, 47, 48,
206 49, 50, 51, 52, 53, 54, 55, 56,
207 57, 58, 59, 128, 256, 512, 1024, 2048
210 struct SmackerVideoDecoder {
211 info: Rc<NACodecInfo>,
212 mmap_tree: SmackerTree16,
213 mclr_tree: SmackerTree16,
214 full_tree: SmackerTree16,
215 type_tree: SmackerTree16,
226 impl SmackerVideoDecoder {
228 let dummy_info = Rc::new(DUMMY_CODEC_INFO);
231 mmap_tree: SmackerTree16::new(),
232 mclr_tree: SmackerTree16::new(),
233 full_tree: SmackerTree16::new(),
234 type_tree: SmackerTree16::new(),
245 fn block_pos(&self, blk_no: usize) -> usize {
246 let bx = blk_no % self.bw;
247 let by = blk_no / self.bw;
248 bx * 4 + by * 4 * self.stride
250 fn decode_frame(&mut self, br: &mut BitReader) -> DecoderResult<bool> {
251 let mut is_intra = true;
252 let blocks = self.bw * self.bh;
254 self.mmap_tree.reset();
255 self.mclr_tree.reset();
256 self.full_tree.reset();
257 self.type_tree.reset();
260 while block < blocks {
261 let btype = br.read_bigtree(&mut self.type_tree)?;
262 let run = SMK_BLOCK_RUNS[((btype as usize) >> 2) & 0x3F];
263 validate!(run <= blocks - block);
265 0 => { // two-colour pattern
267 let clr = br.read_bigtree(&mut self.mclr_tree)?;
268 let mut map = br.read_bigtree(&mut self.mmap_tree)?;
269 let hi = (clr >> 8) as u8;
270 let lo = (clr & 0xFF) as u8;
271 let mut doff = self.block_pos(block + i);
273 self.frame[doff + 0] = if (map & 1) != 0 { hi } else { lo };
274 self.frame[doff + 1] = if (map & 2) != 0 { hi } else { lo };
275 self.frame[doff + 2] = if (map & 4) != 0 { hi } else { lo };
276 self.frame[doff + 3] = if (map & 8) != 0 { hi } else { lo };
284 if !self.is_ver4 || !br.read_bool()? {
287 mode = 1 + br.read(1)?;
290 let mut doff = self.block_pos(block + i);
294 let clr0 = br.read_bigtree(&mut self.full_tree)?;
295 let clr1 = br.read_bigtree(&mut self.full_tree)?;
296 self.frame[doff + 0] = (clr1 & 0xFF) as u8;
297 self.frame[doff + 1] = (clr1 >> 8) as u8;
298 self.frame[doff + 2] = (clr0 & 0xFF) as u8;
299 self.frame[doff + 3] = (clr0 >> 8) as u8;
305 let clr = br.read_bigtree(&mut self.full_tree)?;
306 self.frame[doff + 0] = (clr & 0xFF) as u8;
307 self.frame[doff + 1] = (clr & 0xFF) as u8;
308 self.frame[doff + 2] = (clr >> 8) as u8;
309 self.frame[doff + 3] = (clr >> 8) as u8;
311 self.frame[doff + 0] = (clr & 0xFF) as u8;
312 self.frame[doff + 1] = (clr & 0xFF) as u8;
313 self.frame[doff + 2] = (clr >> 8) as u8;
314 self.frame[doff + 3] = (clr >> 8) as u8;
320 let clr0 = br.read_bigtree(&mut self.full_tree)?;
321 let clr1 = br.read_bigtree(&mut self.full_tree)?;
322 self.frame[doff + 0] = (clr1 & 0xFF) as u8;
323 self.frame[doff + 1] = (clr1 >> 8) as u8;
324 self.frame[doff + 2] = (clr0 & 0xFF) as u8;
325 self.frame[doff + 3] = (clr0 >> 8) as u8;
327 self.frame[doff + 0] = (clr1 & 0xFF) as u8;
328 self.frame[doff + 1] = (clr1 >> 8) as u8;
329 self.frame[doff + 2] = (clr0 & 0xFF) as u8;
330 self.frame[doff + 3] = (clr0 >> 8) as u8;
342 let clr = (btype >> 8) as u8;
344 let mut doff = self.block_pos(block + i);
346 self.frame[doff + 0] = clr;
347 self.frame[doff + 1] = clr;
348 self.frame[doff + 2] = clr;
349 self.frame[doff + 3] = clr;
360 fn output_frame(&self, buf: &mut NAVideoBuffer<u8>) {
361 let stride = buf.get_stride(0);
362 let mut data = buf.get_data_mut();
363 let dst = data.as_mut_slice();
364 let is_scaled = (self.flags & SMK_FLAG_SCALED) != 0;
365 let is_interlaced = (self.flags & SMK_FLAG_INTERLACED) != 0;
369 for x in 0..self.w { dst[didx + x] = self.frame[sidx + x]; }
373 for x in 0..self.w { dst[didx + x] = dst[didx - stride + x]; }
377 for x in 0..self.w { dst[didx + x] = 0; }
380 for x in 0..self.w { dst[didx + x] = 0; }
388 impl NADecoder for SmackerVideoDecoder {
389 fn init(&mut self, info: Rc<NACodecInfo>) -> DecoderResult<()> {
390 if let NACodecTypeInfo::Video(vinfo) = info.get_properties() {
391 let w = vinfo.get_width();
392 let h = vinfo.get_height();
393 let fmt = PAL8_FORMAT;
399 let edata = info.get_extradata().unwrap();
400 validate!(edata.len() > 24);
403 self.frame.resize(w * h, 0);
405 let mut mr = MemoryReader::new_read(&edata);
406 let mut br = ByteReader::new(&mut mr);
407 let magic = br.read_u32be()?;
408 self.flags = br.read_u32le()?;
409 let mmap_size = br.read_u32le()?;
410 let mclr_size = br.read_u32le()?;
411 let full_size = br.read_u32le()?;
412 let type_size = br.read_u32le()?;
414 self.is_ver4 = (magic & 0xFF) == 0x34;
415 let mut br = BitReader::new(&edata[24..], edata.len() - 24, BitReaderMode::LE);
416 self.mmap_tree.decode(&mut br, mmap_size)?;
417 self.mclr_tree.decode(&mut br, mclr_size)?;
418 self.full_tree.decode(&mut br, full_size)?;
419 self.type_tree.decode(&mut br, type_size)?;
422 if (self.flags & SMK_FLAG_INTERLACED) != 0 {
425 if (self.flags & SMK_FLAG_SCALED) != 0 {
428 let myinfo = NACodecTypeInfo::Video(NAVideoInfo::new(w, out_h, false, fmt));
429 self.info = Rc::new(NACodecInfo::new_ref(info.get_name(), myinfo, info.get_extradata()));
434 Err(DecoderError::InvalidData)
437 fn decode(&mut self, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
438 let src = pkt.get_buffer();
439 validate!(src.len() >= PAL_SIZE);
444 if src.len() > PAL_SIZE {
445 let mut br = BitReader::new(&src[PAL_SIZE..], src.len() - PAL_SIZE, BitReaderMode::LE);
447 let bufret = alloc_video_buffer(self.info.get_properties().get_video_info().unwrap(), 2);
448 if let Err(_) = bufret { return Err(DecoderError::InvalidData); }
449 bufinfo = bufret.unwrap();
450 let mut buf = bufinfo.get_vbuf().unwrap();
451 is_intra = self.decode_frame(&mut br)?;
452 self.output_frame(&mut buf);
453 let paloff = buf.get_offset(1);
454 let mut data = buf.get_data_mut();
455 let dst = data.as_mut_slice();
456 let palout = &mut dst[paloff..][..PAL_SIZE];
457 palout.copy_from_slice(&src[0..PAL_SIZE]);
458 ftype = if is_intra { FrameType::I } else { FrameType::P };
460 bufinfo = NABufferType::None;
461 ftype = FrameType::Skip;
465 let mut frm = NAFrame::new_from_pkt(pkt, self.info.clone(), bufinfo);
466 frm.set_keyframe(is_intra);
467 frm.set_frame_type(ftype);
468 Ok(Rc::new(RefCell::new(frm)))
472 pub fn get_decoder_video() -> Box<NADecoder> {
473 Box::new(SmackerVideoDecoder::new())
476 struct SmackerAudioDecoder {
483 impl SmackerAudioDecoder {
486 ainfo: NAAudioInfo::new(0, 1, SND_S16P_FORMAT, 0),
487 chmap: NAChannelMap::new(),
494 impl NADecoder for SmackerAudioDecoder {
495 fn init(&mut self, info: Rc<NACodecInfo>) -> DecoderResult<()> {
496 if let NACodecTypeInfo::Audio(ainfo) = info.get_properties() {
497 self.bits = ainfo.get_format().get_bits();
498 let fmt = if self.bits == 8 { SND_U8_FORMAT } else { SND_S16P_FORMAT };
499 self.chans = ainfo.get_channels() as usize;
500 self.ainfo = NAAudioInfo::new(ainfo.get_sample_rate(), ainfo.get_channels(), fmt, 0);
501 self.chmap = NAChannelMap::from_str(if ainfo.get_channels() == 2 {"L,R"} else {"C"}).unwrap();
504 Err(DecoderError::InvalidData)
507 fn decode(&mut self, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
508 let info = pkt.get_stream().get_info();
509 if let NACodecTypeInfo::Audio(_) = info.get_properties() {
510 let src = pkt.get_buffer();
511 validate!(src.len() > 4);
512 let mut br = BitReader::new(&src, src.len(), BitReaderMode::LE);
513 let unp_size = br.read(32)? as usize;
514 if !br.read_bool()? {
515 let mut frm = NAFrame::new_from_pkt(pkt, info.clone(), NABufferType::None);
516 frm.set_frame_type(FrameType::Skip);
517 return Ok(Rc::new(RefCell::new(frm)));
519 let stereo = br.read_bool()?;
520 let bits16 = br.read_bool()?;
521 validate!(!(stereo ^ (self.chans == 2)));
522 validate!(!(bits16 ^ (self.bits == 16)));
526 let nch = if stereo { 2 } else { 1 };
528 samples = unp_size / 2 / nch;
529 let mask = if stereo { 1 } else { 0 };
530 let mut trees: [SmackerTree8; 4] = [SmackerTree8::new(), SmackerTree8::new(), SmackerTree8::new(), SmackerTree8::new()];
532 trees[i].decode(&mut br)?;
534 let mut pred: [i16; 2] = [0; 2];
536 let hi = br.read(8)?;
537 let lo = br.read(8)?;
538 pred[nch - i - 1] = (lo | (hi << 8)) as i16;
541 abuf = alloc_audio_buffer(self.ainfo, samples, self.chmap.clone())?;
542 let mut adata = abuf.get_abuf_i16().unwrap();
543 let offs: [usize; 2] = [0, adata.get_offset(1)];
544 let mut dst = adata.get_data_mut();
546 dst[offs[ch]] = pred[ch];
548 for i in nch..(unp_size >> 1) {
550 let lo = br.read_tree8(&trees[idx * 2 + 0])? as u16;
551 let hi = br.read_tree8(&trees[idx * 2 + 1])? as u16;
552 let diff = (lo | (hi << 8)) as i16;
553 pred[idx] = pred[idx].wrapping_add(diff);
554 dst[offs[idx] + (i >> 1)] = pred[idx];
557 samples = unp_size / nch;
558 abuf = alloc_audio_buffer(self.ainfo, samples, self.chmap.clone())?;
559 let mut adata = abuf.get_abuf_u8().unwrap();
560 let mut dst = adata.get_data_mut();
562 let mut trees: [SmackerTree8; 2] = [SmackerTree8::new(), SmackerTree8::new()];
563 trees[0].decode(&mut br)?;
564 trees[1].decode(&mut br)?;
565 let pred0 = br.read(8)? as u8;
566 let pred1 = br.read(8)? as u8;
567 let mut pred: [u8; 2] = [ pred1, pred0 ];
568 for ch in 0..2 { dst[ch] = pred[ch]; }
569 for i in 2..unp_size {
570 let diff = br.read_tree8(&trees[i & 1])? as u8;
571 pred[i & 1] = pred[i & 1].wrapping_add(diff);
572 dst[i] = pred[i & 1];
575 let mut tree = SmackerTree8::new();
576 tree.decode(&mut br)?;
577 let mut pred = br.read(8)? as u8;
579 for i in 1..unp_size {
580 let diff = br.read_tree8(&tree)? as u8;
581 pred = pred.wrapping_add(diff);
586 let mut frm = NAFrame::new_from_pkt(pkt, info, abuf);
587 frm.set_duration(Some(samples as u64));
588 frm.set_keyframe(false);
589 Ok(Rc::new(RefCell::new(frm)))
591 Err(DecoderError::InvalidData)
596 pub fn get_decoder_audio() -> Box<NADecoder> {
597 Box::new(SmackerAudioDecoder::new())
602 use nihav_core::codecs::RegisteredDecoders;
603 use nihav_core::demuxers::RegisteredDemuxers;
604 use nihav_core::test::dec_video::*;
605 use crate::codecs::rad_register_all_codecs;
606 use crate::demuxers::rad_register_all_demuxers;
609 let mut dmx_reg = RegisteredDemuxers::new();
610 rad_register_all_demuxers(&mut dmx_reg);
611 let mut dec_reg = RegisteredDecoders::new();
612 rad_register_all_codecs(&mut dec_reg);
614 //let file = "assets/RAD/20130507_audio-distortion.smk";
615 //let file = "assets/RAD/ajfstr1.smk";
616 //let file = "assets/RAD/credits.smk";
617 let file = "assets/RAD/wetlogo.smk";
618 test_file_decoding("smacker", file, Some(1000), true, false, None, &dmx_reg, &dec_reg);
622 let mut dmx_reg = RegisteredDemuxers::new();
623 rad_register_all_demuxers(&mut dmx_reg);
624 let mut dec_reg = RegisteredDecoders::new();
625 rad_register_all_codecs(&mut dec_reg);
627 //let file = "assets/RAD/20130507_audio-distortion.smk";
628 let file = "assets/RAD/wetlogo.smk";
629 test_decode_audio("smacker", file, None, "smk", &dmx_reg, &dec_reg);