aboutsummaryrefslogtreecommitdiffstats
path: root/nihav-ms/src/codecs/msvideo1enc.rs
blob: c63b985109b1d343ba09b91da5797c2b2341ade5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
use nihav_core::codecs::*;
use nihav_core::io::byteio::*;

type UnpackedPixel = [u16; 4];

fn map_quality(quality: u8) -> (u32, u32) {
    if quality == 0 {
        (0, 0)
    } else {
        let skip_threshold = (10 - (u32::from(quality) / 10).min(10)) * 8;
        let fill_threshold = (10 - (u32::from(quality) / 10).min(10)) * 16;
        (skip_threshold, fill_threshold)
    }
}

trait PixelOps {
    fn unpack(&self) -> UnpackedPixel;
    fn dist<T: PixelOps>(&self, val: T) -> u32 {
        dist_core(self.unpack(), &val.unpack())
    }
}

impl PixelOps for u16 {
    fn unpack(&self) -> UnpackedPixel {
        let val = *self;
        let r = (val >> 10) & 0x1F;
        let g = (val >>  5) & 0x1F;
        let b =  val        & 0x1F;
        [r, g, b, rgb2y(r, g, b)]
    }
}

fn dist_core(val: UnpackedPixel, other: &UnpackedPixel) -> u32 {
    let sum = val.iter().zip(other.iter()).take(3).fold(0i32,
            |acc, (&a, &b)| {
                let diff = i32::from(a) - i32::from(b);
                acc + diff * diff
            });
    sum as u32
}


fn rgb2y(r: u16, g: u16, b: u16) -> u16 {
    (r * 77 + g * 150 + b * 29) >> 8
}

fn pack_rgb555(val: UnpackedPixel) -> u16 {
    (val[0] << 10) | (val[1] << 5) | val[2]
}

#[derive(Default)]
struct PixelAverage {
    sum:    UnpackedPixel,
    count:  u16,
}

impl PixelAverage {
    fn new() -> Self { Self::default() }
    fn add(&mut self, val: &UnpackedPixel) {
        for (dst, &src) in self.sum.iter_mut().zip(val.iter()) {
            *dst += src;
        }
        self.count += 1;
    }
    fn get_avg(&self) -> UnpackedPixel {
        if self.count > 0 {
            let mut ret = self.sum;
            for el in ret.iter_mut() {
                *el /= self.count;
            }
            ret
        } else {
            [0; 4]
        }
    }
}

macro_rules! quant_template {
    ($name:ident, $N:expr) => {
        fn $name(pix: &[UnpackedPixel; $N]) -> ([UnpackedPixel; 2], u16, u32) {
            let mut avg = PixelAverage::new();
            let mut maxv = [0; 4];
            let mut minv = [255; 4];
            for src in pix.iter() {
                avg.add(src);
                for ((maxv, minv), &comp) in maxv.iter_mut().zip(minv.iter_mut()).zip(src.iter()) {
                    *maxv = (*maxv).max(comp);
                    *minv = (*minv).min(comp);
                }
            }
            let avg = avg.get_avg();

            let mut best_axis = 3;
            let mut best_dist = maxv[3] - minv[3];
            for (comp_no, (&minval, &maxval)) in minv.iter().zip(maxv.iter()).enumerate().take(3) {
                if maxval - minval > best_dist {
                    best_axis = comp_no;
                    best_dist = maxval - minval;
                }
            }
            if best_dist == 0 {
                let mut dist = 0;
                for el in pix.iter() {
                    dist += dist_core(avg, el);
                }
                return ([avg; 2], 0, dist);
            }

            let mut avg1 = PixelAverage::new();
            let mut avg2 = PixelAverage::new();
            let mut mask = 0;
            let mut mask_bit = 1;
            for clr in pix.iter() {
                if clr[best_axis] > avg[best_axis] {
                    avg2.add(clr);
                    mask |= mask_bit;
                } else {
                    avg1.add(clr);
                }
                mask_bit <<= 1;
            }

            let clr0 = avg1.get_avg();
            let clr1 = avg2.get_avg();
            let mut dist = 0;
            for clr in pix.iter() {
                let dist0 = dist_core(clr0, clr);
                let dist1 = dist_core(clr1, clr);
                dist += dist0.min(dist1);
            }
            ([clr0, clr1], mask, dist)
        }
    }
}

