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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#[cfg(test)]
use std::any::Any;
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::rc::Rc;

use anyhow::Result;
use libva::BufferType;
use libva::Display;
use libva::IQMatrix;
use libva::IQMatrixBufferVP8;
use libva::Picture as VaPicture;
use libva::ProbabilityDataBufferVP8;

use crate::decoders::vp8::backends::Result as StatelessBackendResult;
use crate::decoders::vp8::backends::StatelessDecoderBackend;
use crate::decoders::vp8::decoder::Decoder;
use crate::decoders::vp8::parser::Header;
use crate::decoders::vp8::parser::MbLfAdjustments;
use crate::decoders::vp8::parser::Segmentation;
use crate::decoders::BlockingMode;
use crate::decoders::DecodedHandle;
use crate::decoders::Result as DecoderResult;
use crate::decoders::StatelessBackendError;
use crate::decoders::VideoDecoderBackend;
use crate::utils::vaapi::DecodedHandle as VADecodedHandle;
use crate::utils::vaapi::GenericBackendHandle;
use crate::utils::vaapi::NegotiationStatus;
use crate::utils::vaapi::StreamInfo;
use crate::utils::vaapi::VaapiBackend;
use crate::Resolution;

/// Resolves to the type used as Handle by the backend.
type AssociatedHandle = <Backend as VideoDecoderBackend>::Handle;

/// The number of surfaces to allocate for this codec. Same as GStreamer's vavp8dec.
const NUM_SURFACES: usize = 7;

#[cfg(test)]
struct TestParams {
    pic_param: BufferType,
    slice_param: BufferType,
    slice_data: BufferType,
    iq_matrix: BufferType,
    probability_table: BufferType,
}

impl StreamInfo for &Header {
    fn va_profile(&self) -> anyhow::Result<i32> {
        Ok(libva::VAProfile::VAProfileVP8Version0_3)
    }

    fn rt_format(&self) -> anyhow::Result<u32> {
        Ok(libva::constants::VA_RT_FORMAT_YUV420)
    }

    fn min_num_surfaces(&self) -> usize {
        NUM_SURFACES
    }

    fn coded_size(&self) -> (u32, u32) {
        (self.width() as u32, self.height() as u32)
    }

    fn visible_rect(&self) -> ((u32, u32), (u32, u32)) {
        ((0, 0), self.coded_size())
    }
}

struct Backend {
    backend: VaapiBackend<Header>,

    #[cfg(test)]
    /// Test params. Saves the metadata sent to VA-API for the purposes of
    /// testing.
    test_params: Vec<TestParams>,
}

impl Backend {
    /// Create a new codec backend for VP8.
    fn new(display: Rc<libva::Display>) -> Result<Self> {
        Ok(Self {
            backend: VaapiBackend::new(display),
            #[cfg(test)]
            test_params: Default::default(),
        })
    }

    /// A clamp such that min <= x <= max
    fn clamp<T: PartialOrd>(x: T, low: T, high: T) -> T {
        if x > high {
            high
        } else if x < low {
            low
        } else {
            x
        }
    }

    /// Gets the VASurfaceID for the given `picture`.
    fn surface_id(picture: &GenericBackendHandle) -> libva::VASurfaceID {
        picture.surface_id()
    }

