Repository navigation
Expand file tree
/
Copy pathvaapi_decode.rs
More file actions
2355 lines (2216 loc) · 77.5 KB
/
Copy pathvaapi_decode.rs
File metadata and controls
2355 lines (2216 loc) · 77.5 KB
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Direct stateless VA-API H.264/AV1 camera decoder.
//!
//! Codec parsing, decoded-picture-buffer management, and output ordering are
//! provided by `cros-codecs`. This module supplies its stateless backend
//! traits using blit's existing runtime-loaded `libva` entry points. No
//! FFmpeg symbols, process, or ABI are involved.
#![allow(non_upper_case_globals)]
use crate::gpu_libs::{
self, VA_STATUS_SUCCESS, VABufferID, VAConfigID, VAContextID, VADisplay, VASurfaceID,
};
use cros_codecs::codec::av1::parser::{
BitDepth, FrameHeaderObu, MAX_SEGMENTS, MAX_TILE_COLS, MAX_TILE_ROWS, NUM_REF_FRAMES,
Profile as Av1Profile, SEG_LVL_MAX, StreamInfo as Av1StreamInfo, TileGroupObu, WarpModelType,
};
use cros_codecs::codec::h264::dpb::{Dpb, DpbEntry};
use cros_codecs::codec::h264::parser::{Pps, Slice, SliceHeader, Sps};
use cros_codecs::codec::h264::picture::{Field, PictureData, Reference};
use cros_codecs::decoder::stateless::av1::{Av1, StatelessAV1DecoderBackend};
use cros_codecs::decoder::stateless::h264::{
H264, StatelessH264DecoderBackend, get_raster_from_zigzag_4x4, get_raster_from_zigzag_8x8,
};
use cros_codecs::decoder::stateless::{
DecodeError as CrosDecodeError, NewPictureError, NewPictureResult, StatelessBackendResult,
StatelessDecoder, StatelessDecoderBackend, StatelessDecoderBackendPicture,
StatelessVideoDecoder,
};
use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
use cros_codecs::video_frame::{ReadMapping, VideoFrame, WriteMapping};
use cros_codecs::{DecodedFormat, Fourcc, Resolution};
use std::ffi::c_void;
use std::fmt;
use std::os::fd::{AsRawFd, OwnedFd};
use std::ptr;
use std::rc::Rc;
use std::sync::Arc;
const VAEntrypointVLD: i32 = 1;
const VAConfigAttribRTFormat: i32 = 0;
const VA_PROGRESSIVE: i32 = 2;
const VAProfileH264ConstrainedBaseline: i32 = 13;
const VAProfileH264Main: i32 = 6;
const VAProfileH264High: i32 = 7;
const VAProfileAV1Profile0: i32 = 32;
const VAProfileAV1Profile1: i32 = 33;
const VA_RT_FORMAT_YUV420: u32 = 0x0000_0001;
const VA_RT_FORMAT_YUV444: u32 = 0x0000_0004;
const VAPictureParameterBufferType: i32 = 0;
const VAIQMatrixBufferType: i32 = 1;
const VASliceParameterBufferType: i32 = 4;
const VASliceDataBufferType: i32 = 5;
const VA_SLICE_DATA_FLAG_ALL: u32 = 0;
const VA_INVALID_SURFACE: u32 = u32::MAX;
const VA_PICTURE_H264_INVALID: u32 = 1;
const VA_PICTURE_H264_TOP_FIELD: u32 = 2;
const VA_PICTURE_H264_BOTTOM_FIELD: u32 = 4;
const VA_PICTURE_H264_SHORT_TERM_REFERENCE: u32 = 8;
const VA_PICTURE_H264_LONG_TERM_REFERENCE: u32 = 16;
const VA_FOURCC_NV12: u32 = u32::from_le_bytes(*b"NV12");
const VA_FOURCC_444P: u32 = u32::from_le_bytes(*b"444P");
const MAX_ENCODED_BYTES: usize = 4 * 1024 * 1024;
const MAX_DIMENSION: u32 = 16_384;
const MAX_PIXELS: u64 = 67_108_864;
#[repr(C)]
struct VaConfigAttrib {
kind: i32,
value: u32,
}
// VAImage is kept opaque. These offsets are stable public ABI fields and are
// already used by the direct encoders in vaapi_encode.rs.
const VA_IMAGE_SIZE: usize = 120;
const VAIMG_ID_OFF: usize = 0;
const VAIMG_FOURCC_OFF: usize = 4;
const VAIMG_BUF_OFF: usize = 52;
const VAIMG_WIDTH_OFF: usize = 56;
const VAIMG_HEIGHT_OFF: usize = 58;
const VAIMG_DATA_SIZE_OFF: usize = 60;
const VAIMG_NUM_PLANES_OFF: usize = 64;
const VAIMG_PITCHES_OFF: usize = 68;
const VAIMG_OFFSETS_OFF: usize = 80;
fn va_error(operation: &str, status: i32) -> anyhow::Error {
anyhow::anyhow!("{operation} failed with VAStatus {status}")
}
fn checked_va(operation: &str, status: i32) -> anyhow::Result<()> {
if status == VA_STATUS_SUCCESS {
Ok(())
} else {
Err(va_error(operation, status))
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Codec {
H264,
Av1,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Chroma {
Cs420,
Cs444,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum Error {
Unavailable(String),
Invalid(String),
Resource(String),
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unavailable(detail) => write!(formatter, "VA-API decode unavailable: {detail}"),
Self::Invalid(detail) => write!(formatter, "invalid video bitstream: {detail}"),
Self::Resource(detail) => write!(formatter, "VA-API decode resource failure: {detail}"),
}
}
}
impl std::error::Error for Error {}
impl Chroma {
fn rt_format(self) -> u32 {
match self {
Self::Cs420 => VA_RT_FORMAT_YUV420,
Self::Cs444 => VA_RT_FORMAT_YUV444,
}
}
fn decoded_format(self) -> DecodedFormat {
match self {
Self::Cs420 => DecodedFormat::NV12,
Self::Cs444 => DecodedFormat::I444,
}
}
}
#[derive(Clone, Copy)]
struct Crop {
x: u32,
y: u32,
width: u32,
height: u32,
}
struct SequenceConfig {
profile: i32,
chroma: Chroma,
coded_width: u32,
coded_height: u32,
crop: Crop,
min_frames: usize,
}
/// A token required by the cros-codecs allocation interface. VA surfaces are
/// allocated and owned by [`Surface`] instead; the token deliberately has no
/// mappable storage of its own.
#[derive(Debug)]
pub(crate) struct FrameToken {
width: u32,
height: u32,
chroma: Chroma,
}
impl VideoFrame for FrameToken {
fn fourcc(&self) -> Fourcc {
match self.chroma {
Chroma::Cs420 => Fourcc::from(b"NV12"),
Chroma::Cs444 => Fourcc::from(b"I444"),
}
}
fn resolution(&self) -> Resolution {
Resolution::from((self.width, self.height))
}
fn get_plane_size(&self) -> Vec<usize> {
Vec::new()
}
fn get_plane_pitch(&self) -> Vec<usize> {
Vec::new()
}
fn map<'a>(&'a self) -> Result<Box<dyn ReadMapping<'a> + 'a>, String> {
Err("VA frame tokens are mapped through their decoded handle".into())
}
fn map_mut<'a>(&'a mut self) -> Result<Box<dyn WriteMapping<'a> + 'a>, String> {
Err("VA frame tokens are mapped through their decoded handle".into())
}
}
struct Display {
va: &'static gpu_libs::VaFns,
raw: VADisplay,
_drm_fd: OwnedFd,
}
// libva serializes access to a VADisplay. Decoders live on one worker thread;
// cloned handles only keep resources alive and are never concurrently mapped.
unsafe impl Send for Display {}
unsafe impl Sync for Display {}
impl Display {
fn open(device: &str) -> anyhow::Result<Arc<Self>> {
let va = gpu_libs::va().map_err(|error| anyhow::anyhow!("VA-API: {error}"))?;
let va_drm = gpu_libs::va_drm().map_err(|error| anyhow::anyhow!("VA-DRM: {error}"))?;
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(device)
.map_err(|error| anyhow::anyhow!("failed to open {device}: {error}"))?;
let drm_fd = OwnedFd::from(file);
// SAFETY: drm_fd is live and retained by Display.
let raw = unsafe { (va_drm.vaGetDisplayDRM)(drm_fd.as_raw_fd()) };
if raw.is_null() {
return Err(anyhow::anyhow!(
"vaGetDisplayDRM returned null for {device}"
));
}
let (mut major, mut minor) = (0, 0);
// SAFETY: raw is a non-null VA display and output pointers are valid.
checked_va("vaInitialize", unsafe {
(va.vaInitialize)(raw, &mut major, &mut minor)
})?;
Ok(Arc::new(Self {
va,
raw,
_drm_fd: drm_fd,
}))
}
fn supports_profile(&self, profile: i32) -> anyhow::Result<()> {
let mut entrypoints = [0_i32; 32];
let mut count = 0;
// SAFETY: storage is valid for the driver-advertised entrypoints.
checked_va("vaQueryConfigEntrypoints", unsafe {
(self.va.vaQueryConfigEntrypoints)(
self.raw,
profile,
entrypoints.as_mut_ptr(),
&mut count,
)
})?;
let count = usize::try_from(count).unwrap_or(0).min(entrypoints.len());
if entrypoints[..count].contains(&VAEntrypointVLD) {
Ok(())
} else {
Err(anyhow::anyhow!(
"VAProfile {profile} has no VLD decode entrypoint"
))
}
}
}
impl Drop for Display {
fn drop(&mut self) {
// SAFETY: Display exclusively owns the initialized handle.
unsafe {
(self.va.vaTerminate)(self.raw);
}
}
}
struct DecodeContext {
display: Arc<Display>,
config: VAConfigID,
context: VAContextID,
chroma: Chroma,
width: u32,
height: u32,
}
impl DecodeContext {
fn new(
display: Arc<Display>,
profile: i32,
chroma: Chroma,
width: u32,
height: u32,
) -> anyhow::Result<Arc<Self>> {
display.supports_profile(profile)?;
let va = display.va;
let mut config = 0;
let mut rt_format = VaConfigAttrib {
kind: VAConfigAttribRTFormat,
value: chroma.rt_format(),
};
// Request the exact render-target format in the decoder config. In
// particular, a profile existing is not evidence that its 4:4:4
// subset is implemented.
checked_va("vaCreateConfig(VLD)", unsafe {
(va.vaCreateConfig)(
display.raw,
profile,
VAEntrypointVLD,
(&mut rt_format as *mut VaConfigAttrib).cast(),
1,
&mut config,
)
})?;
let mut probe_surface = 0;
let status = unsafe {
(va.vaCreateSurfaces)(
display.raw,
chroma.rt_format(),
width,
height,
&mut probe_surface,
1,
ptr::null_mut(),
0,
)
};
if status != VA_STATUS_SUCCESS {
unsafe { (va.vaDestroyConfig)(display.raw, config) };
return Err(va_error("vaCreateSurfaces(exact decode format)", status));
}
let mut context = 0;
let status = unsafe {
(va.vaCreateContext)(
display.raw,
config,
width as i32,
height as i32,
VA_PROGRESSIVE,
&mut probe_surface,
1,
&mut context,
)
};
unsafe { (va.vaDestroySurfaces)(display.raw, &mut probe_surface, 1) };
if status != VA_STATUS_SUCCESS {
// SAFETY: config was created above and context was not.
unsafe { (va.vaDestroyConfig)(display.raw, config) };
return Err(va_error("vaCreateContext(VLD)", status));
}
Ok(Arc::new(Self {
display,
config,
context,
chroma,
width,
height,
}))
}
}
impl Drop for DecodeContext {
fn drop(&mut self) {
// SAFETY: no Surface/Buffer can outlive this Arc-owned context.
unsafe {
(self.display.va.vaDestroyContext)(self.display.raw, self.context);
(self.display.va.vaDestroyConfig)(self.display.raw, self.config);
}
}
}
struct Buffer {
context: Arc<DecodeContext>,
id: VABufferID,
}
impl Drop for Buffer {
fn drop(&mut self) {
// SAFETY: the ID was created on this live display and is owned here.
unsafe {
(self.context.display.va.vaDestroyBuffer)(self.context.display.raw, self.id);
}
}
}
struct Surface {
context: Arc<DecodeContext>,
id: VASurfaceID,
}
impl Surface {
fn new(context: Arc<DecodeContext>) -> anyhow::Result<Self> {
let mut id = 0;
// SAFETY: output storage is valid and context retains the display.
checked_va("vaCreateSurfaces", unsafe {
(context.display.va.vaCreateSurfaces)(
context.display.raw,
context.chroma.rt_format(),
context.width,
context.height,
&mut id,
1,
ptr::null_mut(),
0,
)
})?;
Ok(Self { context, id })
}
}
impl Drop for Surface {
fn drop(&mut self) {
// SAFETY: the surface is exclusively owned and no submission can
// reference it after the last Arc<VaHandleInner> is dropped.
unsafe {
(self.context.display.va.vaDestroySurfaces)(self.context.display.raw, &mut self.id, 1);
}
}
}
pub(crate) struct Picture {
surface: Arc<Surface>,
buffers: Vec<Buffer>,
timestamp: u64,
full_range: bool,
crop: Crop,
}
#[derive(Clone)]
pub(crate) struct Handle(Arc<HandleInner>);
struct HandleInner {
surface: Arc<Surface>,
frame: Arc<FrameToken>,
timestamp: u64,
full_range: bool,
crop: Crop,
}
impl Handle {
pub(crate) fn rgba(&self) -> anyhow::Result<Vec<u8>> {
self.sync()?;
read_surface_rgba(&self.0.surface, self.0.full_range, self.0.crop)
}
fn surface_id(&self) -> VASurfaceID {
self.0.surface.id
}
}
impl DecodedHandle for Handle {
type Frame = FrameToken;
fn video_frame(&self) -> Arc<Self::Frame> {
self.0.frame.clone()
}
fn timestamp(&self) -> u64 {
self.0.timestamp
}
fn coded_resolution(&self) -> Resolution {
self.0.frame.resolution()
}
fn display_resolution(&self) -> Resolution {
self.0.frame.resolution()
}
fn is_ready(&self) -> bool {
false
}
fn sync(&self) -> anyhow::Result<()> {
checked_va("vaSyncSurface", unsafe {
(self.0.surface.context.display.va.vaSyncSurface)(
self.0.surface.context.display.raw,
self.0.surface.id,
)
})
}
}
pub(crate) struct Backend {
display: Arc<Display>,
context: Option<Arc<DecodeContext>>,
stream_info: Option<StreamInfo>,
expected_chroma: Chroma,
expected_width: u32,
expected_height: u32,
crop: Crop,
}
impl Backend {
pub(crate) fn new(
device: &str,
expected_chroma: Chroma,
expected_width: u32,
expected_height: u32,
) -> anyhow::Result<Self> {
Ok(Self {
display: Display::open(device)?,
context: None,
stream_info: None,
expected_chroma,
expected_width,
expected_height,
crop: Crop {
x: 0,
y: 0,
width: expected_width,
height: expected_height,
},
})
}
fn set_sequence(&mut self, sequence: SequenceConfig) -> anyhow::Result<()> {
let SequenceConfig {
profile,
chroma,
coded_width: width,
coded_height: height,
crop,
min_frames,
} = sequence;
let Crop {
x: crop_x,
y: crop_y,
width: display_width,
height: display_height,
} = crop;
if chroma != self.expected_chroma {
return Err(anyhow::anyhow!(
"decoded chroma {chroma:?} does not match negotiated {:?}",
self.expected_chroma
));
}
if width == 0
|| height == 0
|| width > MAX_DIMENSION
|| height > MAX_DIMENSION
|| u64::from(width) * u64::from(height) > MAX_PIXELS
{
return Err(anyhow::anyhow!(
"coded dimensions {width}x{height} exceed decoder limits"
));
}
if display_width != self.expected_width || display_height != self.expected_height {
return Err(anyhow::anyhow!(
"decoded display dimensions {display_width}x{display_height} do not match negotiated {}x{}",
self.expected_width,
self.expected_height
));
}
if crop_x
.checked_add(display_width)
.is_none_or(|right| right > width)
|| crop_y
.checked_add(display_height)
.is_none_or(|bottom| bottom > height)
{
return Err(anyhow::anyhow!(
"decoded crop {crop_x},{crop_y} {display_width}x{display_height} exceeds coded {width}x{height}"
));
}
self.context = Some(DecodeContext::new(
self.display.clone(),
profile,
chroma,
width,
height,
)?);
self.stream_info = Some(StreamInfo {
format: chroma.decoded_format(),
coded_resolution: Resolution::from((width, height)),
display_resolution: Resolution::from((display_width, display_height)),
min_num_frames: min_frames,
});
self.crop = crop;
Ok(())
}
fn allocate_picture(&self, timestamp: u64, full_range: bool) -> NewPictureResult<Picture> {
let context = self.context.as_ref().ok_or_else(|| {
NewPictureError::BackendError(anyhow::anyhow!("VA decoder has no active sequence"))
})?;
Ok(Picture {
surface: Arc::new(
Surface::new(context.clone()).map_err(NewPictureError::BackendError)?,
),
buffers: Vec::new(),
timestamp,
full_range,
crop: self.crop,
})
}
fn create_buffer<T>(&self, kind: i32, values: &[T]) -> anyhow::Result<Buffer> {
let context = self
.context
.as_ref()
.ok_or_else(|| anyhow::anyhow!("VA decoder has no active sequence"))?;
let size = u32::try_from(std::mem::size_of::<T>())?;
let count = u32::try_from(values.len())?;
if size == 0 || count == 0 {
return Err(anyhow::anyhow!("refusing to create an empty VA buffer"));
}
let mut id = 0;
checked_va("vaCreateBuffer", unsafe {
(context.display.va.vaCreateBuffer)(
context.display.raw,
context.context,
kind,
size,
count,
values.as_ptr().cast_mut().cast(),
&mut id,
)
})?;
Ok(Buffer {
context: context.clone(),
id,
})
}
fn submit(&self, picture: Picture) -> StatelessBackendResult<Handle> {
let context = picture.surface.context.clone();
let ids: Vec<_> = picture.buffers.iter().map(|buffer| buffer.id).collect();
checked_va("vaBeginPicture", unsafe {
(context.display.va.vaBeginPicture)(
context.display.raw,
context.context,
picture.surface.id,
)
})?;
let render = checked_va("vaRenderPicture", unsafe {
(context.display.va.vaRenderPicture)(
context.display.raw,
context.context,
ids.as_ptr().cast_mut(),
i32::try_from(ids.len()).unwrap_or(i32::MAX),
)
});
if let Err(error) = render {
// Balance a successful begin even if rendering failed.
unsafe { (context.display.va.vaEndPicture)(context.display.raw, context.context) };
return Err(error.into());
}
checked_va("vaEndPicture", unsafe {
(context.display.va.vaEndPicture)(context.display.raw, context.context)
})?;
let frame = Arc::new(FrameToken {
width: picture.crop.width,
height: picture.crop.height,
chroma: context.chroma,
});
Ok(Handle(Arc::new(HandleInner {
surface: picture.surface,
frame,
timestamp: picture.timestamp,
full_range: picture.full_range,
crop: picture.crop,
})))
}
}
impl StatelessDecoderBackend for Backend {
type Handle = Handle;
fn stream_info(&self) -> Option<&StreamInfo> {
self.stream_info.as_ref()
}
fn reset_backend(&mut self) -> anyhow::Result<()> {
self.context = None;
self.stream_info = None;
Ok(())
}
}
impl StatelessDecoderBackendPicture<H264> for Backend {
type Picture = Picture;
}
impl StatelessDecoderBackendPicture<Av1> for Backend {
type Picture = Picture;
}
// ---------------------------------------------------------------------------
// H.264 VA parameter ABI and stateless backend
// ---------------------------------------------------------------------------
#[repr(C)]
#[derive(Clone, Copy)]
struct VaPictureH264 {
picture_id: u32,
frame_idx: u32,
flags: u32,
top_field_order_cnt: i32,
bottom_field_order_cnt: i32,
reserved: [u32; 4],
}
impl Default for VaPictureH264 {
fn default() -> Self {
Self {
picture_id: VA_INVALID_SURFACE,
frame_idx: 0,
flags: VA_PICTURE_H264_INVALID,
top_field_order_cnt: 0,
bottom_field_order_cnt: 0,
reserved: [0; 4],
}
}
}
#[repr(C)]
struct VaPictureParameterH264 {
current: VaPictureH264,
references: [VaPictureH264; 16],
picture_width_in_mbs_minus1: u16,
picture_height_in_mbs_minus1: u16,
bit_depth_luma_minus8: u8,
bit_depth_chroma_minus8: u8,
num_ref_frames: u8,
seq_fields: u32,
num_slice_groups_minus1: u8,
slice_group_map_type: u8,
slice_group_change_rate_minus1: u16,
pic_init_qp_minus26: i8,
pic_init_qs_minus26: i8,
chroma_qp_index_offset: i8,
second_chroma_qp_index_offset: i8,
pic_fields: u32,
frame_num: u16,
reserved: [u32; 8],
}
#[repr(C)]
struct VaIqMatrixH264 {
scaling_4x4: [[u8; 16]; 6],
scaling_8x8: [[u8; 64]; 2],
reserved: [u32; 4],
}
#[repr(C)]
struct VaSliceParameterH264 {
slice_data_size: u32,
slice_data_offset: u32,
slice_data_flag: u32,
slice_data_bit_offset: u16,
first_mb_in_slice: u16,
slice_type: u8,
direct_spatial_mv_pred_flag: u8,
num_ref_idx_l0_active_minus1: u8,
num_ref_idx_l1_active_minus1: u8,
cabac_init_idc: u8,
slice_qp_delta: i8,
disable_deblocking_filter_idc: u8,
slice_alpha_c0_offset_div2: i8,
slice_beta_offset_div2: i8,
ref_pic_list0: [VaPictureH264; 32],
ref_pic_list1: [VaPictureH264; 32],
luma_log2_weight_denom: u8,
chroma_log2_weight_denom: u8,
luma_weight_l0_flag: u8,
luma_weight_l0: [i16; 32],
luma_offset_l0: [i16; 32],
chroma_weight_l0_flag: u8,
chroma_weight_l0: [[i16; 2]; 32],
chroma_offset_l0: [[i16; 2]; 32],
luma_weight_l1_flag: u8,
luma_weight_l1: [i16; 32],
luma_offset_l1: [i16; 32],
chroma_weight_l1_flag: u8,
chroma_weight_l1: [[i16; 2]; 32],
chroma_offset_l1: [[i16; 2]; 32],
reserved: [u32; 4],
}
fn h264_profile(sps: &Sps) -> anyhow::Result<i32> {
match sps.profile_idc {
66 if sps.constraint_set0_flag => Ok(VAProfileH264ConstrainedBaseline),
66 => Err(anyhow::anyhow!(
"unconstrained H.264 Baseline is not a VA constrained-baseline stream"
)),
77 => Ok(VAProfileH264Main),
88 if sps.constraint_set1_flag => Ok(VAProfileH264Main),
88 => Err(anyhow::anyhow!(
"unsupported unconstrained H.264 Extended profile"
)),
100 => Ok(VAProfileH264High),
// libva 2.x has no H.264 High 4:4:4 Predictive profile. Mapping
// profile_idc 244 to VAProfileH264High would falsely claim an exact
// profile match and is known to be driver-dependent.
244 => Err(anyhow::anyhow!(
"H.264 High 4:4:4 Predictive has no exact VA-API profile"
)),
110 | 122 => Err(anyhow::anyhow!(
"10-bit/4:2:2 H.264 profiles are not camera formats"
)),
profile => Err(anyhow::anyhow!("unsupported H.264 profile_idc {profile}")),
}
}
fn h264_chroma(sps: &Sps) -> anyhow::Result<Chroma> {
if sps.bit_depth_luma_minus8 != 0 || sps.bit_depth_chroma_minus8 != 0 {
return Err(anyhow::anyhow!(
"only 8-bit H.264 camera streams are supported"
));
}
match (sps.chroma_format_idc, sps.separate_colour_plane_flag) {
(1, false) => Ok(Chroma::Cs420),
(3, false) => Ok(Chroma::Cs444),
(format, separate) => Err(anyhow::anyhow!(
"unsupported H.264 chroma_format_idc={format}, separate_colour_plane={separate}"
)),
}
}
fn h264_full_range(sps: &Sps) -> bool {
sps.vui_parameters_present_flag
&& sps.vui_parameters.video_signal_type_present_flag
&& sps.vui_parameters.video_full_range_flag
}
fn va_h264_picture(
picture: &PictureData,
surface_id: VASurfaceID,
merge_other_field: bool,
) -> VaPictureH264 {
let mut flags = match picture.reference() {
Reference::LongTerm => VA_PICTURE_H264_LONG_TERM_REFERENCE,
Reference::ShortTerm => VA_PICTURE_H264_SHORT_TERM_REFERENCE,
Reference::None => 0,
};
let frame_idx = if *picture.reference() == Reference::LongTerm {
picture.long_term_frame_idx
} else {
picture.frame_num
};
let (mut top, mut bottom) = (picture.top_field_order_cnt, picture.bottom_field_order_cnt);
match picture.field {
Field::Frame => {}
Field::Top => {
if merge_other_field {
if let Some(other) = picture.other_field() {
bottom = other.borrow().bottom_field_order_cnt;
} else {
flags |= VA_PICTURE_H264_TOP_FIELD;
bottom = 0;
}
} else {
flags |= VA_PICTURE_H264_TOP_FIELD;
bottom = 0;
}
}
Field::Bottom => {
if merge_other_field {
if let Some(other) = picture.other_field() {
top = other.borrow().top_field_order_cnt;
} else {
flags |= VA_PICTURE_H264_BOTTOM_FIELD;
top = 0;
}
} else {
flags |= VA_PICTURE_H264_BOTTOM_FIELD;
top = 0;
}
}
}
VaPictureH264 {
picture_id: surface_id,
frame_idx,
flags,
top_field_order_cnt: top,
bottom_field_order_cnt: bottom,
reserved: [0; 4],
}
}
fn h264_picture_parameter(
header: &SliceHeader,
current_picture: &PictureData,
current_surface: VASurfaceID,
dpb: &Dpb<Handle>,
sps: &Sps,
pps: &Pps,
) -> VaPictureParameterH264 {
let mut references = [VaPictureH264::default(); 16];
let mut index = 0;
// libva's canonical ordering is all short-term references followed by
// long-term references; the slice reference lists carry prediction order.
for entry in dpb.short_term_refs_iter().chain(dpb.long_term_refs_iter()) {
if index == references.len() {
break;
}
let pic = entry.pic.borrow();
if pic.nonexisting || pic.is_second_field() || !pic.is_ref() {
continue;
}
if let Some(handle) = entry.reference.as_ref() {
references[index] = va_h264_picture(&pic, handle.surface_id(), true);
index += 1;
}
}
let mut seq_fields = u32::from(sps.chroma_format_idc);
seq_fields |= u32::from(sps.separate_colour_plane_flag) << 2;
seq_fields |= u32::from(sps.gaps_in_frame_num_value_allowed_flag) << 3;
seq_fields |= u32::from(sps.frame_mbs_only_flag) << 4;
seq_fields |= u32::from(sps.mb_adaptive_frame_field_flag) << 5;
seq_fields |= u32::from(sps.direct_8x8_inference_flag) << 6;
seq_fields |= u32::from((sps.level_idc as u8) >= 31) << 7;
seq_fields |= u32::from(sps.log2_max_frame_num_minus4) << 8;
seq_fields |= u32::from(sps.pic_order_cnt_type) << 12;
seq_fields |= u32::from(sps.log2_max_pic_order_cnt_lsb_minus4) << 14;
seq_fields |= u32::from(sps.delta_pic_order_always_zero_flag) << 18;
let mut pic_fields = u32::from(pps.entropy_coding_mode_flag);
pic_fields |= u32::from(pps.weighted_pred_flag) << 1;
pic_fields |= u32::from(pps.weighted_bipred_idc) << 2;
pic_fields |= u32::from(pps.transform_8x8_mode_flag) << 4;
pic_fields |= u32::from(header.field_pic_flag) << 5;
pic_fields |= u32::from(pps.constrained_intra_pred_flag) << 6;
pic_fields |= u32::from(pps.bottom_field_pic_order_in_frame_present_flag) << 7;
pic_fields |= u32::from(pps.deblocking_filter_control_present_flag) << 8;
pic_fields |= u32::from(pps.redundant_pic_cnt_present_flag) << 9;
pic_fields |= u32::from(current_picture.nal_ref_idc != 0) << 10;
let field_factor = u32::from(!sps.frame_mbs_only_flag);
let picture_height_in_mbs_minus1 =
((sps.pic_height_in_map_units_minus1 + 1) << field_factor) - 1;
VaPictureParameterH264 {
current: va_h264_picture(current_picture, current_surface, false),
references,
picture_width_in_mbs_minus1: sps.pic_width_in_mbs_minus1,
picture_height_in_mbs_minus1,
bit_depth_luma_minus8: sps.bit_depth_luma_minus8,
bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8,
num_ref_frames: sps.max_num_ref_frames,
seq_fields,
num_slice_groups_minus1: 0,
slice_group_map_type: 0,
slice_group_change_rate_minus1: 0,
pic_init_qp_minus26: pps.pic_init_qp_minus26,
pic_init_qs_minus26: pps.pic_init_qs_minus26,
chroma_qp_index_offset: pps.chroma_qp_index_offset,
second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset,
pic_fields,
frame_num: header.frame_num,
reserved: [0; 8],
}
}
fn h264_iq_matrix(pps: &Pps) -> VaIqMatrixH264 {
let mut scaling_4x4 = [[0; 16]; 6];
let mut scaling_8x8 = [[0; 64]; 2];
for (index, output) in scaling_4x4.iter_mut().enumerate() {
get_raster_from_zigzag_4x4(pps.scaling_lists_4x4[index], output);
}
for (index, output) in scaling_8x8.iter_mut().enumerate() {
get_raster_from_zigzag_8x8(pps.scaling_lists_8x8[index], output);
}
VaIqMatrixH264 {
scaling_4x4,
scaling_8x8,
reserved: [0; 4],
}
}
fn h264_ref_list(list: &[&DpbEntry<Handle>]) -> [VaPictureH264; 32] {
let mut output = [VaPictureH264::default(); 32];
for (slot, entry) in output.iter_mut().zip(list) {
if let Some(handle) = entry.reference.as_ref() {
let pic = entry.pic.borrow();
*slot = va_h264_picture(&pic, handle.surface_id(), pic.field == Field::Frame);
}
}
output
}
fn h264_slice_parameter(
slice: &Slice,
sps: &Sps,
pps: &Pps,
ref_list0: &[&DpbEntry<Handle>],
ref_list1: &[&DpbEntry<Handle>],
) -> VaSliceParameterH264 {
let header = &slice.header;
let weights = &header.pred_weight_table;
let fill_l0 = (pps.weighted_pred_flag
&& (header.slice_type.is_p() || header.slice_type.is_sp()))
|| (pps.weighted_bipred_idc == 1 && header.slice_type.is_b());
let fill_l1 = pps.weighted_bipred_idc == 1 && header.slice_type.is_b();
let chroma_l0 = fill_l0 && sps.chroma_array_type() != 0;
let chroma_l1 = fill_l1 && sps.chroma_array_type() != 0;
VaSliceParameterH264 {
slice_data_size: slice.nalu.size as u32,
slice_data_offset: 0,
slice_data_flag: VA_SLICE_DATA_FLAG_ALL,
slice_data_bit_offset: header.header_bit_size as u16,
first_mb_in_slice: header.first_mb_in_slice as u16,
slice_type: header.slice_type as u8,
direct_spatial_mv_pred_flag: u8::from(header.direct_spatial_mv_pred_flag),
num_ref_idx_l0_active_minus1: header.num_ref_idx_l0_active_minus1,
num_ref_idx_l1_active_minus1: header.num_ref_idx_l1_active_minus1,