quant_template!(quant2_16pix, 16);
quant_template!(quant2_4pix, 4);

#[derive(Default)]
struct BlockState {
    fill_dist:  u32,
    fill_val:   UnpackedPixel,
    clr2_dist:  u32,
    clr2_flags: u16,
    clr2:       [UnpackedPixel; 2],
    clr8_dist:  u32,
    clr8_flags: u16,
    clr8:       [[UnpackedPixel; 2]; 4],
    pal_mode:   bool,
}

impl BlockState {
    fn set_fill_val(&mut self, val: UnpackedPixel) {
        self.fill_val = val;
        if !self.pal_mode {
            self.fill_val[0] &= !1;
        }
    }
    fn calc_clrs(buf: &[UnpackedPixel; 16]) -> (Option<UnpackedPixel>, Option<UnpackedPixel>) {
        let     clr0 = buf[0];
        let mut clr1 = clr0;
        let mut single = true;
        for &pix in buf[1..].iter() {
            if pix != clr0 {
                if single {
                    clr1 = pix;
                    single = false;
                } else if pix != clr1 {
                    return (None, None);
                }
            }
        }
        if !single {
            (Some(clr0), Some(clr1))
        } else {
            (Some(clr0), None)
        }
    }
    fn calc_stats(&mut self, buf: &[UnpackedPixel; 16]) {
        let mut filled = false;
        let mut two_clr = false;
        match Self::calc_clrs(buf) {
            (Some(clr0), Some(clr1)) => {
                self.clr2[0] = clr0;
                self.clr2[1] = clr1;
                two_clr = true;
            },
            (Some(clr0), None) => {
                self.clr2[0] = clr0;
                self.clr2[1] = clr0;
                self.set_fill_val(buf[0]);
                filled = true;
                two_clr = true;
            },
            _ => {},
        };
        self.fill_dist = 0;
        if !filled {
            let mut avg = PixelAverage::new();
            for pix in buf.iter() {
                avg.add(pix);
            }
            self.set_fill_val(avg.get_avg());
            for pix in buf.iter() {
                self.fill_dist += dist_core(self.fill_val, pix);
            }
        }
        if self.fill_dist == 0 {
            self.clr2_dist = std::u32::MAX;
            self.clr8_dist = std::u32::MAX;
            return;
        }

        self.clr2_flags = 0u16;
        if two_clr {
            let mut mask = 1;
            self.clr2_dist = 0;
            for &pix in buf.iter() {
                if pix == self.clr2[0] {
                    self.clr2_flags |= mask;
                } else {
                }
                mask <<= 1;
            }
            if (self.clr2_flags & 0x8000) != 0 {
                self.clr2_flags = !self.clr2_flags;
                self.clr2.swap(0, 1);
            }
        } else {
            let (clrs, mask, dist) = quant2_16pix(&buf);
            self.clr2 = clrs;
            self.clr2_flags = mask;
            self.clr2_dist = dist;
            if (self.clr2_flags & 0x8000) != 0 {
                self.clr2_flags = !self.clr2_flags;
                self.clr2.swap(0, 1);
            }
        }
        if self.clr2_dist == 0 {
            self.clr8_dist = std::u32::MAX;
            return;
        }

        self.clr8 = [[UnpackedPixel::default(); 2]; 4];
        self.clr8_flags = 0;
        self.clr8_dist = 0;
        for i in 0..4 {
            let off = (i & 1) * 2 + (i & 2) * 4;
            let src2 = [buf[off], buf[off + 1], buf[off + 4], buf[off + 5]];
            let (clrs, mask, dist) = quant2_4pix(&src2);
            self.clr8[i] = clrs;
            self.clr8_flags |= mask << (i * 4);
            self.clr8_dist += dist;
        }
        if (self.clr8_flags & 0x8000) != 0 {
            self.clr8_flags ^= 0xF000;
            self.clr8[3].swap(0, 1);
        }
    }
}