    fn build_iq_matrix(
        frame_hdr: &Header,
        segmentation: &Segmentation,
    ) -> Result<libva::BufferType> {
        let mut quantization_index: [[u16; 6]; 4] = Default::default();

        for (i, quantization_index) in quantization_index.iter_mut().enumerate() {
            let mut qi_base: i16;

            if segmentation.segmentation_enabled {
                qi_base = i16::from(segmentation.quantizer_update_value[i]);
                if !segmentation.segment_feature_mode {
                    qi_base += i16::from(frame_hdr.quant_indices().y_ac_qi);
                }
            } else {
                qi_base = i16::from(frame_hdr.quant_indices().y_ac_qi);
            }

            let mut qi = qi_base;
            quantization_index[0] = u16::try_from(Backend::clamp(qi, 0, 127))?;
            qi = qi_base + i16::from(frame_hdr.quant_indices().y_dc_delta);
            quantization_index[1] = u16::try_from(Backend::clamp(qi, 0, 127))?;
            qi = qi_base + i16::from(frame_hdr.quant_indices().y2_dc_delta);
            quantization_index[2] = u16::try_from(Backend::clamp(qi, 0, 127))?;
            qi = qi_base + i16::from(frame_hdr.quant_indices().y2_ac_delta);
            quantization_index[3] = u16::try_from(Backend::clamp(qi, 0, 127))?;
            qi = qi_base + i16::from(frame_hdr.quant_indices().uv_dc_delta);
            quantization_index[4] = u16::try_from(Backend::clamp(qi, 0, 127))?;
            qi = qi_base + i16::from(frame_hdr.quant_indices().uv_ac_delta);
            quantization_index[5] = u16::try_from(Backend::clamp(qi, 0, 127))?;
        }

        Ok(BufferType::IQMatrix(IQMatrix::VP8(IQMatrixBufferVP8::new(
            quantization_index,
        ))))
    }

    fn build_probability_table(frame_hdr: &Header) -> libva::BufferType {
        BufferType::Probability(ProbabilityDataBufferVP8::new(frame_hdr.coeff_prob()))
    }

    fn build_pic_param(
        frame_hdr: &Header,
        resolution: &Resolution,
        seg: &Segmentation,
        adj: &MbLfAdjustments,
        last: Option<&AssociatedHandle>,
        golden: Option<&AssociatedHandle>,
        alt: Option<&AssociatedHandle>,
    ) -> Result<libva::BufferType> {
        let mut loop_filter_level: [u8; 4] = Default::default();
        let mut loop_filter_deltas_ref_frame: [i8; 4] = Default::default();
        let mut loop_filter_deltas_mode: [i8; 4] = Default::default();

        for i in 0..4 {
            let mut level;
            if seg.segmentation_enabled {
                level = seg.lf_update_value[i];
                if !seg.segment_feature_mode {
                    level += i8::try_from(frame_hdr.loop_filter_level())?;
                }
            } else {
                level = i8::try_from(frame_hdr.loop_filter_level())?;
            }

            loop_filter_level[i] = Backend::clamp(u8::try_from(level)?, 0, 63);
            loop_filter_deltas_ref_frame[i] = adj.ref_frame_delta[i];
            loop_filter_deltas_mode[i] = adj.mb_mode_delta[i];
        }

        let last_surface = if let Some(last_ref) = last {
            Self::surface_id(&last_ref.handle())
        } else {
            libva::constants::VA_INVALID_SURFACE
        };

        let golden_surface = if let Some(golden_ref) = golden {
            Self::surface_id(&golden_ref.handle())
        } else {
            libva::constants::VA_INVALID_SURFACE
        };

        let alt_surface = if let Some(alt_ref) = alt {
            Self::surface_id(&alt_ref.handle())
        } else {
            libva::constants::VA_INVALID_SURFACE
        };

        let pic_fields = libva::VP8PicFields::new(
            u32::from(!frame_hdr.key_frame()),
            u32::from(frame_hdr.version()),
            u32::from(seg.segmentation_enabled),
            u32::from(seg.update_mb_segmentation_map),
            u32::from(seg.update_segment_feature_data),
            u32::from(frame_hdr.filter_type()),
            u32::from(frame_hdr.sharpness_level()),
            u32::from(adj.loop_filter_adj_enable),
            u32::from(adj.mode_ref_lf_delta_update),
            u32::from(frame_hdr.sign_bias_golden()),
            u32::from(frame_hdr.sign_bias_alternate()),
            u32::from(frame_hdr.mb_no_coeff_skip()),
            u32::from(frame_hdr.loop_filter_level() == 0),
        );

        let bool_coder_ctx = libva::BoolCoderContextVPX::new(
            u8::try_from(frame_hdr.bd_range())?,
            u8::try_from(frame_hdr.bd_value())?,
            u8::try_from(frame_hdr.bd_count())?,
        );

        let pic_param = libva::PictureParameterBufferVP8::new(
            resolution.width,
            resolution.height,
            last_surface,
            golden_surface,
            alt_surface,
            &pic_fields,
            seg.segment_prob,
            loop_filter_level,
            loop_filter_deltas_ref_frame,
            loop_filter_deltas_mode,
            frame_hdr.prob_skip_false(),
            frame_hdr.prob_intra(),
            frame_hdr.prob_last(),
            frame_hdr.prob_golden(),
            frame_hdr.mode_probs().intra_16x16_prob,
            frame_hdr.mode_probs().intra_chroma_prob,
            frame_hdr.mv_prob(),
            &bool_coder_ctx,
        );

        Ok(libva::BufferType::PictureParameter(
            libva::PictureParameter::VP8(pic_param),
        ))
    }

