forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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