struct BlockPainter15 {}
impl BlockPainter15 {
    fn new() -> Self { Self{} }
    fn put_fill(&self, bstate: &BlockState, dst: &mut [u16], dstride: usize) -> u16 {
        let fill_val = pack_rgb555(bstate.fill_val);
        for line in dst.chunks_mut(dstride) {
            for i in 0..4 {
                line[i] = fill_val;
            }
        }
        fill_val
    }
    fn put_clr2(&self, bstate: &BlockState, dst: &mut [u16], dstride: usize) -> [u16; 2] {
        let clr2 = [pack_rgb555(bstate.clr2[0]), pack_rgb555(bstate.clr2[1])];
        for j in 0..4 {
            for i in 0..4 {
                if (bstate.clr2_flags & (1 << (i + j * 4))) == 0 {
                    dst[i + j * dstride] = clr2[0];
                } else {
                    dst[i + j * dstride] = clr2[1];
                }
            }
        }
        clr2
    }
    fn put_clr8(&self, bstate: &BlockState, dst: &mut [u16], dstride: usize) -> [[u16; 4]; 4] {
        let mut clr8 = [[0; 4]; 4];
        for (dst, src) in clr8.iter_mut().zip(bstate.clr8.iter()) {
            for (dst, &src) in dst.iter_mut().zip(src.iter()) {
                *dst = pack_rgb555(src);
            }
        }
        for i in 0..4 {
            let off = (i & 1) * 2 + (i & 2) * dstride;
            let cur_flg = (bstate.clr8_flags >> (i * 4)) & 0xF;
            dst[off]               = clr8[i][( !cur_flg       & 1) as usize];
            dst[off + 1]           = clr8[i][((!cur_flg >> 1) & 1) as usize];
            dst[off +     dstride] = clr8[i][((!cur_flg >> 2) & 1) as usize];
            dst[off + 1 + dstride] = clr8[i][((!cur_flg >> 3) & 1) as usize];
        }
        clr8
    }
}

struct BlockWriter15 {}
impl BlockWriter15 {
    fn write_fill(bw: &mut ByteWriter, fill_val: u16) -> EncoderResult<()> {
        bw.write_u16le(fill_val | 0x8000)?;
        Ok(())
    }
    fn write_clr2(bw: &mut ByteWriter, clr2_flags: u16, clr2: [u16; 2]) -> EncoderResult<()> {
        bw.write_u16le(clr2_flags)?;
        bw.write_u16le(clr2[0])?;
        bw.write_u16le(clr2[1])?;
        Ok(())
    }
    fn write_clr8(bw: &mut ByteWriter, clr8_flags: u16, clr8: &[[u16; 4]; 4]) -> EncoderResult<()> {
        bw.write_u16le(clr8_flags)?;
        bw.write_u16le(clr8[0][0] | 0x8000)?;
        bw.write_u16le(clr8[0][1])?;
        bw.write_u16le(clr8[1][0])?;
        bw.write_u16le(clr8[1][1])?;
        bw.write_u16le(clr8[2][0])?;
        bw.write_u16le(clr8[2][1])?;
        bw.write_u16le(clr8[3][0])?;
        bw.write_u16le(clr8[3][1])?;
        Ok(())
    }
}

struct MSVideo1Encoder {
    stream:     Option<NAStreamRef>,
    pkt:        Option<NAPacket>,
    pool:       NAVideoBufferPool<u16>,
    lastfrm:    Option<NAVideoBufferRef<u16>>,
    quality:    u8,
    frmcount:   u8,
    key_int:    u8,
}

