• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 use std::error::Error;
6 use std::fmt::Display;
7 use std::fmt::Formatter;
8 
9 use base::MappedRegion;
10 use base::MemoryMappingArena;
11 use base::MmapError;
12 use ffmpeg::avcodec::AvBuffer;
13 use ffmpeg::avcodec::AvBufferSource;
14 use ffmpeg::avcodec::AvError;
15 use ffmpeg::avcodec::AvFrame;
16 use ffmpeg::avcodec::AvFrameError;
17 use ffmpeg::avcodec::AvPixelFormat;
18 use ffmpeg::avcodec::Dimensions;
19 use ffmpeg::avcodec::PlaneDescriptor;
20 use thiserror::Error as ThisError;
21 
22 use crate::virtio::video::format::Format;
23 use crate::virtio::video::resource::BufferHandle;
24 use crate::virtio::video::resource::GuestResource;
25 
26 /// A simple wrapper that turns a [`MemoryMappingArena`] into an [`AvBufferSource`].
27 ///
28 /// **Note:** Only use this if you can reasonably assume the mapped memory won't be written to from
29 /// another thread or the VM! The reason [`AvBufferSource`] is not directly implemented on
30 /// [`MemoryMappingArena`] is exactly due to this unsafety: If the guest or someone else writes to
31 /// the buffer FFmpeg is currently reading from or writing to, undefined behavior might occur. This
32 /// struct acts as an opt-in mechanism for this potential unsafety.
33 pub struct MemoryMappingAvBufferSource(MemoryMappingArena);
34 
35 impl From<MemoryMappingArena> for MemoryMappingAvBufferSource {
from(inner: MemoryMappingArena) -> Self36     fn from(inner: MemoryMappingArena) -> Self {
37         Self(inner)
38     }
39 }
40 impl AvBufferSource for MemoryMappingAvBufferSource {
as_ptr(&self) -> *const u841     fn as_ptr(&self) -> *const u8 {
42         self.0.as_ptr() as _
43     }
44 
len(&self) -> usize45     fn len(&self) -> usize {
46         self.0.size()
47     }
48 }
49 
50 pub trait TryAsAvFrameExt {
51     type BufferSource;
52     type Error: Error;
53 
54     /// Try to create an [`AvFrame`] from `self`.
55     ///
56     /// `wrapper` is a constructor for `T` that wraps `Self::BufferSource` and implement the
57     /// `AvBufferSource` functionality. This can be used to provide a custom destructor
58     /// implementation: for example, sending a virtio message signaling the buffer source is no
59     /// longer used and it can be recycled by the guest.
60     ///
61     /// Note that `Self::BufferSource` might not always implement `AvBufferSource`. For instance,
62     /// it's not guaranteed that a `MemoryMappingArena` created from `GuestResource` will be always
63     /// immutable, and the backend need to explicit acknowledge the potential unsoundness by
64     /// wrapping it in [`MemoryMappingAvBufferSource`].
try_as_av_frame<T: AvBufferSource + 'static>( &self, wrapper: impl FnOnce(Self::BufferSource) -> T, ) -> Result<AvFrame, Self::Error>65     fn try_as_av_frame<T: AvBufferSource + 'static>(
66         &self,
67         wrapper: impl FnOnce(Self::BufferSource) -> T,
68     ) -> Result<AvFrame, Self::Error>;
69 }
70 
71 #[derive(Debug, ThisError)]
72 pub enum GuestResourceToAvFrameError {
73     #[error("error while creating the AvFrame: {0}")]
74     AvFrameError(#[from] AvFrameError),
75     #[error("cannot mmap guest resource: {0}")]
76     MappingResource(#[from] MmapError),
77     #[error("virtio resource format is not convertible to AvPixelFormat")]
78     InvalidFormat,
79     #[error("out of memory while allocating AVBuffer")]
80     CannotAllocateAvBuffer,
81 }
82 
83 impl From<AvError> for GuestResourceToAvFrameError {
from(e: AvError) -> Self84     fn from(e: AvError) -> Self {
85         GuestResourceToAvFrameError::AvFrameError(AvFrameError::AvError(e))
86     }
87 }
88 
89 impl TryAsAvFrameExt for GuestResource {
90     type BufferSource = MemoryMappingArena;
91     type Error = GuestResourceToAvFrameError;
92 
try_as_av_frame<T: AvBufferSource + 'static>( &self, wrapper: impl FnOnce(MemoryMappingArena) -> T, ) -> Result<AvFrame, Self::Error>93     fn try_as_av_frame<T: AvBufferSource + 'static>(
94         &self,
95         wrapper: impl FnOnce(MemoryMappingArena) -> T,
96     ) -> Result<AvFrame, Self::Error> {
97         let mut builder = AvFrame::builder()?;
98         builder.set_dimensions(Dimensions {
99             width: self.width,
100             height: self.height,
101         })?;
102         let format = self
103             .format
104             .try_into()
105             .map_err(|_| GuestResourceToAvFrameError::InvalidFormat)?;
106         builder.set_format(format)?;
107         let planes = &self.planes;
108         // We have at least one plane, so we can unwrap below.
109         let len = format.plane_sizes(planes.iter().map(|p| p.stride as _), self.height)?;
110         let start = planes.iter().map(|p| p.offset).min().unwrap();
111         let end = planes
112             .iter()
113             .enumerate()
114             .map(|(i, p)| p.offset + len[i])
115             .max()
116             .unwrap();
117         let mapping = self.handle.get_mapping(start, end - start)?;
118         Ok(builder.build_owned(
119             [AvBuffer::new(wrapper(mapping))
120                 .ok_or(GuestResourceToAvFrameError::CannotAllocateAvBuffer)?],
121             planes.iter().map(|p| PlaneDescriptor {
122                 buffer_index: 0,
123                 offset: p.offset - start,
124                 stride: p.stride,
125             }),
126         )?)
127     }
128 }
129 
130 /// The error returned when converting between `AvPixelFormat` and `Format` and there's no
131 /// applicable format.
132 // The empty field prevents constructing this and allows extending it in the future.
133 #[derive(Debug)]
134 pub struct TryFromFormatError(());
135 
136 impl Display for TryFromFormatError {
fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result137     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
138         write!(
139             f,
140             "No matching format to convert between AvPixelFormat and Format"
141         )
142     }
143 }
144 
145 impl Error for TryFromFormatError {}
146 
147 impl TryFrom<Format> for AvPixelFormat {
148     type Error = TryFromFormatError;
149 
try_from(value: Format) -> Result<Self, Self::Error>150     fn try_from(value: Format) -> Result<Self, Self::Error> {
151         use ffmpeg::*;
152         AvPixelFormat::try_from(match value {
153             Format::NV12 => AVPixelFormat_AV_PIX_FMT_NV12,
154             Format::YUV420 => AVPixelFormat_AV_PIX_FMT_YUV420P,
155             _ => return Err(TryFromFormatError(())),
156         })
157         .map_err(|_|
158             // The error case should never happen as long as we use valid constant values, but
159             // don't panic in case something goes wrong.
160             TryFromFormatError(()))
161     }
162 }
163 
164 impl TryFrom<AvPixelFormat> for Format {
165     type Error = TryFromFormatError;
166 
try_from(fmt: AvPixelFormat) -> Result<Self, Self::Error>167     fn try_from(fmt: AvPixelFormat) -> Result<Self, Self::Error> {
168         // https://github.com/rust-lang/rust/issues/39371 Lint wrongly warns the consumer
169         #![allow(non_upper_case_globals)]
170         use ffmpeg::*;
171         Ok(match fmt.pix_fmt() {
172             AVPixelFormat_AV_PIX_FMT_NV12 => Format::NV12,
173             AVPixelFormat_AV_PIX_FMT_YUV420P => Format::YUV420,
174             _ => return Err(TryFromFormatError(())),
175         })
176     }
177 }
178