    fn build_slice_param(frame_hdr: &Header, slice_size: usize) -> Result<libva::BufferType> {
        let mut partition_size: [u32; 9] = Default::default();
        let num_of_partitions = (1 << frame_hdr.log2_nbr_of_dct_partitions()) + 1;

        partition_size[0] = frame_hdr.first_part_size() - ((frame_hdr.header_size() + 7) >> 3);

        partition_size[1..num_of_partitions]
            .clone_from_slice(&frame_hdr.partition_size()[..(num_of_partitions - 1)]);

        Ok(libva::BufferType::SliceParameter(
            libva::SliceParameter::VP8(libva::SliceParameterBufferVP8::new(
                u32::try_from(slice_size)?,
                u32::from(frame_hdr.data_chunk_size()),
                0,
                frame_hdr.header_size(),
                u8::try_from(num_of_partitions)?,
                partition_size,
            )),
        ))
    }

    #[cfg(test)]
    fn save_params(
        &mut self,
        pic_param: BufferType,
        slice_param: BufferType,
        slice_data: BufferType,
        iq_matrix: BufferType,
        probability_table: BufferType,
    ) {
        let test_params = TestParams {
            pic_param,
            slice_param,
            slice_data,
            iq_matrix,
            probability_table,
        };

        self.test_params.push(test_params);
    }
}

impl StatelessDecoderBackend for Backend {
    fn new_sequence(&mut self, header: &Header) -> StatelessBackendResult<()> {
        self.backend.metadata_state.open(header, None)?;
        self.backend.negotiation_status = NegotiationStatus::Possible(Box::new(header.clone()));

        Ok(())
    }

