forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

lib.rs472 lines, 14.6 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, 16 bits per sample,
226 /// LE. Only the 10 MSBs are used. LOCAL PATCH (see /Cargo.toml
227 /// [patch.crates-io]): what an HEVC Main 10 stream decodes into.
228 P010,
229 /// One Y and one interleaved UV plane, 4:2:0 sampling, 8 bits per sample.
230 /// In a tiled format.
231 MM21,
232}
233
234impl FromStr for DecodedFormat {
235 type Err = &'static str;
236
237 fn from_str(s: &str) -> Result<Self, Self::Err> {
238 match s {
239 "i420" | "I420" => Ok(DecodedFormat::I420),
240 "i422" | "I422" => Ok(DecodedFormat::I422),
241 "i444" | "I444" => Ok(DecodedFormat::I444),
242 "nv12" | "NV12" => Ok(DecodedFormat::NV12),
243 "i010" | "I010" => Ok(DecodedFormat::I010),
244 "i012" | "I012" => Ok(DecodedFormat::I012),
245 "i210" | "I210" => Ok(DecodedFormat::I210),
246 "i212" | "I212" => Ok(DecodedFormat::I212),
247 "i410" | "I410" => Ok(DecodedFormat::I410),
248 "i412" | "I412" => Ok(DecodedFormat::I412),
249 "p010" | "P010" => Ok(DecodedFormat::P010),
250 "mm21" | "MM21" => Ok(DecodedFormat::MM21),
251 _ => Err("unrecognized output format. \
252 Valid values: i420, nv12, i422, i444, i010, i012, i210, i212, i410, i412, mm21"),
253 }
254 }
255}
256
257impl From<Fourcc> for DecodedFormat {
258 fn from(fourcc: Fourcc) -> DecodedFormat {
259 match fourcc.to_string().as_str() {
260 "I420" => DecodedFormat::I420,
261 "NV12" | "NM12" => DecodedFormat::NV12,
262 "P010" => DecodedFormat::P010,
263 "MM21" => DecodedFormat::MM21,
264 _ => todo!("Fourcc {} not yet supported", fourcc),
265 }
266 }
267}
268
269impl From<DecodedFormat> for Fourcc {
270 fn from(format: DecodedFormat) -> Fourcc {
271 match format {
272 DecodedFormat::I420 => Fourcc::from(b"I420"),
273 DecodedFormat::NV12 => Fourcc::from(b"NV12"),
274 DecodedFormat::P010 => Fourcc::from(b"P010"),
275 DecodedFormat::MM21 => Fourcc::from(b"MM21"),
276 _ => todo!(),
277 }
278 }
279}
280
281#[derive(Debug, PartialEq, Eq, Copy, Clone)]
282pub enum EncodedFormat {
283 H264,
284 H265,
285 VP8,
286 VP9,
287 AV1,
288}
289
290impl FromStr for EncodedFormat {
291 type Err = &'static str;
292
293 fn from_str(s: &str) -> Result<Self, Self::Err> {
294 match s {
295 "h264" | "H264" => Ok(EncodedFormat::H264),
296 "h265" | "H265" => Ok(EncodedFormat::H265),
297 "vp8" | "VP8" => Ok(EncodedFormat::VP8),
298 "vp9" | "VP9" => Ok(EncodedFormat::VP9),
299 "av1" | "AV1" => Ok(EncodedFormat::AV1),
300 _ => Err("unrecognized input format. Valid values: h264, h265, vp8, vp9, av1"),
301 }
302 }
303}
304
305impl From<Fourcc> for EncodedFormat {
306 fn from(fourcc: Fourcc) -> EncodedFormat {
307 match fourcc.to_string().as_str() {
308 "H264" => EncodedFormat::H264,
309 "HEVC" => EncodedFormat::H265,
310 "VP80" => EncodedFormat::VP8,
311 "VP90" => EncodedFormat::VP9,
312 "AV1F" => EncodedFormat::AV1,
313 _ => todo!("Fourcc {} not yet supported", fourcc),
314 }
315 }
316}
317
318impl From<EncodedFormat> for Fourcc {
319 fn from(format: EncodedFormat) -> Fourcc {
320 match format {
321 EncodedFormat::H264 => Fourcc::from(b"H264"),
322 EncodedFormat::H265 => Fourcc::from(b"HEVC"),
323 EncodedFormat::VP8 => Fourcc::from(b"VP80"),
324 EncodedFormat::VP9 => Fourcc::from(b"VP90"),
325 EncodedFormat::AV1 => Fourcc::from(b"AV1F"),
326 }
327 }
328}
329
330/// Describes the layout of a plane within a frame.
331#[derive(Debug, Default, Clone, PartialEq)]
332pub struct PlaneLayout {
333 /// Index of the memory buffer the plane belongs to.
334 pub buffer_index: usize,
335 /// Start offset of the plane within its buffer.
336 pub offset: usize,
337 /// Distance in bytes between two lines of data in this plane.
338 pub stride: usize,
339}
340
341/// Unambiguously describes the layout of a frame.
342///
343/// A frame can be made of one or several memory buffers, each containing one or several planes.
344/// For a given frame, this structure defines where each plane can be found.
345#[derive(Debug, Default, Clone, PartialEq)]
346pub struct FrameLayout {
347 /// `(Fourcc, modifier)` tuple describing the arrangement of the planes.
348 ///
349 /// This member is enough to infer how many planes and buffers the frame has, and which
350 /// buffer each plane belongs into.
351 pub format: (Fourcc, u64),
352 /// Size in pixels of the frame.
353 pub size: Resolution,
354 /// Layout of each individual plane.
355 pub planes: Vec<PlaneLayout>,
356}
357
358/// Build a frame memory descriptor enum that supports multiple descriptor types.
359///
360/// This is useful for the case where the frames' memory backing is not decided at compile-time.
361/// In this case, this macro can be used to list all the potential types supported at run-time, and
362/// the selected one can be built as the program is run.
363///
364/// # Example
365///
366///
367/// use cros_codecs::multiple_desc_type;
368/// use cros_codecs::utils::DmabufFrame;
369///
370/// /// Frames' memory can be provided either by the backend, or via PRIME DMABUF handles.
371/// multiple_desc_type! {
372/// enum OwnedOrDmaDescriptor {
373/// Owned(()),
374/// Dmabuf(DmabufFrame),
375/// }
376/// }
377///
378#[macro_export]
379macro_rules! multiple_desc_type {
380 (enum $s:ident { $($v:ident($t:ty),)* } ) => {
381 pub enum $s {
382 $($v($t),)*
383 }
384
385 #[cfg(feature = "vaapi")]
386 impl libva::SurfaceMemoryDescriptor for $s {
387 fn add_attrs(&mut self, attrs: &mut Vec<libva::VASurfaceAttrib>) -> Option<Box<dyn std::any::Any>> {
388 match self {
389 $($s::$v(desc) => desc.add_attrs(attrs),)*
390 }
391 }
392 }
393 }
394}
395
396/// Returns the size required to store a frame of `format` with size `width`x`height`, without any
397/// padding. This is the minimum size of the destination buffer passed to `nv12_copy` or
398/// `i420_copy`.
399pub fn decoded_frame_size(format: DecodedFormat, width: usize, height: usize) -> usize {
400 match format {
401 DecodedFormat::I420 | DecodedFormat::NV12 => {
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;
405
406 u_size + uv_size
407 }
408 DecodedFormat::I422 => {
409 let u_size = width * height;
410 // U and V planes need to be aligned to 2.
411 let uv_size = ((width + 1) / 2) * ((height + 1) / 2) * 2 * 2;
412
413 u_size + uv_size
414 }
415 DecodedFormat::I444 => (width * height) * 3,
416 DecodedFormat::I010 | DecodedFormat::I012 => {
417 decoded_frame_size(DecodedFormat::I420, width, height) * 2
418 }
419 DecodedFormat::I210 | DecodedFormat::I212 => {
420 let u_size = width * height * 2;
421 // U and V planes need to be aligned to 2.
422 let uv_size = ((width + 1) / 2) * ((height + 1) / 2) * 2 * 2;
423
424 u_size + uv_size
425 }
426 DecodedFormat::I410 | DecodedFormat::I412 => (width * height * 2) * 3,
427 // LOCAL PATCH: NV12 with 16-bit samples.
428 DecodedFormat::P010 => decoded_frame_size(DecodedFormat::NV12, width, height) * 2,
429 DecodedFormat::MM21 => panic!("Unable to convert to MM21"),
430 }
431}
432
433/// Instructs on whether it should block on the operation(s).
434#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
435pub enum BlockingMode {
436 Blocking,
437 #[default]
438 NonBlocking,
439}
440
441#[cfg(test)]
442mod tests {
443 use super::Fourcc;
444
445 const NV12_FOURCC: u32 = 0x3231564E;
446
447 #[test]
448 fn fourcc_u32() {
449 let fourcc = Fourcc::from(NV12_FOURCC);
450 let value: u32 = fourcc.into();
451 assert_eq!(value, NV12_FOURCC);
452 }
453
454 #[test]
455 fn fourcc_u8_4() {
456 let fourcc = Fourcc::from(NV12_FOURCC);
457 let value: [u8; 4] = fourcc.into();
458 assert_eq!(value, *b"NV12");
459 }
460
461 #[test]
462 fn fourcc_display() {
463 let fourcc = Fourcc::from(NV12_FOURCC);
464 assert_eq!(fourcc.to_string(), "NV12");
465 }
466
467 #[test]
468 fn fourcc_debug() {
469 let fourcc = Fourcc::from(NV12_FOURCC);
470 assert_eq!(format!("{:?}", fourcc), "0x3231564e (NV12)");
471 }
472}