forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

lib.rs540 lines, 17.9 KiBHistoryRawDownload
1// Copyright 2022 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// LOCAL PATCH: vendored verbatim, so its warnings are upstream's business and
6// would otherwise drown out this workspace's own.
7#![allow(warnings)]
8
9//! Implements a lightweight and safe interface over `libva`.
10//!
11//! The starting point to using this crate is to open a [`Display`], from which a [`Context`] and
12//! [`Surface`]s can be allocated and used for doing actual work.
13
14mod bindings;
15pub mod buffer;
16mod config;
17mod context;
18mod display;
19mod generic_value;
20mod image;
21mod picture;
22mod surface;
23mod usage_hint;
24
25pub use bindings::_VADRMPRIMESurfaceDescriptor__bindgen_ty_1 as VADRMPRIMESurfaceDescriptorObject;
26pub use bindings::_VADRMPRIMESurfaceDescriptor__bindgen_ty_2 as VADRMPRIMESurfaceDescriptorLayer;
27pub use bindings::*;
28pub use buffer::*;
29pub use config::*;
30pub use context::*;
31pub use display::*;
32pub use generic_value::*;
33pub use image::*;
34pub use picture::*;
35pub use surface::*;
36pub use usage_hint::*;
37
38use std::num::NonZeroI32;
39
40/// A `VAStatus` that is guaranteed to not be `VA_STATUS_SUCCESS`.
41#[derive(Debug)]
42pub struct VaError(NonZeroI32);
43
44impl VaError {
45 /// Returns the `VAStatus` of this error.
46 pub fn va_status(&self) -> VAStatus {
47 self.0.get() as VAStatus
48 }
49}
50
51impl std::fmt::Display for VaError {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 use std::ffi::CStr;
54
55 // Safe because `vaErrorStr` will return a pointer to a statically allocated, null
56 // terminated C string. The pointer is guaranteed to never be null.
57 let err_str = unsafe { CStr::from_ptr(bindings::vaErrorStr(self.0.get())) }
58 .to_str()
59 .unwrap();
60 f.write_str(err_str)
61 }
62}
63
64impl std::error::Error for VaError {}
65
66/// Checks a VA return value and returns a `VaError` if it is not `VA_STATUS_SUCCESS`.
67///
68/// This can be used on the return value of any VA function returning `VAStatus` in order to
69/// convert it to a proper Rust `Result`.
70fn va_check(code: VAStatus) -> Result<(), VaError> {
71 match code as u32 {
72 bindings::VA_STATUS_SUCCESS => Ok(()),
73 _ => Err(VaError(unsafe { NonZeroI32::new_unchecked(code) })),
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use std::io::Write;
80 use std::rc::Rc;
81
82 use super::*;
83
84 /// Returns a 32-bit CRC for the visible part of `image`, which must be in NV12 format.
85 fn crc_nv12_image(image: &Image) -> u32 {
86 let data = image.as_ref();
87 let va_image = image.image();
88 let offsets = &va_image.offsets;
89 let pitches = &va_image.pitches;
90 let width = va_image.width as usize;
91 let height = va_image.height as usize;
92
93 // We only support NV12 images
94 assert_eq!(va_image.format.fourcc, u32::from_ne_bytes(*b"NV12"));
95 // Consistency check
96 assert_eq!(va_image.num_planes, 2);
97
98 let mut hasher = crc32fast::Hasher::new();
99
100 let offset = offsets[0] as usize;
101 let pitch = pitches[0] as usize;
102 let y_plane = data[offset..(offset + pitch * height)]
103 .chunks(pitch)
104 .map(|line| &line[0..width]);
105
106 let offset = offsets[1] as usize;
107 let pitch = pitches[1] as usize;
108 let uv_plane = data[offset..(offset + pitch * ((height + 1) / 2))]
109 .chunks(pitch)
110 .map(|line| &line[0..width]);
111
112 for line in y_plane.chain(uv_plane) {
113 hasher.update(line);
114 }
115
116 hasher.finalize()
117 }
118
119 #[test]
120 // Ignore this test by default as it requires libva-compatible hardware.
121 #[ignore]
122 fn libva_utils_mpeg2vldemo() {
123 // Adapted from <https://github.com/intel/libva-utils/blob/master/decode/mpeg2vldemo.cpp>
124 let display = Display::open().unwrap();
125
126 assert!(!display.query_vendor_string().unwrap().is_empty());
127 let profiles = display.query_config_profiles().unwrap();
128 assert!(!profiles.is_empty());
129
130 let profile = bindings::VAProfile::VAProfileMPEG2Main;
131 let entrypoints = display.query_config_entrypoints(profile).unwrap();
132 assert!(!entrypoints.is_empty());
133 assert!(entrypoints
134 .iter()
135 .any(|e| *e == bindings::VAEntrypoint::VAEntrypointVLD));
136
137 let format = bindings::VA_RT_FORMAT_YUV420;
138 let width = 16u32;
139 let height = 16u32;
140
141 let mut attrs = vec![bindings::VAConfigAttrib {
142 type_: bindings::VAConfigAttribType::VAConfigAttribRTFormat,
143 value: 0,
144 }];
145
146 let entrypoint = bindings::VAEntrypoint::VAEntrypointVLD;
147 display
148 .get_config_attributes(profile, entrypoint, &mut attrs)
149 .unwrap();
150 assert!(attrs[0].value != bindings::VA_ATTRIB_NOT_SUPPORTED);
151 assert!(attrs[0].value & bindings::VA_RT_FORMAT_YUV420 != 0);
152
153 let config = display.create_config(attrs, profile, entrypoint).unwrap();
154
155 let mut surfaces = display
156 .create_surfaces(
157 format,
158 None,
159 width,
160 height,
161 Some(UsageHint::USAGE_HINT_DECODER),
162 vec![()],
163 )
164 .unwrap();
165 let context = display
166 .create_context(
167 &config,
168 width,
169 ((height + 15) / 16) * 16,
170 Some(&surfaces),
171 true,
172 )
173 .unwrap();
174
175 // The picture data is adapted from libva-utils at decode/mpeg2vldemo.cpp
176 // Data dump of a 16x16 MPEG2 video clip,it has one I frame
177 let mut mpeg2_clip: Vec<u8> = vec![
178 0x00, 0x00, 0x01, 0xb3, 0x01, 0x00, 0x10, 0x13, 0xff, 0xff, 0xe0, 0x18, 0x00, 0x00,
179 0x01, 0xb5, 0x14, 0x8a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0xb8, 0x00, 0x08,
180 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0f, 0xff, 0xf8, 0x00, 0x00, 0x01, 0xb5,
181 0x8f, 0xff, 0xf3, 0x41, 0x80, 0x00, 0x00, 0x01, 0x01, 0x13, 0xe1, 0x00, 0x15, 0x81,
182 0x54, 0xe0, 0x2a, 0x05, 0x43, 0x00, 0x2d, 0x60, 0x18, 0x01, 0x4e, 0x82, 0xb9, 0x58,
183 0xb1, 0x83, 0x49, 0xa4, 0xa0, 0x2e, 0x05, 0x80, 0x4b, 0x7a, 0x00, 0x01, 0x38, 0x20,
184 0x80, 0xe8, 0x05, 0xff, 0x60, 0x18, 0xe0, 0x1d, 0x80, 0x98, 0x01, 0xf8, 0x06, 0x00,
185 0x54, 0x02, 0xc0, 0x18, 0x14, 0x03, 0xb2, 0x92, 0x80, 0xc0, 0x18, 0x94, 0x42, 0x2c,
186 0xb2, 0x11, 0x64, 0xa0, 0x12, 0x5e, 0x78, 0x03, 0x3c, 0x01, 0x80, 0x0e, 0x80, 0x18,
187 0x80, 0x6b, 0xca, 0x4e, 0x01, 0x0f, 0xe4, 0x32, 0xc9, 0xbf, 0x01, 0x42, 0x69, 0x43,
188 0x50, 0x4b, 0x01, 0xc9, 0x45, 0x80, 0x50, 0x01, 0x38, 0x65, 0xe8, 0x01, 0x03, 0xf3,
189 0xc0, 0x76, 0x00, 0xe0, 0x03, 0x20, 0x28, 0x18, 0x01, 0xa9, 0x34, 0x04, 0xc5, 0xe0,
190 0x0b, 0x0b, 0x04, 0x20, 0x06, 0xc0, 0x89, 0xff, 0x60, 0x12, 0x12, 0x8a, 0x2c, 0x34,
191 0x11, 0xff, 0xf6, 0xe2, 0x40, 0xc0, 0x30, 0x1b, 0x7a, 0x01, 0xa9, 0x0d, 0x00, 0xac,
192 0x64,
193 ];
194
195 let picture_coding_extension =
196 MPEG2PictureCodingExtension::new(0, 3, 0, 1, 0, 0, 0, 0, 0, 1, 1);
197 let pic_param = PictureParameterBufferMPEG2::new(
198 16,
199 16,
200 0xffffffff,
201 0xffffffff,
202 1,
203 0xffff,
204 &picture_coding_extension,
205 );
206
207 let pic_param = BufferType::PictureParameter(PictureParameter::MPEG2(pic_param));
208
209 let iq_matrix = IQMatrixBufferMPEG2::new(
210 1,
211 1,
212 0,
213 0,
214 [
215 8, 16, 16, 19, 16, 19, 22, 22, 22, 22, 22, 22, 26, 24, 26, 27, 27, 27, 26, 26, 26,
216 26, 27, 27, 27, 29, 29, 29, 34, 34, 34, 29, 29, 29, 27, 27, 29, 29, 32, 32, 34, 34,
217 37, 38, 37, 35, 35, 34, 35, 38, 38, 40, 40, 40, 48, 48, 46, 46, 56, 56, 58, 69, 69,
218 83,
219 ],
220 [
221 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0, 0,
224 ],
225 [0; 64],
226 [0; 64],
227 );
228
229 let iq_matrix = BufferType::IQMatrix(IQMatrix::MPEG2(iq_matrix));
230
231 let slice_param = SliceParameterBufferMPEG2::new(150, 0, 0, 38, 0, 0, 2, 0);
232
233 let slice_param = BufferType::SliceParameter(SliceParameter::MPEG2(slice_param));
234
235 let test_data_offset = 47;
236 let slice_data = BufferType::SliceData(mpeg2_clip.drain(test_data_offset..).collect());
237
238 let buffers = vec![
239 context.create_buffer(pic_param).unwrap(),
240 context.create_buffer(slice_param).unwrap(),
241 context.create_buffer(iq_matrix).unwrap(),
242 context.create_buffer(slice_data).unwrap(),
243 ];
244
245 let mut picture = Picture::new(0, Rc::clone(&context), surfaces.remove(0));
246 for buffer in buffers {
247 picture.add_buffer(buffer);
248 }
249
250 // Actual client code can just chain the calls.
251 let picture = picture.begin().unwrap();
252 let picture = picture.render().unwrap();
253 let picture = picture.end().unwrap();
254 let picture = picture.sync().map_err(|(e, _)| e).unwrap();
255
256 // Test whether we can map the resulting surface to obtain the raw yuv
257 // data
258 let image_fmts = display.query_image_formats().unwrap();
259 let image_fmt = image_fmts
260 .into_iter()
261 .find(|f| f.fourcc == bindings::VA_FOURCC_NV12)
262 .expect("No valid VAImageFormat found for NV12");
263
264 let resolution = (width, height);
265 let image = picture
266 .create_image(image_fmt, resolution, resolution)
267 .unwrap();
268
269 assert_eq!(crc_nv12_image(&image), 0xa5713e52);
270 }
271
272 #[test]
273 // Ignore this test by default as it requires libva-compatible hardware.
274 #[ignore]
275 fn enc_h264_demo() {
276 // Based on `gst-launch-1.0 videotestsrc num-buffers=1 ! video/x-raw,width=64,height=64,format=NV12 ! vaapih264enc ! filesink location=frame.h264`
277 // Frame created using `gst-launch-1.0 videotestsrc num-buffers=1 ! video/x-raw,width=64,height=64,format=NV12 ! filesink location=src/test_frame.nv12`
278 let raw_frame_nv12 = include_bytes!("test_frame.nv12");
279
280 let display = Display::open().unwrap();
281
282 let format = bindings::VA_RT_FORMAT_YUV420;
283 let entrypoint = bindings::VAEntrypoint::VAEntrypointEncSliceLP;
284 let profile = bindings::VAProfile::VAProfileH264ConstrainedBaseline;
285 let width = 64u32;
286 let height = 64u32;
287
288 let mut attrs = vec![bindings::VAConfigAttrib {
289 type_: bindings::VAConfigAttribType::VAConfigAttribRTFormat,
290 value: 0,
291 }];
292
293 display
294 .get_config_attributes(profile, entrypoint, &mut attrs)
295 .unwrap();
296
297 let config = display.create_config(attrs, profile, entrypoint).unwrap();
298
299 let mut surfaces = display
300 .create_surfaces(
301 format,
302 None,
303 width,
304 height,
305 Some(UsageHint::USAGE_HINT_ENCODER),
306 vec![()],
307 )
308 .unwrap();
309
310 let context = display
311 .create_context(&config, width, height, Some(&surfaces), true)
312 .unwrap();
313
314 let seq_fields = H264EncSeqFields::new(
315 1, // 4:2:0
316 1, // Only frames
317 0, 0, 0, 1, 0, 2, 0,
318 );
319
320 let image_fmts = display.query_image_formats().unwrap();
321 let image_fmt = image_fmts
322 .into_iter()
323 .find(|f| f.fourcc == bindings::VA_FOURCC_NV12)
324 .expect("No valid VAImageFormat found for NV12");
325
326 let surface = surfaces.pop().unwrap();
327 let surface_id = surface.id();
328
329 let coded_buffer = context.create_enc_coded(raw_frame_nv12.len()).unwrap();
330
331 let mut image =
332 Image::create_from(&surface, image_fmt, (width, height), (width, height)).unwrap();
333
334 let va_image = *image.image();
335 let dest = image.as_mut();
336 let data = &raw_frame_nv12[..];
337 let width = width as usize;
338 let height = height as usize;
339
340 let mut src = data;
341 let mut dst = &mut dest[va_image.offsets[0] as usize..];
342
343 // Copy luma
344 for _ in 0..height {
345 dst[..width].copy_from_slice(&src[..width]);
346 dst = &mut dst[va_image.pitches[0] as usize..];
347 src = &src[width..];
348 }
349
350 // Advance to the offset of the chroma plane
351 let mut src = &data[width * height..];
352 let mut dst = &mut dest[va_image.offsets[1] as usize..];
353
354 let height = height / 2;
355
356 // Copy chroma
357 for _ in 0..height {
358 dst[..width].copy_from_slice(&src[..width]);
359 dst = &mut dst[va_image.pitches[1] as usize..];
360 src = &src[width..];
361 }
362 drop(image);
363
364 let sps = BufferType::EncSequenceParameter(EncSequenceParameter::H264(
365 EncSequenceParameterBufferH264::new(
366 0,
367 10,
368 10,
369 30,
370 1,
371 0,
372 1,
373 (width / 16) as u16, // width / 16
374 (height / 16) as u16, // height / 16
375 &seq_fields,
376 0,
377 0,
378 0,
379 0,
380 0,
381 [0; 256],
382 None,
383 Some(H264VuiFields::new(1, 1, 0, 0, 0, 1, 0, 0)),
384 255,
385 1,
386 1,
387 1,
388 60,
389 ),
390 ));
391
392 let sps = context.create_buffer(sps).unwrap();
393
394 let ref_frames: [PictureH264; 16] = (0..16)
395 .map(|_| {
396 PictureH264::new(
397 bindings::VA_INVALID_ID,
398 0,
399 bindings::VA_INVALID_SURFACE,
400 0,
401 0,
402 )
403 })
404 .collect::<Vec<_>>()
405 .try_into()
406 .unwrap_or_else(|_| {
407 panic!();
408 });
409
410 let pps = BufferType::EncPictureParameter(EncPictureParameter::H264(
411 EncPictureParameterBufferH264::new(
412 PictureH264::new(surface_id, 0, 0, 0, 0),
413 ref_frames,
414 coded_buffer.id(),
415 0,
416 0,
417 0,
418 0,
419 26,
420 0,
421 0,
422 0,
423 0,
424 &H264EncPicFields::new(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0),
425 ),
426 ));
427
428 let pps = context.create_buffer(pps).unwrap();
429
430 let ref_pic_list_0: [PictureH264; 32] = (0..32)
431 .map(|_| {
432 PictureH264::new(
433 bindings::VA_INVALID_ID,
434 0,
435 bindings::VA_INVALID_SURFACE,
436 0,
437 0,
438 )
439 })
440 .collect::<Vec<_>>()
441 .try_into()
442 .unwrap_or_else(|_| {
443 panic!();
444 });
445
446 let ref_pic_list_1: [PictureH264; 32] = (0..32)
447 .map(|_| {
448 PictureH264::new(
449 bindings::VA_INVALID_ID,
450 0,
451 bindings::VA_INVALID_SURFACE,
452 0,
453 0,
454 )
455 })
456 .collect::<Vec<_>>()
457 .try_into()
458 .unwrap_or_else(|_| {
459 panic!();
460 });
461
462 let slice = BufferType::EncSliceParameter(EncSliceParameter::H264(
463 EncSliceParameterBufferH264::new(
464 0,
465 ((width / 16) * (height / 16)) as u32,
466 bindings::VA_INVALID_ID,
467 2, // I
468 0,
469 1,
470 0,
471 0,
472 [0, 0],
473 1,
474 0,
475 0,
476 0,
477 ref_pic_list_0,
478 ref_pic_list_1,
479 0,
480 0,
481 0,
482 [0; 32],
483 [0; 32],
484 0,
485 [[0; 2]; 32],
486 [[0; 2]; 32],
487 0,
488 [0; 32],
489 [0; 32],
490 0,
491 [[0; 2]; 32],
492 [[0; 2]; 32],
493 0,
494 0,
495 0,
496 2,
497 2,
498 ),
499 ));
500
501 let slice = context.create_buffer(slice).unwrap();
502
503 let mut picture = Picture::new(0, Rc::clone(&context), surface);
504 picture.add_buffer(pps);
505 picture.add_buffer(sps);
506 picture.add_buffer(slice);
507
508 let picture = picture.begin().unwrap();
509 let picture = picture.render().unwrap();
510 let picture = picture.end().unwrap();
511 let _ = picture.sync().map_err(|(e, _)| e).unwrap();
512
513 let coded_buf = MappedCodedBuffer::new(&coded_buffer).unwrap();
514 assert_ne!(coded_buf.segments().len(), 0);
515
516 for segment in coded_buf.iter() {
517 assert_ne!(segment.buf.len(), 0);
518 }
519
520 const WRITE_TO_FILE: bool = false;
521 if WRITE_TO_FILE {
522 let raw_sps_bitstream: Vec<u8> = vec![
523 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x0a, 0xab, 0x42, 0x12, 0x7f, 0xe0, 0x00,
524 0x20, 0x00, 0x22, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x79, 0x28,
525 ];
526
527 let raw_pps_bitstream: Vec<u8> = vec![0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x3c, 0x80];
528
529 let mut raw_file = std::fs::File::create("libva_utils_enc_h264_demo.h264").unwrap();
530 raw_file.write_all(&raw_sps_bitstream).unwrap();
531 raw_file.write_all(&raw_pps_bitstream).unwrap();
532
533 for segment in coded_buf.segments() {
534 raw_file.write_all(segment.buf).unwrap();
535 }
536
537 raw_file.flush().unwrap();
538 }
539 }
540}