    fn submit_picture(
        &mut self,
        picture: &Header,
        last_ref: Option<&Self::Handle>,
        golden_ref: Option<&Self::Handle>,
        alt_ref: Option<&Self::Handle>,
        bitstream: &[u8],
        segmentation: &Segmentation,
        mb_lf_adjust: &MbLfAdjustments,
        timestamp: u64,
        block: BlockingMode,
    ) -> StatelessBackendResult<Self::Handle> {
        self.backend.negotiation_status = NegotiationStatus::Negotiated;

        let metadata = self.backend.metadata_state.get_parsed_mut()?;
        let context = &metadata.context;
        let coded_resolution = metadata.surface_pool.coded_resolution();

        let iq_buffer = context.create_buffer(Backend::build_iq_matrix(picture, segmentation)?)?;

        let probs = context.create_buffer(Backend::build_probability_table(picture))?;

        let pic_param = context.create_buffer(Backend::build_pic_param(
            picture,
            &coded_resolution,
            segmentation,
            mb_lf_adjust,
            last_ref,
            golden_ref,
            alt_ref,
        )?)?;

        let slice_param =
            context.create_buffer(Backend::build_slice_param(picture, bitstream.len())?)?;

        let slice_data =
            context.create_buffer(libva::BufferType::SliceData(Vec::from(bitstream)))?;

        let surface = metadata
            .surface_pool
            .get_surface()
            .ok_or(StatelessBackendError::OutOfResources)?;

        let mut va_picture = VaPicture::new(timestamp, Rc::clone(context), surface);

        // Add buffers with the parsed data.
        va_picture.add_buffer(iq_buffer);
        va_picture.add_buffer(probs);
        va_picture.add_buffer(pic_param);
        va_picture.add_buffer(slice_param);
        va_picture.add_buffer(slice_data);

        #[cfg(test)]
        self.save_params(
            Backend::build_pic_param(
                picture,
                &coded_resolution,
                segmentation,
                mb_lf_adjust,
                last_ref,
                golden_ref,
                alt_ref,
            )?,
            Backend::build_slice_param(picture, bitstream.len())?,
            libva::BufferType::SliceData(Vec::from(bitstream)),
            Backend::build_iq_matrix(picture, segmentation)?,
            Backend::build_probability_table(picture),
        );

        self.backend.process_picture(va_picture, block)
    }

    #[cfg(test)]
    fn get_test_params(&self) -> &dyn Any {
        &self.test_params
    }
}

impl VideoDecoderBackend for Backend {
    type Handle = VADecodedHandle;

    fn coded_resolution(&self) -> Option<Resolution> {
        self.backend.coded_resolution()
    }

    fn display_resolution(&self) -> Option<Resolution> {
        self.backend.display_resolution()
    }

    fn num_resources_total(&self) -> usize {
        self.backend.num_resources_total()
    }

    fn num_resources_left(&self) -> usize {
        self.backend.num_resources_left()
    }

    fn format(&self) -> Option<crate::DecodedFormat> {
        self.backend.format()
    }

    fn try_format(&mut self, format: crate::DecodedFormat) -> DecoderResult<()> {
        self.backend.try_format(format)
    }

    fn poll(&mut self, blocking_mode: BlockingMode) -> DecoderResult<VecDeque<Self::Handle>> {
        self.backend.poll(blocking_mode)
    }

    fn handle_is_ready(&self, handle: &Self::Handle) -> bool {
        self.backend.handle_is_ready(handle)
    }

    fn block_on_handle(&mut self, handle: &Self::Handle) -> StatelessBackendResult<()> {
        self.backend.block_on_handle(handle)
    }
}

