forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

lib.rs463 lines, 14.1 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//! This crate provides tools to help decode and encode various video codecs, leveraging the
10//! hardware acceleration available on the target.
11//!
12//! The [codec] module contains tools to parse encoded video streams like H.264 or VP9 and extract
13//! the information useful in order to perform e.g. hardware-accelerated decoding.
14//!
15//! The [backend] module contains common backend code. A backend is a provider of some way to
16//! decode or encode a particular codec, like VAAPI.
17//!
18//! The [decoder] module contains decoders that can turn an encoded video stream into a sequence of
19//! decoded frames using the hardware acceleration available on the host.
20//!
21//! The [encoder] module contains encoder that can turn a picture sequence into a compressed
22//! sequence of decodable encoded packets using the hardware acceleration available on the host.
23//!
24//! The [utils] module contains some useful code that is shared between different parts of this
25//! crate and didn't fit any of the modules above.
26
27pub mod bitstream_utils;
28pub mod codec;
29
30#[cfg(feature = "backend")]
31pub mod backend;
32#[cfg(feature = "backend")]
33pub mod c2_wrapper;
34#[cfg(feature = "backend")]
35pub mod decoder;
36#[cfg(feature = "v4l2")]
37pub mod device;
38#[cfg(feature = "backend")]
39pub mod encoder;
40#[cfg(feature = "backend")]
41pub mod image_processing;
42#[cfg(feature = "backend")]
43pub mod utils;
44#[cfg(feature = "backend")]
45pub mod video_frame;
46
47use std::str::FromStr;
48
49#[cfg(feature = "vaapi")]
50pub use libva;
51#[cfg(feature = "v4l2")]
52pub use v4l2r;
53
54#[derive(Debug, PartialEq, Eq, Copy, Clone)]
55pub enum FrameMemoryType {
56 Managed,
57 Prime,
58 User,
59}
60
61impl FromStr for FrameMemoryType {
62 type Err = &'static str;
63
64 fn from_str(s: &str) -> Result<Self, Self::Err> {
65 match s {
66 "managed" => Ok(FrameMemoryType::Managed),
67 "prime" => Ok(FrameMemoryType::Prime),
68 "user" => Ok(FrameMemoryType::User),
69 _ => Err("unrecognized memory type. Valid values: managed, prime, user"),
70 }
71 }
72}
73
74/// Rounding modes for `Resolution`
75#[derive(Copy, Clone, Debug, PartialEq, Eq)]
76pub enum ResolutionRoundMode {
77 /// Rounds component-wise to the next even value.
78 Even,
79}
80
81/// A frame resolution in pixels.
82#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
83pub struct Resolution {
84 pub width: u32,
85 pub height: u32,
86}
87
88impl Resolution {
89 /// Whether `self` can contain `other`.
90 pub fn can_contain(&self, other: Self) -> bool {
91 self.width >= other.width && self.height >= other.height
92 }
93
94 /// Rounds `self` according to `rnd_mode`.
95 pub fn round(mut self, rnd_mode: ResolutionRoundMode) -> Self {
96 match rnd_mode {
97 ResolutionRoundMode::Even => {
98 if self.width % 2 != 0 {
99 self.width += 1;
100 }
101
102 if self.height % 2 != 0 {
103 self.height += 1;
104 }
105 }
106 }
107
108 self
109 }
110
111 pub fn get_area(&self) -> usize {
112 (self.width as usize) * (self.height as usize)
113 }
114}
115
116impl From<(u32, u32)> for Resolution {
117 fn from(value: (u32, u32)) -> Self {
118 Self { width: value.0, height: value.1 }
119 }
120}
121
122impl From<Resolution> for (u32, u32) {
123 fn from(value: Resolution) -> Self {
124 (value.width, value.height)
125 }
126}
127
128#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
129pub struct Rect {
130 pub x: u32,
131 pub y: u32,
132 pub width: u32,
133 pub height: u32,
134}
135
136impl From<Rect> for Resolution {
137 fn from(value: Rect) -> Self {
138 Self { width: value.width - value.x, height: value.height - value.y }
139 }
140}
141
142impl From<Resolution> for Rect {
143 fn from(value: Resolution) -> Self {
144 Self { x: 0, y: 0, width: value.width, height: value.height }
145 }
146}
147
148impl From<((u32, u32), (u32, u32))> for Rect {
149 fn from(value: ((u32, u32), (u32, u32))) -> Self {
150 Self { x: value.0 .0, y: value.0 .1, width: value.1 .0, height: value.1 .1 }
151 }
152}
153/// Wrapper around u32 when they are meant to be a fourcc.
154///
155/// Provides conversion and display/debug implementations useful when dealing with fourcc codes.
156#[derive(Clone, Copy, Default, PartialEq)]
157pub struct Fourcc(u32);
158
159impl From<u32> for Fourcc {
160 fn from(fourcc: u32) -> Self {
161 Self(fourcc)
162 }
163}
164
165impl From<Fourcc> for u32 {
166 fn from(fourcc: Fourcc) -> Self {
167 fourcc.0
168 }
169}
170
171impl From<&[u8; 4]> for Fourcc {
172 fn from(n: &[u8; 4]) -> Self {
173 Self(n[0] as u32 | (n[1] as u32) << 8 | (n[2] as u32) << 16 | (n[3] as u32) << 24)
174 }
175}
176
177impl From<Fourcc> for [u8; 4] {
178 fn from(n: Fourcc) -> Self {
179 [n.0 as u8, (n.0 >> 8) as u8, (n.0 >> 16) as u8, (n.0 >> 24) as u8]
180 }
181}
182
183impl std::fmt::Display for Fourcc {
184 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185 let c: [u8; 4] = (*self).into();
186
187 f.write_fmt(format_args!(
188 "{}{}{}{}",
189 c[0] as char, c[1] as char, c[2] as char, c[3] as char
190 ))
191 }
192}
193
194impl std::fmt::Debug for Fourcc {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 f.write_fmt(format_args!("0x{:08x} ({})", self.0, self))
197 }
198}
199
200/// Formats that buffers can be mapped into for the CPU to read.
201///
202/// The conventions here largely follow these of libyuv.
203#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
204pub enum DecodedFormat {
205 /// Y, U and V planes, 4:2:0 sampling, 8 bits per sample.
206 I420,
207 /// One Y and one interleaved UV plane, 4:2:0 sampling, 8 bits per sample.
208 NV12,
209 /// Y, U and V planes, 4:2:2 sampling, 8 bits per sample.
210 I422,
211 /// Y, U and V planes, 4:4:4 sampling, 8 bits per sample.
212 I444,
213 /// Y, U and V planes, 4:2:0 sampling, 16 bits per sample, LE. Only the 10 LSBs are used.
214 I010,
215 /// Y, U and V planes, 4:2:0 sampling, 16 bits per sample, LE. Only the 12 LSBs are used.
216 I012,
217 /// Y, U and V planes, 4:2:2 sampling, 16 bits per sample, LE. Only the 10 LSBs are used.
218 I210,
219 /// Y, U and V planes, 4:2:2 sampling, 16 bits per sample, LE. Only the 12 LSBs are used.
220 I212,
221 /// Y, U and V planes, 4:4:4 sampling, 16 bits per sample, LE. Only the 10 LSBs are used.
222 I410,
223 /// Y, U and V planes, 4:4:4 sampling, 16 bits per sample, LE. Only the 12 LSBs are used.
224 I412,
225 /// One Y and one interleaved UV plane, 4:2:0 sampling, 8 bits per sample.
226 /// In a tiled format.
227 MM21,
228}
229
230impl FromStr for DecodedFormat {
231 type Err = &'static str;
232
233 fn from_str(s: &str) -> Result<Self, Self::Err> {
234 match s {
235 "i420" | "I420" => Ok(DecodedFormat::I420),
236 "i422" | "I422" => Ok(DecodedFormat::I422),
237 "i444" | "I444" => Ok(DecodedFormat::I444),
238 "nv12" | "NV12" => Ok(DecodedFormat::NV12),
239 "i010" | "I010" => Ok(DecodedFormat::I010),
240 "i012" | "I012" => Ok(DecodedFormat::I012),
241 "i210" | "I210" => Ok(DecodedFormat::I210),
242 "i212" | "I212" => Ok(DecodedFormat::I212),
243 "i410" | "I410" => Ok(DecodedFormat::I410),
244 "i412" | "I412" => Ok(DecodedFormat::I412),
245 "mm21" | "MM21" => Ok(DecodedFormat::MM21),
246 _ => Err("unrecognized output format. \
247 Valid values: i420, nv12, i422, i444, i010, i012, i210, i212, i410, i412, mm21"),
248 }
249 }
250}
251
252impl From<Fourcc> for DecodedFormat {
253 fn from(fourcc: Fourcc) -> DecodedFormat {
254 match fourcc.to_string().as_str() {
255 "I420" => DecodedFormat::I420,
256 "NV12" | "NM12" => DecodedFormat::NV12,
257 "MM21" => DecodedFormat::MM21,
258 _ => todo!("Fourcc {} not yet supported", fourcc),
259 }
260 }
261}
262
263impl From<DecodedFormat> for Fourcc {
264 fn from(format: DecodedFormat) -> Fourcc {
265 match format {
266 DecodedFormat::I420 => Fourcc::from(b"I420"),
267 DecodedFormat::NV12 => Fourcc::from(b"NV12"),
268 DecodedFormat::MM21 => Fourcc::from(b"MM21"),
269 _ => todo!(),
270 }
271 }
272}
273
274#[derive(Debug, PartialEq, Eq, Copy, Clone)]
275pub enum EncodedFormat {
276 H264,
277 H265,
278 VP8,
279 VP9,
280 AV1,
281}
282
283impl FromStr for EncodedFormat {
284 type Err = &'static str;
285
286 fn from_str(s: &str) -> Result<Self, Self::Err> {
287 match s {
288 "h264" | "H264" => Ok(EncodedFormat::H264),
289 "h265" | "H265" => Ok(EncodedFormat::H265),
290 "vp8" | "VP8" => Ok(EncodedFormat::VP8),
291 "vp9" | "VP9" => Ok(EncodedFormat::VP9),
292 "av1" | "AV1" => Ok(EncodedFormat::AV1),
293 _ => Err("unrecognized input format. Valid values: h264, h265, vp8, vp9, av1"),
294 }
295 }
296}
297
298impl From<Fourcc> for EncodedFormat {
299 fn from(fourcc: Fourcc) -> EncodedFormat {
300 match fourcc.to_string().as_str() {
301 "H264" => EncodedFormat::H264,
302 "HEVC" => EncodedFormat::H265,
303 "VP80" => EncodedFormat::VP8,
304 "VP90" => EncodedFormat::VP9,
305 "AV1F" => EncodedFormat::AV1,
306 _ => todo!("Fourcc {} not yet supported", fourcc),
307 }
308 }
309}
310
311impl From<EncodedFormat> for Fourcc {
312 fn from(format: EncodedFormat) -> Fourcc {
313 match format {
314 EncodedFormat::H264 => Fourcc::from(b"H264"),
315 EncodedFormat::H265 => Fourcc::from(b"HEVC"),
316 EncodedFormat::VP8 => Fourcc::from(b"VP80"),
317 EncodedFormat::VP9 => Fourcc::from(b"VP90"),
318 EncodedFormat::AV1 => Fourcc::from(b"AV1F"),
319 }
320 }
321}
322
323/// Describes the layout of a plane within a frame.
324#[derive(Debug, Default, Clone, PartialEq)]
325pub struct PlaneLayout {
326 /// Index of the memory buffer the plane belongs to.
327 pub buffer_index: usize,
328 /// Start offset of the plane within its buffer.
329 pub offset: usize,
330 /// Distance in bytes between two lines of data in this plane.
331 pub stride: usize,
332}
333
334/// Unambiguously describes the layout of a frame.
335///
336/// A frame can be made of one or several memory buffers, each containing one or several planes.
337/// For a given frame, this structure defines where each plane can be found.
338#[derive(Debug, Default, Clone, PartialEq)]
339pub struct FrameLayout {
340 /// `(Fourcc, modifier)` tuple describing the arrangement of the planes.
341 ///
342 /// This member is enough to infer how many planes and buffers the frame has, and which
343 /// buffer each plane belongs into.
344 pub format: (Fourcc, u64),
345 /// Size in pixels of the frame.
346 pub size: Resolution,
347 /// Layout of each individual plane.
348 pub planes: Vec<PlaneLayout>,
349}
350
351/// Build a frame memory descriptor enum that supports multiple descriptor types.
352///
353/// This is useful for the case where the frames' memory backing is not decided at compile-time.
354/// In this case, this macro can be used to list all the potential types supported at run-time, and
355/// the selected one can be built as the program is run.
356///
357/// # Example
358///
359///
360/// use cros_codecs::multiple_desc_type;
361/// use cros_codecs::utils::DmabufFrame;
362///
363/// /// Frames' memory can be provided either by the backend, or via PRIME DMABUF handles.
364/// multiple_desc_type! {
365/// enum OwnedOrDmaDescriptor {
366/// Owned(()),
367/// Dmabuf(DmabufFrame),
368/// }
369/// }
370///
371#[macro_export]
372macro_rules! multiple_desc_type {
373 (enum $s:ident { $($v:ident($t:ty),)* } ) => {
374 pub enum $s {
375 $($v($t),)*
376 }
377
378 #[cfg(feature = "vaapi")]
379 impl libva::SurfaceMemoryDescriptor for $s {
380 fn add_attrs(&mut self, attrs: &mut Vec<libva::VASurfaceAttrib>) -> Option<Box<dyn std::any::Any>> {
381 match self {
382 $($s::$v(desc) => desc.add_attrs(attrs),)*
383 }
384 }
385 }
386 }
387}
388
389/// Returns the size required to store a frame of `format` with size `width`x`height`, without any
390/// padding. This is the minimum size of the destination buffer passed to `nv12_copy` or
391/// `i420_copy`.
392pub fn decoded_frame_size(format: DecodedFormat, width: usize, height: usize) -> usize {
393 match format {
394 DecodedFormat::I420 | DecodedFormat::NV12 => {
395 let u_size = width * height;
396 // U and V planes need to be aligned to 2.
397 let uv_size = ((width + 1) / 2) * ((height + 1) / 2) * 2;
398
399 u_size + uv_size
400 }
401 DecodedFormat::I422 => {
402 let u_size = width * height;
403 // U and V planes need to be aligned to 2.
404 let uv_size = ((width + 1) / 2) * ((height + 1) / 2) * 2 * 2;
405
406 u_size + uv_size
407 }
408 DecodedFormat::I444 => (width * height) * 3,
409 DecodedFormat::I010 | DecodedFormat::I012 => {
410 decoded_frame_size(DecodedFormat::I420, width, height) * 2
411 }
412 DecodedFormat::I210 | DecodedFormat::I212 => {
413 let u_size = width * height * 2;
414 // U and V planes need to be aligned to 2.
415 let uv_size = ((width + 1) / 2) * ((height + 1) / 2) * 2 * 2;
416
417 u_size + uv_size
418 }
419 DecodedFormat::I410 | DecodedFormat::I412 => (width * height * 2) * 3,
420 DecodedFormat::MM21 => panic!("Unable to convert to MM21"),
421 }
422}
423
424/// Instructs on whether it should block on the operation(s).
425#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
426pub enum BlockingMode {
427 Blocking,
428 #[default]
429 NonBlocking,
430}
431
432#[cfg(test)]
433mod tests {
434 use super::Fourcc;
435
436 const NV12_FOURCC: u32 = 0x3231564E;
437
438 #[test]
439 fn fourcc_u32() {
440 let fourcc = Fourcc::from(NV12_FOURCC);
441 let value: u32 = fourcc.into();
442 assert_eq!(value, NV12_FOURCC);
443 }
444
445 #[test]
446 fn fourcc_u8_4() {
447 let fourcc = Fourcc::from(NV12_FOURCC);
448 let value: [u8; 4] = fourcc.into();
449 assert_eq!(value, *b"NV12");
450 }
451
452 #[test]
453 fn fourcc_display() {
454 let fourcc = Fourcc::from(NV12_FOURCC);
455 assert_eq!(fourcc.to_string(), "NV12");
456 }
457
458 #[test]
459 fn fourcc_debug() {
460 let fourcc = Fourcc::from(NV12_FOURCC);
461 assert_eq!(format!("{:?}", fourcc), "0x3231564e (NV12)");
462 }
463}