1 use nihav_core::codecs::*;
2 use nihav_core::io::byteio::*;
4 type UnpackedPixel = [u16; 4];
6 fn map_quality_pal(quality: u8) -> (u32, u32) {
10 let skip_threshold = (10 - (u32::from(quality) / 10).min(10)) * (8 << 6);
11 let fill_threshold = (10 - (u32::from(quality) / 10).min(10)) * (16 << 6);
12 (skip_threshold, fill_threshold)
16 fn map_quality_15bit(quality: u8) -> (u32, u32) {
20 let skip_threshold = (10 - (u32::from(quality) / 10).min(10)) * 8;
21 let fill_threshold = (10 - (u32::from(quality) / 10).min(10)) * 16;
22 (skip_threshold, fill_threshold)
27 fn unpack(&self) -> UnpackedPixel;
28 fn dist<T: PixelOps>(&self, val: T) -> u32 {
29 dist_core(self.unpack(), &val.unpack())
33 impl PixelOps for u16 {
34 fn unpack(&self) -> UnpackedPixel {
36 let r = (val >> 10) & 0x1F;
37 let g = (val >> 5) & 0x1F;
39 [r, g, b, rgb2y(r, g, b)]
43 fn dist_core(val: UnpackedPixel, other: &UnpackedPixel) -> u32 {
44 let sum = val.iter().zip(other.iter()).take(3).fold(0i32,
46 let diff = i32::from(a) - i32::from(b);
52 fn find_nearest(pix: UnpackedPixel, pal: &[UnpackedPixel; 256]) -> usize {
54 let mut bestdist = std::u32::MAX;
56 for (idx, entry) in pal.iter().enumerate() {
57 let dist = dist_core(pix, entry);
70 pal: [UnpackedPixel; 256],
71 db: Vec<Vec<UnpackedPixel>>,
75 fn quant(key: UnpackedPixel) -> usize {
76 (((key[0] >> 3) as usize) << 10) |
77 (((key[1] >> 3) as usize) << 5) |
78 ((key[2] >> 3) as usize)
81 let mut db = Vec::with_capacity(1 << 15);
82 for _ in 0..(1 << 15) {
86 pal: [UnpackedPixel::default(); 256],
90 fn recalculate(&mut self, pal: &[UnpackedPixel; 256]) {
92 for vec in self.db.iter_mut() {
95 for (i, palentry) in pal.iter().enumerate() {
96 let r0 = (palentry[0] >> 3) as usize;
97 let g0 = (palentry[1] >> 3) as usize;
98 let b0 = (palentry[2] >> 3) as usize;
99 for r in r0.saturating_sub(1)..=(r0 + 1).min(31) {
100 for g in g0.saturating_sub(1)..=(g0 + 1).min(31) {
101 for b in b0.saturating_sub(1)..=(b0 + 1).min(31) {
102 let idx = (r << 10) | (g << 5) | b;
103 self.db[idx].push([palentry[0], palentry[1], palentry[2], i as u16]);
109 fn search(&self, pix: UnpackedPixel) -> usize {
110 let idx = Self::quant(pix);
111 let mut best_dist = std::u32::MAX;
112 let mut best_idx = 0;
114 for clr in self.db[idx].iter() {
115 let dist = dist_core(pix, clr);
117 if best_dist > dist {
119 best_idx = clr[3] as usize;
120 if dist == 0 { break; }
126 find_nearest(pix, &self.pal)
131 fn rgb2y(r: u16, g: u16, b: u16) -> u16 {
132 (r * 77 + g * 150 + b * 29) >> 8
135 fn pack_rgb555(val: UnpackedPixel) -> u16 {
136 (val[0] << 10) | (val[1] << 5) | val[2]
140 struct PixelAverage {
146 fn new() -> Self { Self::default() }
147 fn add(&mut self, val: &UnpackedPixel) {
148 for (dst, &src) in self.sum.iter_mut().zip(val.iter()) {
153 fn get_avg(&self) -> UnpackedPixel {
155 let mut ret = self.sum;
156 for el in ret.iter_mut() {
166 macro_rules! quant_template {
167 ($name:ident, $N:expr) => {
168 fn $name(pix: &[UnpackedPixel; $N]) -> ([UnpackedPixel; 2], u16, u32) {
169 let mut avg = PixelAverage::new();
170 let mut maxv = [0; 4];
171 let mut minv = [255; 4];
172 for src in pix.iter() {
174 for ((maxv, minv), &comp) in maxv.iter_mut().zip(minv.iter_mut()).zip(src.iter()) {
175 *maxv = (*maxv).max(comp);
176 *minv = (*minv).min(comp);
179 let avg = avg.get_avg();
181 let mut best_axis = 3;
182 let mut best_dist = maxv[3] - minv[3];
183 for (comp_no, (&minval, &maxval)) in minv.iter().zip(maxv.iter()).enumerate().take(3) {
184 if maxval - minval > best_dist {
186 best_dist = maxval - minval;
191 for el in pix.iter() {
192 dist += dist_core(avg, el);
194 return ([avg; 2], 0, dist);
197 let mut avg1 = PixelAverage::new();
198 let mut avg2 = PixelAverage::new();
200 let mut mask_bit = 1;
201 for clr in pix.iter() {
202 if clr[best_axis] > avg[best_axis] {
211 let clr0 = avg1.get_avg();
212 let clr1 = avg2.get_avg();
214 for clr in pix.iter() {
215 let dist0 = dist_core(clr0, clr);
216 let dist1 = dist_core(clr1, clr);
217 dist += dist0.min(dist1);
219 ([clr0, clr1], mask, dist)
224 quant_template!(quant2_16pix, 16);
225 quant_template!(quant2_4pix, 4);
230 fill_val: UnpackedPixel,
233 clr2: [UnpackedPixel; 2],
236 clr8: [[UnpackedPixel; 2]; 4],
241 fn new_pal() -> Self { Self { pal_mode: true, ..Default::default() } }
242 fn set_fill_val(&mut self, val: UnpackedPixel) {
245 self.fill_val[0] &= !1;
248 fn calc_clrs(buf: &[UnpackedPixel; 16]) -> (Option<UnpackedPixel>, Option<UnpackedPixel>) {
251 let mut single = true;
252 for &pix in buf[1..].iter() {
257 } else if pix != clr1 {
263 (Some(clr0), Some(clr1))
268 fn calc_stats(&mut self, buf: &[UnpackedPixel; 16]) {
269 let mut filled = false;
270 let mut two_clr = false;
271 match Self::calc_clrs(buf) {
272 (Some(clr0), Some(clr1)) => {
277 (Some(clr0), None) => {
280 self.set_fill_val(buf[0]);
288 let mut avg = PixelAverage::new();
289 for pix in buf.iter() {
292 self.set_fill_val(avg.get_avg());
293 for pix in buf.iter() {
294 self.fill_dist += dist_core(self.fill_val, pix);
297 if self.fill_dist == 0 {
298 self.clr2_dist = std::u32::MAX;
299 self.clr8_dist = std::u32::MAX;
303 self.clr2_flags = 0u16;
307 for &pix in buf.iter() {
308 if pix == self.clr2[0] {
309 self.clr2_flags |= mask;
314 if (self.clr2_flags & 0x8000) != 0 {
315 self.clr2_flags = !self.clr2_flags;
316 self.clr2.swap(0, 1);
319 let (clrs, mask, dist) = quant2_16pix(&buf);
321 self.clr2_flags = mask;
322 self.clr2_dist = dist;
323 if (self.clr2_flags & 0x8000) != 0 {
324 self.clr2_flags = !self.clr2_flags;
325 self.clr2.swap(0, 1);
328 if self.clr2_dist == 0 {
329 self.clr8_dist = std::u32::MAX;
333 self.clr8 = [[UnpackedPixel::default(); 2]; 4];
337 let off = (i & 1) * 2 + (i & 2) * 4;
338 let src2 = [buf[off], buf[off + 1], buf[off + 4], buf[off + 5]];
339 let (clrs, mask, dist) = quant2_4pix(&src2);
341 let lo_bits = (mask & 0x3) ^ 0x3;
342 let hi_bits = ((mask & 0xC) ^ 0xC) << 2;
343 self.clr8_flags |= (hi_bits | lo_bits) << ((i & 1) * 2 + (i & 2) * 4);
344 self.clr8_dist += dist;
349 struct BlockPainterPal<'a> {
352 impl<'a> BlockPainterPal<'a> {
353 fn new(ls: &'a LocalSearch) -> Self { Self{ ls } }
354 fn find_index(&self, pix: UnpackedPixel) -> u8 { self.ls.search(pix) as u8 }
355 fn put_fill(&self, bstate: &BlockState, dst: &mut [u8], dstride: usize) -> u8 {
356 let fill_val = self.find_index(bstate.fill_val);
357 for line in dst.chunks_mut(dstride) {
364 fn put_clr2(&self, bstate: &BlockState, dst: &mut [u8], dstride: usize) -> [u8; 2] {
365 let clr2 = [self.find_index(bstate.clr2[0]), self.find_index(bstate.clr2[1])];
368 if (bstate.clr2_flags & (1 << (i + j * 4))) == 0 {
369 dst[i + j * dstride] = clr2[0];
371 dst[i + j * dstride] = clr2[1];
377 fn put_clr8(&self, bstate: &BlockState, dst: &mut [u8], dstride: usize) -> [[u8; 4]; 4] {
378 let mut clr8 = [[0; 4]; 4];
379 for (dst, src) in clr8.iter_mut().zip(bstate.clr8.iter()) {
380 for (dst, &src) in dst.iter_mut().zip(src.iter()) {
381 *dst = self.find_index(src);
384 let mut clr8_flags = bstate.clr8_flags;
385 let swap = (clr8_flags & 0x8000) == 0;
387 clr8_flags ^= 0xFF00;
389 if clr8_flags < 0x9000 {
390 clr8_flags |= 0x1000;
393 clr8_flags ^= 0xFF00;
395 for (j, line) in dst.chunks_mut(dstride).take(4).enumerate() {
396 for (i, el) in line.iter_mut().take(4).enumerate() {
397 let blk_no = (i >> 1) + (j & 2);
398 *el = clr8[blk_no][(!clr8_flags & 1) as usize];
406 struct BlockWriterPal {}
407 impl BlockWriterPal {
408 fn write_fill(bw: &mut ByteWriter, fill_val: u8) -> EncoderResult<()> {
409 bw.write_byte(fill_val)?;
410 bw.write_byte(0x80)?;
413 fn write_clr2(bw: &mut ByteWriter, clr2_flags: u16, clr2: [u8; 2]) -> EncoderResult<()> {
414 bw.write_u16le(clr2_flags)?;
415 bw.write_byte(clr2[0])?;
416 bw.write_byte(clr2[1])?;
419 fn write_clr8(bw: &mut ByteWriter, mut clr8_flags: u16, mut clr8: [[u8; 4]; 4]) -> EncoderResult<()> {
420 if (clr8_flags & 0x8000) == 0 {
421 clr8_flags ^= 0xFF00;
425 if clr8_flags < 0x9000 {
426 clr8_flags |= 0x1000;
429 bw.write_u16le(clr8_flags)?;
430 bw.write_byte(clr8[0][0])?;
431 bw.write_byte(clr8[0][1])?;
432 bw.write_byte(clr8[1][0])?;
433 bw.write_byte(clr8[1][1])?;
434 bw.write_byte(clr8[2][0])?;
435 bw.write_byte(clr8[2][1])?;
436 bw.write_byte(clr8[3][0])?;
437 bw.write_byte(clr8[3][1])?;
442 struct BlockPainter15 {}
443 impl BlockPainter15 {
444 fn new() -> Self { Self{} }
445 fn put_fill(&self, bstate: &BlockState, dst: &mut [u16], dstride: usize) -> u16 {
446 let fill_val = pack_rgb555(bstate.fill_val);
447 for line in dst.chunks_mut(dstride) {
454 fn put_clr2(&self, bstate: &BlockState, dst: &mut [u16], dstride: usize) -> [u16; 2] {
455 let clr2 = [pack_rgb555(bstate.clr2[0]), pack_rgb555(bstate.clr2[1])];
458 if (bstate.clr2_flags & (1 << (i + j * 4))) == 0 {
459 dst[i + j * dstride] = clr2[0];
461 dst[i + j * dstride] = clr2[1];
467 fn put_clr8(&self, bstate: &BlockState, dst: &mut [u16], dstride: usize) -> [[u16; 4]; 4] {
468 let mut clr8 = [[0; 4]; 4];
469 for (dst, src) in clr8.iter_mut().zip(bstate.clr8.iter()) {
470 for (dst, &src) in dst.iter_mut().zip(src.iter()) {
471 *dst = pack_rgb555(src);
474 let mut clr8_flags = bstate.clr8_flags;
475 for (j, line) in dst.chunks_mut(dstride).take(4).enumerate() {
476 for (i, el) in line.iter_mut().take(4).enumerate() {
477 let blk_no = (i >> 1) + (j & 2);
478 *el = clr8[blk_no][(!clr8_flags & 1) as usize];
486 struct BlockWriter15 {}
488 fn write_fill(bw: &mut ByteWriter, fill_val: u16) -> EncoderResult<()> {
489 bw.write_u16le(fill_val | 0x8000)?;
492 fn write_clr2(bw: &mut ByteWriter, clr2_flags: u16, clr2: [u16; 2]) -> EncoderResult<()> {
493 bw.write_u16le(clr2_flags)?;
494 bw.write_u16le(clr2[0])?;
495 bw.write_u16le(clr2[1])?;
498 fn write_clr8(bw: &mut ByteWriter, mut clr8_flags: u16, mut clr8: [[u16; 4]; 4]) -> EncoderResult<()> {
499 if (clr8_flags & 0x8000) != 0 {
500 clr8_flags ^= 0xFF00;
504 bw.write_u16le(clr8_flags)?;
505 bw.write_u16le(clr8[0][0] | 0x8000)?;
506 bw.write_u16le(clr8[0][1])?;
507 bw.write_u16le(clr8[1][0])?;
508 bw.write_u16le(clr8[1][1])?;
509 bw.write_u16le(clr8[2][0])?;
510 bw.write_u16le(clr8[2][1])?;
511 bw.write_u16le(clr8[3][0])?;
512 bw.write_u16le(clr8[3][1])?;
517 struct MSVideo1Encoder {
518 stream: Option<NAStreamRef>,
519 pkt: Option<NAPacket>,
520 pool8: NAVideoBufferPool<u8>,
521 pool15: NAVideoBufferPool<u16>,
522 lastfrm8: Option<NAVideoBufferRef<u8>>,
523 lastfrm15: Option<NAVideoBufferRef<u16>>,
529 pal: [UnpackedPixel; 256],
533 impl MSVideo1Encoder {
538 pool8: NAVideoBufferPool::new(2),
539 pool15: NAVideoBufferPool::new(2),
547 pal: [UnpackedPixel::default(); 256],
548 ls: LocalSearch::new(),
551 fn get_block(src: &[u16], sstride: usize, buf: &mut [UnpackedPixel; 16]) {
552 for (line, dst) in src.chunks(sstride).zip(buf.chunks_mut(4)) {
553 for (dst, src) in dst.iter_mut().zip(line.iter()) {
558 fn get_block8(src: &[u8], sstride: usize, buf: &mut [UnpackedPixel; 16], pal: &[UnpackedPixel; 256]) {
559 for (line, dst) in src.chunks(sstride).zip(buf.chunks_mut(4)) {
560 for (dst, src) in dst.iter_mut().zip(line.iter()) {
561 *dst = pal[usize::from(*src)];
565 fn write_skips(bw: &mut ByteWriter, skips: usize) -> EncoderResult<()> {
566 bw.write_u16le((skips as u16) | 0x8400)?;
569 fn encode_inter_rgb555(bw: &mut ByteWriter, cur_frm: &mut NAVideoBuffer<u16>, in_frm: &NAVideoBuffer<u16>, prev_frm: &NAVideoBuffer<u16>, quality: u8) -> EncoderResult<bool> {
570 let (skip_threshold, fill_threshold) = map_quality_15bit(quality);
571 let mut is_intra = true;
572 let src = in_frm.get_data();
573 let sstride = in_frm.get_stride(0);
574 let soff = in_frm.get_offset(0);
575 let (w, h) = in_frm.get_dimensions(0);
576 let rsrc = prev_frm.get_data();
577 let rstride = prev_frm.get_stride(0);
578 let roff = prev_frm.get_offset(0);
579 let dstride = cur_frm.get_stride(0);
580 let doff = cur_frm.get_offset(0);
581 let dst = cur_frm.get_data_mut().unwrap();
582 let mut skip_run = 0;
583 let bpainter = BlockPainter15::new();
584 for ((sstrip, rstrip), dstrip) in (&src[soff..]).chunks(sstride * 4).take(h / 4).zip((&rsrc[roff..]).chunks(rstride * 4)).zip((&mut dst[doff..]).chunks_mut(dstride * 4)) {
585 for x in (0..w).step_by(4) {
586 let mut buf = [UnpackedPixel::default(); 16];
587 let mut refbuf = [UnpackedPixel::default(); 16];
588 Self::get_block(&sstrip[x..], sstride, &mut buf);
589 Self::get_block(&rstrip[x..], rstride, &mut refbuf);
591 let mut skip_dist = 0;
592 for (pix, rpix) in buf.iter().zip(refbuf.iter()) {
593 skip_dist += dist_core(*rpix, pix);
595 if skip_dist <= skip_threshold {
598 for (dst, src) in dstrip[x..].chunks_mut(dstride).zip(rstrip[x..].chunks(rstride)).take(4) {
599 dst[..4].copy_from_slice(&src[..4]);
601 if skip_run == 1023 {
602 Self::write_skips(bw, skip_run)?;
608 let mut bstate = BlockState::default();
609 bstate.calc_stats(&buf);
611 let dst = &mut dstrip[x..];
612 if skip_dist <= bstate.fill_dist && skip_dist * 2 <= bstate.clr2_dist {
615 for (dst, src) in dst.chunks_mut(dstride).zip(rstrip[x..].chunks(rstride)).take(4) {
616 dst[..4].copy_from_slice(&src[..4]);
618 if skip_run == 1023 {
619 Self::write_skips(bw, skip_run)?;
622 } else if bstate.fill_dist <= fill_threshold ||
623 bstate.fill_dist <= bstate.clr2_dist {
624 let fill_val = bpainter.put_fill(&bstate, dst, dstride);
626 Self::write_skips(bw, skip_run)?;
629 BlockWriter15::write_fill(bw, fill_val)?;
630 } else if bstate.clr8_dist < bstate.clr2_dist {
631 let clr8 = bpainter.put_clr8(&bstate, dst, dstride);
633 Self::write_skips(bw, skip_run)?;
636 BlockWriter15::write_clr8(bw, bstate.clr8_flags, clr8)?;
638 let clr2 = bpainter.put_clr2(&bstate, dst, dstride);
640 Self::write_skips(bw, skip_run)?;
643 BlockWriter15::write_clr2(bw, bstate.clr2_flags, clr2)?;
648 Self::write_skips(bw, skip_run)?;
652 } //xxx: something for inter?
655 fn encode_intra_rgb555(bw: &mut ByteWriter, cur_frm: &mut NAVideoBuffer<u16>, in_frm: &NAVideoBuffer<u16>, quality: u8) -> EncoderResult<bool> {
656 let (_, fill_threshold) = map_quality_15bit(quality);
657 let src = in_frm.get_data();
658 let sstride = in_frm.get_stride(0);
659 let soff = in_frm.get_offset(0);
660 let (w, h) = in_frm.get_dimensions(0);
661 let dstride = cur_frm.get_stride(0);
662 let doff = cur_frm.get_offset(0);
663 let dst = cur_frm.get_data_mut().unwrap();
664 let bpainter = BlockPainter15::new();
665 for (sstrip, dstrip) in (&src[soff..]).chunks(sstride * 4).take(h / 4).zip((&mut dst[doff..]).chunks_mut(dstride * 4)) {
666 for x in (0..w).step_by(4) {
667 let mut buf = [UnpackedPixel::default(); 16];
668 Self::get_block(&sstrip[x..], sstride, &mut buf);
669 let mut bstate = BlockState::default();
670 bstate.calc_stats(&buf);
672 let dst = &mut dstrip[x..];
673 if bstate.fill_dist <= fill_threshold ||
674 bstate.fill_dist <= bstate.clr2_dist {
675 let fill_val = bpainter.put_fill(&bstate, dst, dstride);
676 BlockWriter15::write_fill(bw, fill_val)?;
677 } else if bstate.clr8_dist < bstate.clr2_dist {
678 let clr8 = bpainter.put_clr8(&bstate, dst, dstride);
679 BlockWriter15::write_clr8(bw, bstate.clr8_flags, clr8)?;
681 let clr2 = bpainter.put_clr2(&bstate, dst, dstride);
682 BlockWriter15::write_clr2(bw, bstate.clr2_flags, clr2)?;
689 fn encode_inter_pal(bw: &mut ByteWriter, cur_frm: &mut NAVideoBuffer<u8>, in_frm: &NAVideoBuffer<u8>, prev_frm: &NAVideoBuffer<u8>, quality: u8, pal: &[UnpackedPixel; 256], ls: &LocalSearch) -> EncoderResult<bool> {
690 let (skip_threshold, fill_threshold) = map_quality_pal(quality);
691 let mut is_intra = true;
692 let src = in_frm.get_data();
693 let sstride = in_frm.get_stride(0);
694 let soff = in_frm.get_offset(0);
695 let (w, h) = in_frm.get_dimensions(0);
696 let rsrc = prev_frm.get_data();
697 let rstride = prev_frm.get_stride(0);
698 let roff = prev_frm.get_offset(0);
699 let dstride = cur_frm.get_stride(0);
700 let doff = cur_frm.get_offset(0);
701 let dst = cur_frm.get_data_mut().unwrap();
702 let mut skip_run = 0;
703 let bpainter = BlockPainterPal::new(ls);
704 for ((sstrip, rstrip), dstrip) in (&src[soff..]).chunks(sstride * 4).take(h / 4).zip((&rsrc[roff..]).chunks(rstride * 4)).zip((&mut dst[doff..]).chunks_mut(dstride * 4)) {
705 for x in (0..w).step_by(4) {
706 let mut buf = [UnpackedPixel::default(); 16];
707 let mut refbuf = [UnpackedPixel::default(); 16];
708 Self::get_block8(&sstrip[x..], sstride, &mut buf, pal);
709 Self::get_block8(&rstrip[x..], rstride, &mut refbuf, pal);
711 let mut skip_dist = 0;
712 for (pix, rpix) in buf.iter().zip(refbuf.iter()) {
713 skip_dist += dist_core(*rpix, pix);
715 if skip_dist <= skip_threshold {
718 for (dst, src) in dstrip[x..].chunks_mut(dstride).zip(rstrip[x..].chunks(rstride)).take(4) {
719 dst[..4].copy_from_slice(&src[..4]);
721 if skip_run == 1023 {
722 Self::write_skips(bw, skip_run)?;
728 let mut bstate = BlockState::new_pal();
729 bstate.calc_stats(&buf);
731 let dst = &mut dstrip[x..];
732 if skip_dist <= bstate.fill_dist && skip_dist * 2 <= bstate.clr2_dist {
735 for (dst, src) in dst.chunks_mut(dstride).zip(rstrip[x..].chunks(rstride)).take(4) {
736 dst[..4].copy_from_slice(&src[..4]);
738 if skip_run == 1023 {
739 Self::write_skips(bw, skip_run)?;
742 } else if bstate.fill_dist <= fill_threshold ||
743 bstate.fill_dist <= bstate.clr2_dist {
744 let fill_val = bpainter.put_fill(&bstate, dst, dstride);
746 Self::write_skips(bw, skip_run)?;
749 BlockWriterPal::write_fill(bw, fill_val)?;
750 } else if bstate.clr8_dist < bstate.clr2_dist {
751 let clr8 = bpainter.put_clr8(&bstate, dst, dstride);
753 Self::write_skips(bw, skip_run)?;
756 BlockWriterPal::write_clr8(bw, bstate.clr8_flags, clr8)?;
758 let clr2 = bpainter.put_clr2(&bstate, dst, dstride);
760 Self::write_skips(bw, skip_run)?;
763 BlockWriterPal::write_clr2(bw, bstate.clr2_flags, clr2)?;
768 Self::write_skips(bw, skip_run)?;
772 } //xxx: something for inter?
775 fn encode_intra_pal(bw: &mut ByteWriter, cur_frm: &mut NAVideoBuffer<u8>, in_frm: &NAVideoBuffer<u8>, quality: u8, pal: &[UnpackedPixel; 256], ls: &LocalSearch) -> EncoderResult<bool> {
776 let (_, fill_threshold) = map_quality_pal(quality);
777 let src = in_frm.get_data();
778 let sstride = in_frm.get_stride(0);
779 let soff = in_frm.get_offset(0);
780 let (w, h) = in_frm.get_dimensions(0);
781 let dstride = cur_frm.get_stride(0);
782 let doff = cur_frm.get_offset(0);
783 let dst = cur_frm.get_data_mut().unwrap();
784 let bpainter = BlockPainterPal::new(ls);
785 for (sstrip, dstrip) in (&src[soff..]).chunks(sstride * 4).take(h / 4).zip((&mut dst[doff..]).chunks_mut(dstride * 4)) {
786 for x in (0..w).step_by(4) {
787 let mut buf = [UnpackedPixel::default(); 16];
788 Self::get_block8(&sstrip[x..], sstride, &mut buf, pal);
789 let mut bstate = BlockState::new_pal();
790 bstate.calc_stats(&buf);
792 let dst = &mut dstrip[x..];
793 if bstate.fill_dist <= fill_threshold ||
794 bstate.fill_dist <= bstate.clr2_dist {
795 let fill_val = bpainter.put_fill(&bstate, dst, dstride);
796 BlockWriterPal::write_fill(bw, fill_val)?;
797 } else if bstate.clr8_dist < bstate.clr2_dist {
798 let clr8 = bpainter.put_clr8(&bstate, dst, dstride);
799 BlockWriterPal::write_clr8(bw, bstate.clr8_flags, clr8)?;
801 let clr2 = bpainter.put_clr2(&bstate, dst, dstride);
802 BlockWriterPal::write_clr2(bw, bstate.clr2_flags, clr2)?;
811 const RGB555_FORMAT: NAPixelFormaton = NAPixelFormaton {
812 model: ColorModel::RGB(RGBSubmodel::RGB), components: 3,
814 Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: 10, comp_offs: 0, next_elem: 2 }),
815 Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: 5, comp_offs: 0, next_elem: 2 }),
816 Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: 0, comp_offs: 0, next_elem: 2 }),
818 elem_size: 2, be: false, alpha: false, palette: false };
820 impl NAEncoder for MSVideo1Encoder {
821 fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters> {
822 match encinfo.format {
823 NACodecTypeInfo::None => {
824 Ok(EncodeParameters {
825 format: NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, true, RGB555_FORMAT)),
826 ..Default::default() })
828 NACodecTypeInfo::Audio(_) => Err(EncoderError::FormatError),
829 NACodecTypeInfo::Video(vinfo) => {
830 let oformat = if vinfo.format == PAL8_FORMAT { PAL8_FORMAT } else { RGB555_FORMAT };
831 let outinfo = NAVideoInfo::new((vinfo.width + 3) & !3, (vinfo.height + 3) & !3, true, oformat);
832 let mut ofmt = *encinfo;
833 ofmt.format = NACodecTypeInfo::Video(outinfo);
838 fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef> {
839 match encinfo.format {
840 NACodecTypeInfo::None => Err(EncoderError::FormatError),
841 NACodecTypeInfo::Audio(_) => Err(EncoderError::FormatError),
842 NACodecTypeInfo::Video(vinfo) => {
843 if vinfo.format != RGB555_FORMAT && vinfo.format != PAL8_FORMAT {
844 return Err(EncoderError::FormatError);
846 if ((vinfo.width | vinfo.height) & 3) != 0 {
847 return Err(EncoderError::FormatError);
850 let out_info = NAVideoInfo::new(vinfo.width, vinfo.height, true, vinfo.format);
851 let info = NACodecInfo::new("msvideo1", NACodecTypeInfo::Video(out_info), None);
852 let mut stream = NAStream::new(StreamType::Video, stream_id, info, encinfo.tb_num, encinfo.tb_den, 0);
853 stream.set_num(stream_id as usize);
854 let stream = stream.into_ref();
855 self.pal_mode = vinfo.format.is_paletted();
858 if self.pool15.prealloc_video(out_info, 2).is_err() {
859 return Err(EncoderError::AllocError);
862 if self.pool8.prealloc_video(out_info, 2).is_err() {
863 return Err(EncoderError::AllocError);
867 self.stream = Some(stream.clone());
868 self.quality = encinfo.quality;
874 fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()> {
875 let buf = frm.get_buffer();
876 if let Some(ref vbuf) = buf.get_vbuf16() {
878 return Err(EncoderError::InvalidParameters);
880 let mut cur_frm = self.pool15.get_free().unwrap();
881 let mut dbuf = Vec::with_capacity(4);
882 let mut gw = GrowableMemoryWriter::new_write(&mut dbuf);
883 let mut bw = ByteWriter::new(&mut gw);
884 if self.frmcount == 0 {
885 self.lastfrm15 = None;
887 let is_intra = if let Some(ref prev_buf) = self.lastfrm15 {
888 Self::encode_inter_rgb555(&mut bw, &mut cur_frm, vbuf, prev_buf, self.quality)?
890 Self::encode_intra_rgb555(&mut bw, &mut cur_frm, vbuf, self.quality)?
892 self.lastfrm15 = Some(cur_frm);
893 self.pkt = Some(NAPacket::new(self.stream.clone().unwrap(), frm.ts, is_intra, dbuf));
895 if self.frmcount == self.key_int {
899 } else if let Some(ref vbuf) = buf.get_vbuf() {
901 return Err(EncoderError::InvalidParameters);
903 let src = vbuf.get_data();
904 let pal = &src[vbuf.get_offset(1)..];
905 let mut pal_changed = false;
906 for (cur_pal, new_pal) in self.pal.iter_mut().zip(pal.chunks_exact(3)) {
907 let (cur_clr, luma) = cur_pal.split_at_mut(3);
908 let new_clr = [u16::from(new_pal[0]), u16::from(new_pal[1]), u16::from(new_pal[2])];
909 if cur_clr != &new_clr {
911 cur_clr.copy_from_slice(&new_clr);
912 luma[0] = rgb2y(cur_clr[0], cur_clr[1], cur_clr[2]);
917 self.ls.recalculate(&self.pal);
920 let mut cur_frm = self.pool8.get_free().unwrap();
921 let mut dbuf = Vec::with_capacity(4);
922 let mut gw = GrowableMemoryWriter::new_write(&mut dbuf);
923 let mut bw = ByteWriter::new(&mut gw);
924 if self.frmcount == 0 {
925 self.lastfrm8 = None;
927 let is_intra = if let Some(ref prev_buf) = self.lastfrm8 {
928 Self::encode_inter_pal(&mut bw, &mut cur_frm, vbuf, prev_buf, self.quality, &self.pal, &self.ls)?
930 Self::encode_intra_pal(&mut bw, &mut cur_frm, vbuf, self.quality, &self.pal, &self.ls)?
932 self.lastfrm8 = Some(cur_frm);
933 let mut pkt = NAPacket::new(self.stream.clone().unwrap(), frm.ts, is_intra, dbuf);
935 let mut epal = [0; 1024];
936 for (dst, src) in epal.chunks_mut(4).zip(self.pal.iter()) {
937 dst[0] = src[0] as u8;
938 dst[1] = src[1] as u8;
939 dst[2] = src[2] as u8;
941 pkt.add_side_data(NASideData::Palette(true, Arc::new(epal)));
943 self.pkt = Some(pkt);
945 if self.frmcount == self.key_int {
950 Err(EncoderError::InvalidParameters)
953 fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>> {
955 std::mem::swap(&mut self.pkt, &mut npkt);
958 fn flush(&mut self) -> EncoderResult<()> {
964 const ENCODER_OPTS: &[NAOptionDefinition] = &[
966 name: KEYFRAME_OPTION, description: KEYFRAME_OPTION_DESC,
967 opt_type: NAOptionDefinitionType::Int(Some(0), Some(128)) },
970 impl NAOptionHandler for MSVideo1Encoder {
971 fn get_supported_options(&self) -> &[NAOptionDefinition] { ENCODER_OPTS }
972 fn set_options(&mut self, options: &[NAOption]) {
973 for option in options.iter() {
974 for opt_def in ENCODER_OPTS.iter() {
975 if opt_def.check(option).is_ok() {
978 if let NAValue::Int(intval) = option.value {
979 self.key_int = intval as u8;
988 fn query_option_value(&self, name: &str) -> Option<NAValue> {
990 KEYFRAME_OPTION => Some(NAValue::Int(i64::from(self.key_int))),
996 pub fn get_encoder() -> Box<dyn NAEncoder + Send> {
997 Box::new(MSVideo1Encoder::new())
1002 use nihav_core::codecs::*;
1003 use nihav_core::demuxers::*;
1004 use nihav_core::muxers::*;
1006 use nihav_commonfmt::*;
1007 use nihav_codec_support::test::enc_video::*;
1008 use super::RGB555_FORMAT;
1011 fn test_ms_video1_encoder_pal() {
1012 let mut dmx_reg = RegisteredDemuxers::new();
1013 generic_register_all_demuxers(&mut dmx_reg);
1014 let mut dec_reg = RegisteredDecoders::new();
1015 generic_register_all_decoders(&mut dec_reg);
1016 ms_register_all_decoders(&mut dec_reg);
1017 let mut mux_reg = RegisteredMuxers::new();
1018 generic_register_all_muxers(&mut mux_reg);
1019 let mut enc_reg = RegisteredEncoders::new();
1020 ms_register_all_encoders(&mut enc_reg);
1022 // sample: https://samples.mplayerhq.hu/V-codecs/RLE/mplayer-msrle-4bit.avi
1023 let dec_config = DecoderTestParams {
1025 in_name: "assets/MS/mplayer-msrle-4bit.avi",
1026 stream_type: StreamType::Video,
1030 let enc_config = EncoderTestParams {
1032 enc_name: "msvideo1",
1033 out_name: "msvideo1pal.avi",
1036 let dst_vinfo = NAVideoInfo {
1039 format: PAL8_FORMAT,
1043 let enc_params = EncodeParameters {
1044 format: NACodecTypeInfo::Video(dst_vinfo),
1051 //test_encoding_to_file(&dec_config, &enc_config, enc_params, &[]);
1052 test_encoding_md5(&dec_config, &enc_config, enc_params, &[],
1053 &[0x27a9db38, 0x74f1000a, 0x38818c05, 0x99d692ba]);
1057 fn test_ms_video1_encoder_rgb555() {
1058 let mut dmx_reg = RegisteredDemuxers::new();
1059 generic_register_all_demuxers(&mut dmx_reg);
1060 let mut dec_reg = RegisteredDecoders::new();
1061 generic_register_all_decoders(&mut dec_reg);
1062 ms_register_all_decoders(&mut dec_reg);
1063 let mut mux_reg = RegisteredMuxers::new();
1064 generic_register_all_muxers(&mut mux_reg);
1065 let mut enc_reg = RegisteredEncoders::new();
1066 ms_register_all_encoders(&mut enc_reg);
1068 // sample: https://samples.mplayerhq.hu/V-codecs/UCOD/TalkingHead_352x288.avi
1069 let dec_config = DecoderTestParams {
1071 in_name: "assets/Misc/TalkingHead_352x288.avi",
1072 stream_type: StreamType::Video,
1076 let enc_config = EncoderTestParams {
1078 enc_name: "msvideo1",
1079 out_name: "msvideo1.avi",
1082 let dst_vinfo = NAVideoInfo {
1085 format: RGB555_FORMAT,
1089 let enc_params = EncodeParameters {
1090 format: NACodecTypeInfo::Video(dst_vinfo),
1097 //test_encoding_to_file(&dec_config, &enc_config, enc_params, &[]);
1098 test_encoding_md5(&dec_config, &enc_config, enc_params, &[],
1099 &[0xe570a206, 0xc223063f, 0x44a0b70e, 0xa71fed1f]);