impl MSVideo1Encoder {
    fn new() -> Self {
        Self {
            stream:     None,
            pkt:        None,
            pool:       NAVideoBufferPool::new(2),
            lastfrm:    None,
            quality:    0,
            frmcount:   0,
            key_int:    25,
        }
    }
    fn get_block(src: &[u16], sstride: usize, buf: &mut [UnpackedPixel; 16]) {
        for (line, dst) in src.chunks(sstride).zip(buf.chunks_mut(4)) {
            for (dst, src) in dst.iter_mut().zip(line.iter()) {
                *dst = src.unpack();
            }
        }
    }
    fn write_skips(bw: &mut ByteWriter, skips: usize) -> EncoderResult<()> {
        bw.write_u16le((skips as u16) | 0x8400)?;
        Ok(())
    }
    fn encode_inter(bw: &mut ByteWriter, cur_frm: &mut NAVideoBuffer<u16>, in_frm: &NAVideoBuffer<u16>, prev_frm: &NAVideoBuffer<u16>, quality: u8) -> EncoderResult<bool> {
        let (skip_threshold, fill_threshold) = map_quality(quality);
        let mut is_intra = true;
        let src = in_frm.get_data();
        let sstride = in_frm.get_stride(0);
        let soff = in_frm.get_offset(0);
        let (w, h) = in_frm.get_dimensions(0);
        let rsrc = prev_frm.get_data();
        let rstride = prev_frm.get_stride(0);
        let roff = prev_frm.get_offset(0);
        let dstride = cur_frm.get_stride(0);
        let doff = cur_frm.get_offset(0);
        let dst = cur_frm.get_data_mut().unwrap();
        let mut skip_run = 0;
        let bpainter = BlockPainter15::new();
        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)) {
            for x in (0..w).step_by(4) {
                let mut buf = [UnpackedPixel::default(); 16];
                let mut refbuf = [UnpackedPixel::default(); 16];
                Self::get_block(&sstrip[x..], sstride, &mut buf);
                Self::get_block(&rstrip[x..], rstride, &mut refbuf);

                let mut skip_dist = 0;
                for (pix, rpix) in buf.iter().zip(refbuf.iter()) {
                    skip_dist += dist_core(*rpix, pix);
                }
                if skip_dist <= skip_threshold {
                    skip_run += 1;
                    is_intra = false;
                    if skip_threshold > 0 {
                        for (dst, src) in dstrip[x..].chunks_mut(dstride).zip(rstrip[x..].chunks(rstride)).take(4) {
                            dst[..4].copy_from_slice(&src[..4]);
                        }
                    }
                    if skip_run == 1023 {
                        Self::write_skips(bw, skip_run)?;
                        skip_run = 0;
                    }
                    continue;
                }

                let mut bstate = BlockState::default();
                bstate.calc_stats(&buf);

                let dst = &mut dstrip[x..];
                if skip_dist <= bstate.fill_dist {
                    skip_run += 1;
                    is_intra = false;
                    for (dst, src) in dst.chunks_mut(dstride).zip(rstrip[x..].chunks(rstride)).take(4) {
                        dst[..4].copy_from_slice(&src[..4]);
                    }
                    if skip_run == 1023 {
                        Self::write_skips(bw, skip_run)?;
                        skip_run = 0;
                    }
                } else if bstate.fill_dist <= fill_threshold ||
                          bstate.fill_dist <= bstate.clr2_dist {
                    let fill_val = bpainter.put_fill(&bstate, dst, dstride);
                    if skip_run != 0 {
                        Self::write_skips(bw, skip_run)?;
                        skip_run = 0;
                    }
                    BlockWriter15::write_fill(bw, fill_val)?;
                } else if bstate.clr8_dist < bstate.clr2_dist {
                    let clr8 = bpainter.put_clr8(&bstate, dst, dstride);
                    if skip_run != 0 {
                        Self::write_skips(bw, skip_run)?;
                        skip_run = 0;
                    }
                    BlockWriter15::write_clr8(bw, bstate.clr8_flags, &clr8)?;
                } else {
                    let clr2 = bpainter.put_clr2(&bstate, dst, dstride);
                    if skip_run != 0 {
                        Self::write_skips(bw, skip_run)?;
                        skip_run = 0;
                    }
                    BlockWriter15::write_clr2(bw, bstate.clr2_flags, clr2)?;
                }
            }
        }
        if skip_run != 0 {
            Self::write_skips(bw, skip_run)?;
        }
        if is_intra {
            bw.write_u16le(0)?;
        } //xxx: something for inter?
        Ok(is_intra)
    }
    fn encode_intra(bw: &mut ByteWriter, cur_frm: &mut NAVideoBuffer<u16>, in_frm: &NAVideoBuffer<u16>, quality: u8) -> EncoderResult<bool> {
        let (_, fill_threshold) = map_quality(quality);
        let src = in_frm.get_data();
        let sstride = in_frm.get_stride(0);
        let soff = in_frm.get_offset(0);
        let (w, h) = in_frm.get_dimensions(0);
        let dstride = cur_frm.get_stride(0);
        let doff = cur_frm.get_offset(0);
        let dst = cur_frm.get_data_mut().unwrap();
        let bpainter = BlockPainter15::new();
        for (sstrip, dstrip) in (&src[soff..]).chunks(sstride * 4).take(h / 4).zip((&mut dst[doff..]).chunks_mut(dstride * 4)) {
            for x in (0..w).step_by(4) {
                let mut buf = [UnpackedPixel::default(); 16];
                Self::get_block(&sstrip[x..], sstride, &mut buf);
                let mut bstate = BlockState::default();
                bstate.calc_stats(&buf);

                let dst = &mut dstrip[x..];
                if bstate.fill_dist <= fill_threshold ||
                   bstate.fill_dist <= bstate.clr2_dist {
                    let fill_val = bpainter.put_fill(&bstate, dst, dstride);
                    BlockWriter15::write_fill(bw, fill_val)?;
                } else if bstate.clr8_dist < bstate.clr2_dist {
                    let clr8 = bpainter.put_clr8(&bstate, dst, dstride);
                    BlockWriter15::write_clr8(bw, bstate.clr8_flags, &clr8)?;
                } else {
                    let clr2 = bpainter.put_clr2(&bstate, dst, dstride);
                    BlockWriter15::write_clr2(bw, bstate.clr2_flags, clr2)?;
                }
            }
        }
        bw.write_u16le(0)?;
        Ok(true)
    }
}

