oximedia-codec 0.1.7

Video codec implementations for OxiMedia
Documentation
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! VP9 Symbol decoding with boolean arithmetic decoder.
//!
//! This module provides symbol decoding functions that use the boolean
//! arithmetic decoder to decode various syntax elements with probability-based
//! contexts, including partitions, modes, motion vectors, and segmentation.

#![forbid(unsafe_code)]
#![allow(dead_code)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::similar_names)]
#![allow(clippy::many_single_char_names)]
#![allow(clippy::fn_params_excessive_bools)]

use super::bitstream::BoolDecoder;
use super::compressed::ReferenceMode;
use super::inter::{CompoundMode, InterMode, RefFrameType};
use super::intra::IntraMode;
use super::mv::{MotionVector, MvClass, MvJoint};
use super::partition::{Partition, TxSize};
use super::probability::{FrameContext, Prob, INTRA_MODES};
use super::segmentation::MAX_SEGMENTS;
use crate::error::{CodecError, CodecResult};

// =============================================================================
// Boolean Decoder Extension
// =============================================================================

impl BoolDecoder {
    /// Initializes the decoder with data.
    pub fn init(&mut self, data: &[u8], offset: usize) -> CodecResult<()> {
        if offset + 2 > data.len() {
            return Err(CodecError::InvalidBitstream(
                "Not enough data for boolean decoder".into(),
            ));
        }

        self.value = (u32::from(data[offset]) << 8) | u32::from(data[offset + 1]);
        self.range = 255;
        self.count = -8;
        Ok(())
    }

    /// Reads a single bit with probability.
    #[allow(clippy::cast_possible_wrap)]
    pub fn read_bool(&mut self, data: &[u8], offset: &mut usize, prob: Prob) -> CodecResult<bool> {
        let split = 1 + (((self.range - 1) * u32::from(prob)) >> 8);
        let big_split = split << 8;

        let bit = if self.value >= big_split {
            self.range -= split;
            self.value -= big_split;
            true
        } else {
            self.range = split;
            false
        };

        // Renormalize
        while self.range < 128 {
            self.range <<= 1;
            self.value <<= 1;
            self.count += 1;

            if self.count == 0 {
                self.count = -8;
                if *offset < data.len() {
                    self.value |= u32::from(data[*offset]);
                    *offset += 1;
                }
            }
        }

        Ok(bit)
    }

    /// Reads a literal bit.
    pub fn read_literal(&mut self, data: &[u8], offset: &mut usize) -> CodecResult<bool> {
        self.read_bool(data, offset, 128)
    }

    /// Reads multiple literal bits as u32.
    pub fn read_literal_bits(
        &mut self,
        data: &[u8],
        offset: &mut usize,
        bits: u8,
    ) -> CodecResult<u32> {
        let mut value = 0u32;
        for _ in 0..bits {
            value = (value << 1) | u32::from(self.read_literal(data, offset)?);
        }
        Ok(value)
    }

    /// Reads a symbol from a tree using probabilities.
    pub fn read_tree(
        &mut self,
        data: &[u8],
        offset: &mut usize,
        tree: &[i8],
        probs: &[Prob],
    ) -> CodecResult<i8> {
        let mut index = 0usize;

        loop {
            let prob_index = (index >> 1) as usize;
            if prob_index >= probs.len() {
                return Err(CodecError::InvalidBitstream(
                    "Prob index out of bounds".into(),
                ));
            }

            let bit = self.read_bool(data, offset, probs[prob_index])?;
            index = (index << 1) | (usize::from(bit));

            let tree_index = index as usize;
            if tree_index >= tree.len() {
                return Err(CodecError::InvalidBitstream(
                    "Tree index out of bounds".into(),
                ));
            }

            let val = tree[tree_index];
            if val <= 0 {
                return Ok(-val);
            }
            index = val as usize;
        }
    }
}

// =============================================================================
// Symbol Decoder
// =============================================================================

/// Symbol decoder for VP9 entropy coding.
#[derive(Debug)]
pub struct SymbolDecoder {
    /// Boolean arithmetic decoder.
    bool_decoder: BoolDecoder,
    /// Current byte offset in data.
    offset: usize,
}

impl Default for SymbolDecoder {
    fn default() -> Self {
        Self::new()
    }
}