impl Decoder<VADecodedHandle> {
    // Creates a new instance of the decoder using the VAAPI backend.
    pub fn new_vaapi(display: Rc<Display>, blocking_mode: BlockingMode) -> Result<Self> {
        Self::new(Box::new(Backend::new(display)?), blocking_mode)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use libva::BufferType;
    use libva::Display;
    use libva::IQMatrix;
    use libva::PictureParameter;
    use libva::SliceParameter;

    use crate::decoders::vp8::backends::vaapi::AssociatedHandle;
    use crate::decoders::vp8::backends::vaapi::TestParams;
    use crate::decoders::vp8::backends::StatelessDecoderBackend;
    use crate::decoders::vp8::decoder::tests::process_ready_frames;
    use crate::decoders::vp8::decoder::tests::run_decoding_loop;
    use crate::decoders::vp8::decoder::Decoder;
    use crate::decoders::BlockingMode;
    use crate::decoders::DecodedHandle;
    use crate::decoders::DynHandle;

    fn get_test_params(
        backend: &dyn StatelessDecoderBackend<Handle = AssociatedHandle>,
    ) -> &Vec<TestParams> {
        backend.get_test_params().downcast_ref::<_>().unwrap()
    }

    fn process_handle(
        handle: &AssociatedHandle,
        dump_yuv: bool,
        expected_crcs: Option<&mut HashSet<&str>>,
        frame_num: i32,
    ) {
        let mut picture = handle.handle_mut();
        let mut backend_handle = picture.dyn_mappable_handle_mut();

        let buffer_size = backend_handle.image_size();
        let mut nv12 = vec![0; buffer_size];

        backend_handle.read(&mut nv12).unwrap();

        if dump_yuv {
            std::fs::write(format!("/tmp/frame{}.yuv", frame_num), &nv12).unwrap();
        }

        let frame_crc = crc32fast::hash(&nv12);

        if let Some(expected_crcs) = expected_crcs {
            let frame_crc = format!("{:08x}", frame_crc);
            let removed = expected_crcs.remove(frame_crc.as_str());
            assert!(
                removed,
                "CRC not found: {:?}, iteration: {:?}",
                frame_crc, frame_num
            );
        }
    }

    #[test]
    // Ignore this test by default as it requires libva-compatible hardware.
    #[ignore]
    fn test_25fps_vp8() {
        const TEST_STREAM: &[u8] = include_bytes!("../test_data/test-25fps.vp8");
        const STREAM_CRCS: &str = include_str!("../test_data/test-25fps.vp8.crc");

        const TEST_25_FPS_VP8_STREAM_SLICE_DATA_0: &[u8] =
            include_bytes!("../test_data/test-25fps-vp8-slice-data-0.bin");
        const TEST_25_FPS_VP8_STREAM_SLICE_DATA_1: &[u8] =
            include_bytes!("../test_data/test-25fps-vp8-slice-data-1.bin");
        const TEST_25_FPS_VP8_STREAM_SLICE_DATA_2: &[u8] =
            include_bytes!("../test_data/test-25fps-vp8-slice-data-2.bin");

        const TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_0: &[u8] =
            include_bytes!("../test_data/test-25fps-vp8-probability-table-0.bin");
        const TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_1: &[u8] =
            include_bytes!("../test_data/test-25fps-vp8-probability-table-1.bin");
        const TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_2: &[u8] =
            include_bytes!("../test_data/test-25fps-vp8-probability-table-2.bin");

        let blocking_modes = [BlockingMode::Blocking, BlockingMode::NonBlocking];

        for blocking_mode in blocking_modes {
            let mut expected_crcs = STREAM_CRCS.lines().collect::<HashSet<_>>();

            let mut frame_num = 0;
            let display = Display::open().unwrap();

            let mut decoder = Decoder::new_vaapi(display, blocking_mode).unwrap();

            run_decoding_loop(&mut decoder, TEST_STREAM, |decoder| {
                process_ready_frames(decoder, &mut |decoder, handle| {
                    // Contains the params used to decode the picture. Useful if we want to
                    // write assertions against any particular value used therein.
                    let params = &get_test_params(decoder.backend())[frame_num as usize];

                    process_handle(handle, false, Some(&mut expected_crcs), frame_num);

                    let pic_param = match params.pic_param {
                        BufferType::PictureParameter(PictureParameter::VP8(ref pic_param)) => {
                            pic_param
                        }
                        _ => panic!(),
                    };

                    let slice_param = match params.slice_param {
                        BufferType::SliceParameter(SliceParameter::VP8(ref slice_param)) => {
                            slice_param
                        }
                        _ => panic!(),
                    };

                    let slice_data = match params.slice_data {
                        BufferType::SliceData(ref data) => data,
                        _ => panic!(),
                    };

                    let iq_matrix = match params.iq_matrix {
                        BufferType::IQMatrix(IQMatrix::VP8(ref iq_matrix)) => iq_matrix,
                        _ => panic!(),
                    };

                    let probability_table = match params.probability_table {
                        BufferType::Probability(ref probability_table) => probability_table,
                        _ => panic!(),
                    };

                    if frame_num == 0 {
                        assert_eq!(iq_matrix.inner().quantization_index, [[4; 6]; 4]);
                        for i in 0..4 {
                            for j in 0..8 {
                                for k in 0..3 {
                                    for l in 0..11 {
                                        const OFF_I: usize = 8 * 3 * 11;
                                        const OFF_J: usize = 3 * 11;
                                        const OFF_K: usize = 11;
                                        // maybe std::transmute?
                                        assert_eq!(
                                            probability_table.inner().dct_coeff_probs[i][j][k][l],
                                            TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_0
                                                [(i * OFF_I) + (j * OFF_J) + (k * OFF_K) + l]
                                        );
                                    }
                                }
                            }
                        }

                        assert_eq!(pic_param.inner().frame_width, 320);
                        assert_eq!(pic_param.inner().frame_height, 240);
                        assert_eq!(
                            pic_param.inner().last_ref_frame,
                            libva::constants::VA_INVALID_SURFACE
                        );
                        assert_eq!(
                            pic_param.inner().golden_ref_frame,
                            libva::constants::VA_INVALID_SURFACE
                        );
                        assert_eq!(
                            pic_param.inner().alt_ref_frame,
                            libva::constants::VA_INVALID_SURFACE
                        );
                        assert_eq!(
                            pic_param.inner().out_of_loop_frame,
                            libva::constants::VA_INVALID_SURFACE
                        );

                        // Safe because this bitfield is initialized by the decoder.
                        assert_eq!(unsafe { pic_param.inner().pic_fields.value }, unsafe {
                            libva::VP8PicFields::new(0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1)
                                .inner()
                                .value
                        });

                        assert_eq!(pic_param.inner().mb_segment_tree_probs, [0; 3]);
                        assert_eq!(pic_param.inner().loop_filter_level, [0; 4]);
                        assert_eq!(
                            pic_param.inner().loop_filter_deltas_ref_frame,
                            [2, 0, -2, -2]
                        );
                        assert_eq!(pic_param.inner().loop_filter_deltas_mode, [4, -2, 2, 4]);
                        assert_eq!(pic_param.inner().prob_skip_false, 0xbe);
                        assert_eq!(pic_param.inner().prob_intra, 0);
                        assert_eq!(pic_param.inner().prob_last, 0);
                        assert_eq!(pic_param.inner().prob_gf, 0);

                        assert_eq!(pic_param.inner().y_mode_probs, [0x91, 0x9c, 0xa3, 0x80]);
                        assert_eq!(pic_param.inner().uv_mode_probs, [0x8e, 0x72, 0xb7]);
                        assert_eq!(
                            pic_param.inner().mv_probs[0],
                            [
                                0xa2, 0x80, 0xe1, 0x92, 0xac, 0x93, 0xd6, 0x27, 0x9c, 0x80, 0x81,
                                0x84, 0x4b, 0x91, 0xb2, 0xce, 0xef, 0xfe, 0xfe
                            ]
                        );
                        assert_eq!(
                            pic_param.inner().mv_probs[1],
                            [
                                0xa4, 0x80, 0xcc, 0xaa, 0x77, 0xeb, 0x8c, 0xe6, 0xe4, 0x80, 0x82,
                                0x82, 0x4a, 0x94, 0xb4, 0xcb, 0xec, 0xfe, 0xfe,
                            ]
                        );

                        assert_eq!(pic_param.inner().bool_coder_ctx.range, 0xfc);
                        assert_eq!(pic_param.inner().bool_coder_ctx.value, 0x39);
                        assert_eq!(pic_param.inner().bool_coder_ctx.count, 0x0);

                        assert_eq!(
                            slice_param.inner(),
                            libva::SliceParameterBufferVP8::new(
                                14788,
                                10,
                                0,
                                3040,
                                2,
                                [926, 13472, 0, 0, 0, 0, 0, 0, 0],
                            )
                            .inner(),
                        );

                        assert_eq!(&slice_data[..], TEST_25_FPS_VP8_STREAM_SLICE_DATA_0);
                    } else if frame_num == 1 {
                        assert_eq!(iq_matrix.inner().quantization_index, [[0x7f; 6]; 4]);
                        for i in 0..4 {
                            for j in 0..8 {
                                for k in 0..3 {
                                    for l in 0..11 {
                                        const OFF_I: usize = 8 * 3 * 11;
                                        const OFF_J: usize = 3 * 11;
                                        const OFF_K: usize = 11;
                                        // maybe std::transmute?
                                        assert_eq!(
                                            probability_table.inner().dct_coeff_probs[i][j][k][l],
                                            TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_1
                                                [(i * OFF_I) + (j * OFF_J) + (k * OFF_K) + l]
                                        );
                                    }
                                }
                            }
                        }
                        assert_eq!(pic_param.inner().frame_width, 320);
                        assert_eq!(pic_param.inner().frame_height, 240);
                        assert_eq!(pic_param.inner().last_ref_frame, 0);
                        assert_eq!(pic_param.inner().golden_ref_frame, 0);
                        assert_eq!(pic_param.inner().alt_ref_frame, 0);
                        assert_eq!(
                            pic_param.inner().out_of_loop_frame,
                            libva::constants::VA_INVALID_SURFACE
                        );

                        // Safe because this bitfield is initialized by the decoder.
                        assert_eq!(unsafe { pic_param.inner().pic_fields.value }, unsafe {
                            libva::VP8PicFields::new(1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0)
                                .inner()
                                .value
                        });

                        assert_eq!(pic_param.inner().mb_segment_tree_probs, [0; 3]);
                        assert_eq!(pic_param.inner().loop_filter_level, [44; 4]);
                        assert_eq!(
                            pic_param.inner().loop_filter_deltas_ref_frame,
                            [2, 0, -2, -2]
                        );
                        assert_eq!(pic_param.inner().loop_filter_deltas_mode, [4, -2, 2, 4]);
                        assert_eq!(pic_param.inner().prob_skip_false, 0x11);
                        assert_eq!(pic_param.inner().prob_intra, 0x2a);
                        assert_eq!(pic_param.inner().prob_last, 0xff);
                        assert_eq!(pic_param.inner().prob_gf, 0x80);

                        assert_eq!(pic_param.inner().y_mode_probs, [0x70, 0x56, 0x8c, 0x25]);
                        assert_eq!(pic_param.inner().uv_mode_probs, [0xa2, 0x65, 0xcc]);
                        assert_eq!(
                            pic_param.inner().mv_probs[0],
                            [
                                0xa2, 0x80, 0xe1, 0x92, 0xac, 0x93, 0xd6, 0x27, 0x9c, 0x80, 0x81,
                                0x84, 0x4b, 0x91, 0xb2, 0xce, 0xef, 0xfe, 0xfe,
                            ]
                        );
                        assert_eq!(
                            pic_param.inner().mv_probs[1],
                            [
                                0xa4, 0x80, 0xcc, 0xaa, 0x77, 0xeb, 0x8c, 0xe6, 0xe4, 0x80, 0x82,
                                0x82, 0x4a, 0x94, 0xb4, 0xcb, 0xec, 0xfe, 0xfe,
                            ]
                        );

                        assert_eq!(pic_param.inner().bool_coder_ctx.range, 0xde);
                        assert_eq!(pic_param.inner().bool_coder_ctx.value, 0x39);
                        assert_eq!(pic_param.inner().bool_coder_ctx.count, 0x7);

                        assert_eq!(
                            slice_param.inner(),
                            libva::SliceParameterBufferVP8::new(
                                257,
                                3,
                                0,
                                129,
                                2,
                                [143, 94, 0, 0, 0, 0, 0, 0, 0],
                            )
                            .inner()
                        );

                        assert_eq!(&slice_data[..], TEST_25_FPS_VP8_STREAM_SLICE_DATA_1);
                    } else if frame_num == 2 {
                        assert_eq!(iq_matrix.inner().quantization_index, [[0x7f; 6]; 4]);
                        for i in 0..4 {
                            for j in 0..8 {
                                for k in 0..3 {
                                    for l in 0..11 {
                                        const OFF_I: usize = 8 * 3 * 11;
                                        const OFF_J: usize = 3 * 11;
                                        const OFF_K: usize = 11;
                                        // maybe std::transmute?
                                        assert_eq!(
                                            probability_table.inner().dct_coeff_probs[i][j][k][l],
                                            TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_2
                                                [(i * OFF_I) + (j * OFF_J) + (k * OFF_K) + l]
                                        );
                                    }
                                }
                            }
                        }
                        assert_eq!(pic_param.inner().frame_width, 320);
                        assert_eq!(pic_param.inner().frame_height, 240);
                        assert_eq!(pic_param.inner().last_ref_frame, 1);
                        assert_eq!(pic_param.inner().golden_ref_frame, 0);
                        assert_eq!(pic_param.inner().alt_ref_frame, 0);
                        assert_eq!(
                            pic_param.inner().out_of_loop_frame,
                            libva::constants::VA_INVALID_SURFACE
                        );

                        // Safe because this bitfield is initialized by the decoder.
                        assert_eq!(unsafe { pic_param.inner().pic_fields.value }, unsafe {
                            libva::VP8PicFields::new(1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0)
                                .inner()
                                .value
                        });

                        assert_eq!(pic_param.inner().mb_segment_tree_probs, [0; 3]);
                        assert_eq!(pic_param.inner().loop_filter_level, [28; 4]);
                        assert_eq!(
                            pic_param.inner().loop_filter_deltas_ref_frame,
                            [2, 0, -2, -2]
                        );
                        assert_eq!(pic_param.inner().loop_filter_deltas_mode, [4, -2, 2, 4]);
                        assert_eq!(pic_param.inner().prob_skip_false, 0x6);
                        assert_eq!(pic_param.inner().prob_intra, 0x1);
                        assert_eq!(pic_param.inner().prob_last, 0xf8);
                        assert_eq!(pic_param.inner().prob_gf, 0xff);

                        assert_eq!(pic_param.inner().y_mode_probs, [0x70, 0x56, 0x8c, 0x25]);
                        assert_eq!(pic_param.inner().uv_mode_probs, [0xa2, 0x65, 0xcc]);
                        assert_eq!(
                            pic_param.inner().mv_probs[0],
                            [
                                0xa2, 0x80, 0xe1, 0x92, 0xac, 0x93, 0xd6, 0x27, 0x9c, 0x80, 0x81,
                                0x84, 0x4b, 0x91, 0xb2, 0xce, 0xef, 0xfe, 0xfe,
                            ]
                        );
                        assert_eq!(
                            pic_param.inner().mv_probs[1],
                            [
                                0xa4, 0x80, 0xcc, 0xaa, 0x77, 0xeb, 0x8c, 0xe6, 0xe4, 0x80, 0x82,
                                0x82, 0x4a, 0x94, 0xb4, 0xcb, 0xec, 0xfe, 0xfe,
                            ]
                        );

                        assert_eq!(pic_param.inner().bool_coder_ctx.range, 0xb1);
                        assert_eq!(pic_param.inner().bool_coder_ctx.value, 0xd);
                        assert_eq!(pic_param.inner().bool_coder_ctx.count, 0x2);

                        assert_eq!(
                            slice_param.inner(),
                            libva::SliceParameterBufferVP8::new(
                                131,
                                3,
                                0,
                                86,
                                2,
                                [66, 51, 0, 0, 0, 0, 0, 0, 0],
                            )
                            .inner()
                        );

                        assert_eq!(&slice_data[..], TEST_25_FPS_VP8_STREAM_SLICE_DATA_2);
                    }

                    frame_num += 1;
                });
            });
        }
    }
}