const RGB555_FORMAT: NAPixelFormaton = NAPixelFormaton {
        model: ColorModel::RGB(RGBSubmodel::RGB), components: 3,
        comp_info: [
            Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: 10, comp_offs: 0, next_elem: 2 }),
            Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 5, shift:  5, comp_offs: 0, next_elem: 2 }),
            Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 5, shift:  0, comp_offs: 0, next_elem: 2 }),
            None, None],
        elem_size: 2, be: false, alpha: false, palette: false };

impl NAEncoder for MSVideo1Encoder {
    fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters> {
        match encinfo.format {
            NACodecTypeInfo::None => {
                Ok(EncodeParameters {
                    format: NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, true, RGB555_FORMAT)),
                    ..Default::default() })
            },
            NACodecTypeInfo::Audio(_) => Err(EncoderError::FormatError),
            NACodecTypeInfo::Video(vinfo) => {
                let outinfo = NAVideoInfo::new((vinfo.width + 3) & !3, (vinfo.height + 3) & !3, true, RGB555_FORMAT);
                let mut ofmt = *encinfo;
                ofmt.format = NACodecTypeInfo::Video(outinfo);
                Ok(ofmt)
            }
        }
    }
    fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef> {
        match encinfo.format {
            NACodecTypeInfo::None => Err(EncoderError::FormatError),
            NACodecTypeInfo::Audio(_) => Err(EncoderError::FormatError),
            NACodecTypeInfo::Video(vinfo) => {
                if vinfo.format != RGB555_FORMAT {
                    return Err(EncoderError::FormatError);
                }
                if ((vinfo.width | vinfo.height) & 3) != 0 {
                    return Err(EncoderError::FormatError);
                }

                let out_info = NAVideoInfo::new(vinfo.width, vinfo.height, true, RGB555_FORMAT);
                let info = NACodecInfo::new("msvideo1", NACodecTypeInfo::Video(out_info), None);
                let mut stream = NAStream::new(StreamType::Video, stream_id, info, encinfo.tb_num, encinfo.tb_den, 0);
                stream.set_num(stream_id as usize);
                let stream = stream.into_ref();
                if self.pool.prealloc_video(out_info, 2).is_err() {
                    return Err(EncoderError::AllocError);
                }

                self.stream = Some(stream.clone());
                self.quality = encinfo.quality;

                Ok(stream)
            },
        }
    }
    fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()> {
        let buf = frm.get_buffer();
        if let Some(ref vbuf) = buf.get_vbuf16() {
            let mut cur_frm = self.pool.get_free().unwrap();
            let mut dbuf = Vec::with_capacity(4);
            let mut gw   = GrowableMemoryWriter::new_write(&mut dbuf);
            let mut bw   = ByteWriter::new(&mut gw);
            if self.frmcount == 0 {
                self.lastfrm = None;
            }
            let is_intra = if let Some(ref prev_buf) = self.lastfrm {
                    Self::encode_inter(&mut bw, &mut cur_frm, vbuf, prev_buf, self.quality)?
                } else {
                    Self::encode_intra(&mut bw, &mut cur_frm, vbuf, self.quality)?
                };
            self.lastfrm = Some(cur_frm);
            self.pkt = Some(NAPacket::new(self.stream.clone().unwrap(), frm.ts, is_intra, dbuf));
            self.frmcount += 1;
            if self.frmcount == self.key_int {
                self.frmcount = 0;
            }
            Ok(())
        } else {
            Err(EncoderError::InvalidParameters)
        }
    }
    fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>> {
        let mut npkt = None;
        std::mem::swap(&mut self.pkt, &mut npkt);
        Ok(npkt)
    }
    fn flush(&mut self) -> EncoderResult<()> {
        self.frmcount = 0;
        Ok(())
    }
}