impl SymbolDecoder {
    /// Creates a new symbol decoder.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            bool_decoder: BoolDecoder::new(),
            offset: 0,
        }
    }

    /// Initializes the decoder with compressed data.
    pub fn init(&mut self, data: &[u8], offset: usize) -> CodecResult<()> {
        self.offset = offset;
        self.bool_decoder.init(data, offset)?;
        self.offset += 2; // Skip initial bytes
        Ok(())
    }

    /// Returns the current byte offset.
    #[must_use]
    pub const fn offset(&self) -> usize {
        self.offset
    }

    // =========================================================================
    // Partition Decoding
    // =========================================================================

    /// Decodes a partition type.
    pub fn decode_partition(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        context: usize,
    ) -> CodecResult<Partition> {
        let probs = ctx.probs.get_partition_probs(context);

        // Read partition tree
        let has_rows = self
            .bool_decoder
            .read_bool(data, &mut self.offset, probs[0])?;
        if !has_rows {
            return Ok(Partition::None);
        }

        let has_cols = self
            .bool_decoder
            .read_bool(data, &mut self.offset, probs[1])?;
        if !has_cols {
            return Ok(Partition::Horz);
        }

        let split = self
            .bool_decoder
            .read_bool(data, &mut self.offset, probs[2])?;
        if split {
            Ok(Partition::Split)
        } else {
            Ok(Partition::Vert)
        }
    }

    // =========================================================================
    // Skip Decoding
    // =========================================================================

    /// Decodes skip flag.
    pub fn decode_skip(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        context: usize,
    ) -> CodecResult<bool> {
        let prob = ctx.probs.get_skip_prob(context);
        self.bool_decoder.read_bool(data, &mut self.offset, prob)
    }

    // =========================================================================
    // Intra/Inter Decoding
    // =========================================================================

    /// Decodes intra/inter flag.
    pub fn decode_is_inter(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        context: usize,
    ) -> CodecResult<bool> {
        let prob = ctx.probs.get_intra_inter_prob(context);
        self.bool_decoder.read_bool(data, &mut self.offset, prob)
    }

    // =========================================================================
    // Intra Mode Decoding
    // =========================================================================

    /// Decodes intra Y mode for keyframes.
    pub fn decode_intra_y_mode_kf(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        above_mode: usize,
        left_mode: usize,
    ) -> CodecResult<IntraMode> {
        let probs = ctx.probs.get_kf_y_mode_probs(above_mode, left_mode);
        let mode_idx = self.decode_intra_mode_from_probs(data, probs)?;
        IntraMode::from_u8(mode_idx)
            .ok_or_else(|| CodecError::InvalidBitstream(format!("Invalid intra mode: {mode_idx}")))
    }

    /// Decodes intra UV mode.
    pub fn decode_intra_uv_mode(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        y_mode: usize,
    ) -> CodecResult<IntraMode> {
        let probs = ctx.probs.get_uv_mode_probs(y_mode);
        let mode_idx = self.decode_intra_mode_from_probs(data, probs)?;
        IntraMode::from_u8(mode_idx).ok_or_else(|| {
            CodecError::InvalidBitstream(format!("Invalid intra UV mode: {mode_idx}"))
        })
    }

    /// Helper to decode intra mode from probability array.
    fn decode_intra_mode_from_probs(
        &mut self,
        data: &[u8],
        probs: &[Prob; INTRA_MODES - 1],
    ) -> CodecResult<u8> {
        // Intra mode tree decoding
        for (i, &prob) in probs.iter().enumerate() {
            let bit = self.bool_decoder.read_bool(data, &mut self.offset, prob)?;
            if !bit {
                return Ok(i as u8);
            }
        }
        Ok((INTRA_MODES - 1) as u8)
    }

    // =========================================================================
    // Inter Mode Decoding
    // =========================================================================

    /// Decodes inter mode.
    pub fn decode_inter_mode(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        context: usize,
    ) -> CodecResult<InterMode> {
        let probs = ctx.probs.get_inter_mode_probs(context);

        // Inter mode tree: NEARESTMV, NEARMV, ZEROMV, NEWMV
        for (i, &prob) in probs.iter().enumerate() {
            let bit = self.bool_decoder.read_bool(data, &mut self.offset, prob)?;
            if !bit {
                return InterMode::from_u8(i as u8).ok_or_else(|| {
                    CodecError::InvalidBitstream(format!("Invalid inter mode: {i}"))
                });
            }
        }

        Ok(InterMode::NewMv)
    }

    // =========================================================================
    // Reference Frame Decoding
    // =========================================================================

    /// Decodes compound reference mode flag.
    pub fn decode_comp_mode(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        context: usize,
    ) -> CodecResult<bool> {
        if context >= ctx.probs.comp_mode.len() {
            return Ok(false);
        }
        let prob = ctx.probs.comp_mode[context];
        self.bool_decoder.read_bool(data, &mut self.offset, prob)
    }

    /// Decodes single reference frame.
    pub fn decode_single_ref(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        context_0: usize,
        context_1: usize,
    ) -> CodecResult<RefFrameType> {
        // First bit: LAST vs (GOLDEN or ALTREF)
        let prob_0 = if context_0 < ctx.probs.single_ref.len() {
            ctx.probs.single_ref[context_0][0]
        } else {
            128
        };

        let is_last = !self
            .bool_decoder
            .read_bool(data, &mut self.offset, prob_0)?;
        if is_last {
            return Ok(RefFrameType::Last);
        }

        // Second bit: GOLDEN vs ALTREF
        let prob_1 = if context_1 < ctx.probs.single_ref.len() {
            ctx.probs.single_ref[context_1][1]
        } else {
            128
        };

        let is_golden = !self
            .bool_decoder
            .read_bool(data, &mut self.offset, prob_1)?;
        if is_golden {
            Ok(RefFrameType::Golden)
        } else {
            Ok(RefFrameType::AltRef)
        }
    }

    /// Decodes compound reference frame pair.
    pub fn decode_comp_ref(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        context: usize,
    ) -> CodecResult<(RefFrameType, RefFrameType)> {
        let prob = if context < ctx.probs.comp_ref.len() {
            ctx.probs.comp_ref[context]
        } else {
            128
        };

        let bit = self.bool_decoder.read_bool(data, &mut self.offset, prob)?;
        if bit {
            Ok((RefFrameType::Golden, RefFrameType::AltRef))
        } else {
            Ok((RefFrameType::Last, RefFrameType::AltRef))
        }
    }

    // =========================================================================
    // Motion Vector Decoding
    // =========================================================================

    /// Decodes a motion vector.
    pub fn decode_mv(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        allow_hp: bool,
    ) -> CodecResult<MotionVector> {
        // Decode MV joint (which components are non-zero)
        let joint = self.decode_mv_joint(data, ctx)?;

        let row = if joint.has_vertical() {
            self.decode_mv_component(data, ctx, 0, allow_hp)?
        } else {
            0
        };

        let col = if joint.has_horizontal() {
            self.decode_mv_component(data, ctx, 1, allow_hp)?
        } else {
            0
        };

        Ok(MotionVector::new(row, col))
    }

    /// Decodes motion vector joint.
    fn decode_mv_joint(&mut self, data: &[u8], ctx: &FrameContext) -> CodecResult<MvJoint> {
        let probs = &ctx.probs.mv.joints;

        let bit0 = self
            .bool_decoder
            .read_bool(data, &mut self.offset, probs[0])?;
        if !bit0 {
            return Ok(MvJoint::Zero);
        }

        let bit1 = self
            .bool_decoder
            .read_bool(data, &mut self.offset, probs[1])?;
        let bit2 = self
            .bool_decoder
            .read_bool(data, &mut self.offset, probs[2])?;

        match (bit1, bit2) {
            (false, false) => Ok(MvJoint::HnzVz),
            (false, true) => Ok(MvJoint::HzVnz),
            _ => Ok(MvJoint::HnzVnz),
        }
    }

    /// Decodes a single motion vector component.
    #[allow(clippy::cast_possible_wrap)]
    fn decode_mv_component(
        &mut self,
        data: &[u8],
        ctx: &FrameContext,
        comp: usize,
        allow_hp: bool,
    ) -> CodecResult<i16> {
        let comp_probs = &ctx.probs.mv.comps[comp];

        // Sign
        let sign = self
            .bool_decoder
            .read_bool(data, &mut self.offset, comp_probs.sign)?;

        // Class
        let class = self.decode_mv_class(data, comp_probs.classes)?;

        // Decode based on class
        let mut mag = if class == 0 {
            // Class 0: use class0 bit
            let class0_bit =
                self.bool_decoder
                    .read_bool(data, &mut self.offset, comp_probs.class0[0])?;

            // Class 0 fractional part
            let fp_idx = if class0_bit { 1 } else { 0 };
            let fp = self.decode_mv_fp(data, &comp_probs.class0_fp[fp_idx])?;

            let base = if class0_bit { 1 } else { 0 };
            (base << 3) | i32::from(fp)
        } else {
            // Offset bits for this class
            let mut mag = (1 << (class + 2)) as i32;

            for i in 0..class {
                let bit_idx = (class - 1 - i) as usize;
                if bit_idx < comp_probs.bits.len() {
                    let bit = self.bool_decoder.read_bool(
                        data,
                        &mut self.offset,
                        comp_probs.bits[bit_idx],
                    )?;
                    if bit {
                        mag |= 1 << (i + 1);
                    }
                }
            }

            // Fractional part
            let fp = self.decode_mv_fp(data, &comp_probs.fp)?;
            (mag << 3) | i32::from(fp)
        };

        // High precision bit
        if allow_hp {
            let hp_bit = if class == 0 {
                self.bool_decoder
                    .read_bool(data, &mut self.offset, comp_probs.class0_hp)?
            } else {
                self.bool_decoder
                    .read_bool(data, &mut self.offset, comp_probs.hp)?
            };

            if hp_bit {
                mag = (mag << 1) | 1;
            } else {
                mag <<= 1;
            }
        } else {
            mag <<= 1;
        }

        // Apply sign
        if sign {
            mag = -mag;
        }

        Ok(mag as i16)
    }

    /// Decodes motion vector class.
    fn decode_mv_class(&mut self, data: &[u8], probs: [Prob; 10]) -> CodecResult<u8> {
        for (i, &prob) in probs.iter().enumerate() {
            let bit = self.bool_decoder.read_bool(data, &mut self.offset, prob)?;
            if !bit {
                return Ok(i as u8);
            }
        }
        Ok(10)
    }

    /// Decodes motion vector fractional precision.
    fn decode_mv_fp(&mut self, data: &[u8], probs: &[Prob; 3]) -> CodecResult<u8> {
        let bit1 = self
            .bool_decoder
            .read_bool(data, &mut self.offset, probs[0])?;
        let bit2 = self
            .bool_decoder
            .read_bool(data, &mut self.offset, probs[1])?;
        let bit3 = self
            .bool_decoder
            .read_bool(data, &mut self.offset, probs[2])?;

        Ok((u8::from(bit1) << 2) | (u8::from(bit2) << 1) | u8::from(bit3))
    }

    // =========================================================================
    // Transform Size Decoding
    // =========================================================================

    /// Decodes transform size.
    pub fn decode_tx_size(
        &mut self,
        data: &[u8],
        _ctx: &FrameContext,
        max_tx_size: TxSize,
        _context: usize,
    ) -> CodecResult<TxSize> {
        // Simplified: return max TX size for now
        // Full implementation would decode based on probability tables
        Ok(max_tx_size)
    }

    // =========================================================================
    // Segmentation Decoding
    // =========================================================================

    /// Decodes segment ID.
    pub fn decode_segment_id(
        &mut self,
        data: &[u8],
        _ctx: &FrameContext,
        _context: usize,
    ) -> CodecResult<u8> {
        // Decode segment ID using tree
        let mut seg_id = 0u8;

        for i in 0..3 {
            // 3 bits for 8 segments
            let bit = self.bool_decoder.read_literal(data, &mut self.offset)?;
            seg_id |= (u8::from(bit)) << (2 - i);
        }

        Ok(seg_id.min((MAX_SEGMENTS - 1) as u8))
    }

    // =========================================================================
    // Utility Methods
    // =========================================================================

    /// Reads a signed integer value.
    #[allow(clippy::cast_possible_wrap)]
    pub fn read_signed(&mut self, _data: &[u8], _bits: u8) -> CodecResult<i32> {
        // Simplified implementation
        Ok(0)
    }

    /// Reads an unsigned integer value.
    pub fn read_unsigned(&mut self, _data: &[u8], _bits: u8) -> CodecResult<u32> {
        Ok(0) // Simplified implementation
    }

    /// Finishes decoding and returns the final offset.
    #[must_use]
    pub const fn finish(&self) -> usize {
        self.offset
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_symbol_decoder_new() {
        let decoder = SymbolDecoder::new();
        assert_eq!(decoder.offset(), 0);
    }

    #[test]
    fn test_bool_decoder_init() {
        let mut decoder = BoolDecoder::new();
        let data = vec![0xAA, 0x55, 0x00];
        assert!(decoder.init(&data, 0).is_ok());
    }

    #[test]
    fn test_bool_decoder_read_literal() {
        let mut decoder = BoolDecoder::new();
        let data = vec![0xFF, 0xFF, 0xFF, 0xFF];
        decoder.init(&data, 0).expect("should succeed");
        let mut offset = 2;

        let bit = decoder
            .read_literal(&data, &mut offset)
            .expect("should succeed");
        assert!(bit);
    }

    #[test]
    fn test_bool_decoder_read_literal_bits() {
        let mut decoder = BoolDecoder::new();
        let data = vec![0xAA, 0x55, 0xF0, 0x0F];
        decoder.init(&data, 0).expect("should succeed");
        let mut offset = 2;

        let value = decoder
            .read_literal_bits(&data, &mut offset, 4)
            .expect("should succeed");
        // Value depends on boolean decoder state, just verify it's within valid range
        assert!(value <= 15);
    }

    #[test]
    fn test_mv_joint_properties() {
        assert!(!MvJoint::Zero.has_horizontal());
        assert!(!MvJoint::Zero.has_vertical());

        assert!(MvJoint::HnzVz.has_horizontal());
        assert!(!MvJoint::HnzVz.has_vertical());

        assert!(!MvJoint::HzVnz.has_horizontal());
        assert!(MvJoint::HzVnz.has_vertical());

        assert!(MvJoint::HnzVnz.has_horizontal());
        assert!(MvJoint::HnzVnz.has_vertical());
    }

    #[test]
    fn test_partition_decode_simple() {
        let mut decoder = SymbolDecoder::new();
        let data = vec![0x80, 0x80, 0x00, 0x00, 0x00];
        decoder.init(&data, 0).expect("should succeed");

        let ctx = FrameContext::new();
        // In a real scenario, this would decode actual partition data
        // Here we just test that the function runs without error
        let result = decoder.decode_partition(&data, &ctx, 0);
        assert!(result.is_ok());
    }

    #[test]
    fn test_skip_decode() {
        let mut decoder = SymbolDecoder::new();
        let data = vec![0x80, 0x80, 0x00, 0x00];
        decoder.init(&data, 0).expect("should succeed");

        let ctx = FrameContext::new();
        let result = decoder.decode_skip(&data, &ctx, 0);
        assert!(result.is_ok());
    }

    #[test]
    fn test_inter_mode_from_u8() {
        assert_eq!(InterMode::from_u8(0), Some(InterMode::NearestMv));
        assert_eq!(InterMode::from_u8(1), Some(InterMode::NearMv));
        assert_eq!(InterMode::from_u8(2), Some(InterMode::ZeroMv));
        assert_eq!(InterMode::from_u8(3), Some(InterMode::NewMv));
    }

    #[test]
    fn test_ref_frame_decode_single() {
        let mut decoder = SymbolDecoder::new();
        let data = vec![0x80, 0x80, 0x00, 0x00, 0x00];
        decoder.init(&data, 0).expect("should succeed");

        let ctx = FrameContext::new();
        let result = decoder.decode_single_ref(&data, &ctx, 0, 0);
        assert!(result.is_ok());
    }

    #[test]
    fn test_mv_class_offset_bits() {
        assert_eq!(MvClass::Class0.offset_bits(), 0);
        assert_eq!(MvClass::Class1.offset_bits(), 1);
        assert_eq!(MvClass::Class5.offset_bits(), 5);
        assert_eq!(MvClass::Class10.offset_bits(), 10);
    }

    #[test]
    fn test_symbol_decoder_read_unsigned() {
        let mut decoder = SymbolDecoder::new();
        let data = vec![0xFF, 0xFF, 0xFF, 0xFF];
        decoder.init(&data, 0).expect("should succeed");

        let value = decoder.read_unsigned(&data, 4).expect("should succeed");
        assert!(value <= 15);
    }

    #[test]
    fn test_symbol_decoder_finish() {
        let mut decoder = SymbolDecoder::new();
        let data = vec![0x80, 0x80];
        decoder.init(&data, 0).expect("should succeed");

        assert_eq!(decoder.finish(), 2);
    }

    #[test]
    fn test_intra_mode_from_u8() {
        assert_eq!(IntraMode::from_u8(0), Some(IntraMode::Dc));
        assert!(IntraMode::from_u8(100).is_none());
    }

    #[test]
    fn test_segment_id_bounds() {
        let mut decoder = SymbolDecoder::new();
        let data = vec![0xFF, 0xFF, 0xFF, 0xFF];
        decoder.init(&data, 0).expect("should succeed");

        let seg_id = decoder
            .decode_segment_id(&data, &FrameContext::new(), 0)
            .expect("should succeed");
        assert!(seg_id < MAX_SEGMENTS as u8);
    }
}