const ENCODER_OPTS: &[NAOptionDefinition] = &[
    NAOptionDefinition {
        name: KEYFRAME_OPTION, description: KEYFRAME_OPTION_DESC,
        opt_type: NAOptionDefinitionType::Int(Some(0), Some(128)) },
];

impl NAOptionHandler for MSVideo1Encoder {
    fn get_supported_options(&self) -> &[NAOptionDefinition] { ENCODER_OPTS }
    fn set_options(&mut self, options: &[NAOption]) {
        for option in options.iter() {
            for opt_def in ENCODER_OPTS.iter() {
                if opt_def.check(option).is_ok() {
                    match option.name {
                        KEYFRAME_OPTION => {
                            if let NAValue::Int(intval) = option.value {
                                self.key_int = intval as u8;
                            }
                        },
                        _ => {},
                    };
                }
            }
        }
    }
    fn query_option_value(&self, name: &str) -> Option<NAValue> {
        match name {
            KEYFRAME_OPTION => Some(NAValue::Int(i64::from(self.key_int))),
            _ => None,
        }
    }
}

pub fn get_encoder() -> Box<dyn NAEncoder + Send> {
    Box::new(MSVideo1Encoder::new())
}

#[cfg(test)]
mod test {
    use nihav_core::codecs::*;
    use nihav_core::demuxers::*;
    use nihav_core::muxers::*;
    use crate::*;
    use nihav_commonfmt::*;
    use nihav_codec_support::test::enc_video::*;
    use super::RGB555_FORMAT;

    #[test]
    fn test_ms_video1_encoder() {
        let mut dmx_reg = RegisteredDemuxers::new();
        generic_register_all_demuxers(&mut dmx_reg);
        let mut dec_reg = RegisteredDecoders::new();
        generic_register_all_decoders(&mut dec_reg);
        ms_register_all_decoders(&mut dec_reg);
        let mut mux_reg = RegisteredMuxers::new();
        generic_register_all_muxers(&mut mux_reg);
        let mut enc_reg = RegisteredEncoders::new();
        ms_register_all_encoders(&mut enc_reg);

        // sample: https://samples.mplayerhq.hu/V-codecs/UCOD/TalkingHead_352x288.avi
        let dec_config = DecoderTestParams {
                demuxer:        "avi",
                in_name:        "assets/Misc/TalkingHead_352x288.avi",
                stream_type:    StreamType::Video,
                limit:          Some(3),
                dmx_reg, dec_reg,
            };
        let enc_config = EncoderTestParams {
                muxer:          "avi",
                enc_name:       "msvideo1",
                out_name:       "msvideo1.avi",
                mux_reg, enc_reg,
            };
        let dst_vinfo = NAVideoInfo {
                width:   0,
                height:  0,
                format:  RGB555_FORMAT,
                flipped: true,
                bits:    16,
            };
        let enc_params = EncodeParameters {
                format:  NACodecTypeInfo::Video(dst_vinfo),
                quality: 80,
                bitrate: 0,
                tb_num:  0,
                tb_den:  0,
                flags:   0,
            };
        //test_encoding_to_file(&dec_config, &enc_config, enc_params, &[]);
        test_encoding_md5(&dec_config, &enc_config, enc_params, &[],
                          &[0x35d95583, 0xb7431be7, 0xad490677, 0x968a1d84]);
    }
}