forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

c2_decoder.rs338 lines, 14.1 KiBHistoryRawDownload
1// Copyright 2025 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
5use nix::errno::Errno;
6use nix::sys::epoll::Epoll;
7use nix::sys::epoll::EpollCreateFlags;
8use nix::sys::epoll::EpollEvent;
9use nix::sys::epoll::EpollFlags;
10use nix::sys::epoll::EpollTimeout;
11use nix::sys::eventfd::EventFd;
12
13use std::collections::VecDeque;
14use std::marker::PhantomData;
15use std::os::fd::AsFd;
16#[cfg(feature = "vaapi")]
17use std::path::PathBuf;
18use std::sync::Arc;
19use std::sync::Mutex;
20use thiserror::Error;
21
22use crate::c2_wrapper::C2DecodeJob;
23use crate::c2_wrapper::C2State;
24use crate::c2_wrapper::C2Status;
25use crate::c2_wrapper::C2Worker;
26use crate::c2_wrapper::DrainMode;
27use crate::c2_wrapper::Job;
28use crate::decoder::stateless::DecodeError;
29use crate::decoder::stateless::DynStatelessVideoDecoder;
30use crate::decoder::DecoderEvent;
31use crate::decoder::StreamInfo;
32use crate::image_processing::convert_video_frame;
33use crate::video_frame::frame_pool::FramePool;
34use crate::video_frame::frame_pool::PooledVideoFrame;
35#[cfg(feature = "vaapi")]
36use crate::video_frame::gbm_video_frame::{GbmDevice, GbmUsage, GbmVideoFrame};
37#[cfg(feature = "v4l2")]
38use crate::video_frame::v4l2_mmap_video_frame::V4l2MmapVideoFrame;
39use crate::video_frame::VideoFrame;
40use crate::EncodedFormat;
41use crate::Fourcc;
42
43#[derive(Debug, Error)]
44pub enum C2DecoderPollErrorWrapper {
45 #[error("failed to create Epoll: {0}")]
46 Epoll(Errno),
47 #[error("failed to add poll FDs to Epoll: {0}")]
48 EpollAdd(Errno),
49}
50
51pub trait C2DecoderBackend {
52 type DecoderOptions: Clone + Send + 'static;
53
54 fn new(options: Self::DecoderOptions) -> Result<Self, String>
55 where
56 Self: Sized;
57 fn supported_output_formats(&self) -> Vec<Fourcc>;
58 // TODO: Support stateful video decoders.
59 fn get_decoder<V: VideoFrame + 'static>(
60 &mut self,
61 input_format: EncodedFormat,
62 ) -> Result<DynStatelessVideoDecoder<V>, String>;
63}
64
65#[cfg(feature = "vaapi")]
66type AuxiliaryVideoFrame = GbmVideoFrame;
67#[cfg(feature = "v4l2")]
68type AuxiliaryVideoFrame = V4l2MmapVideoFrame;
69
70// An "importing decoder" can directly import the DMA bufs we are getting, while a "converting
71// decoder" is used for performing image processing routines to convert between the video hardware
72// output and a pixel format that can be consumed by the GPU and display controller.
73// TODO: Come up with a better name for these?
74enum C2Decoder<V: VideoFrame> {
75 ImportingDecoder(DynStatelessVideoDecoder<V>),
76 ConvertingDecoder(DynStatelessVideoDecoder<PooledVideoFrame<AuxiliaryVideoFrame>>),
77}
78
79pub struct C2DecoderWorker<V, B>
80where
81 V: VideoFrame,
82 B: C2DecoderBackend,
83{
84 decoder: C2Decoder<V>,
85 epoll_fd: Epoll,
86 awaiting_job_event: Arc<EventFd>,
87 auxiliary_frame_pool: Option<FramePool<AuxiliaryVideoFrame>>,
88 error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
89 work_done_cb: Arc<Mutex<dyn FnMut(C2DecodeJob<V>) + Send + 'static>>,
90 framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
91 alloc_cb: Arc<Mutex<dyn FnMut() -> Option<V> + Send + 'static>>,
92 work_queue: Arc<Mutex<VecDeque<C2DecodeJob<V>>>>,
93 frame_num: u64,
94 state: Arc<Mutex<C2State>>,
95 _phantom: PhantomData<B>,
96}
97
98impl<V, B> C2DecoderWorker<V, B>
99where
100 V: VideoFrame,
101 B: C2DecoderBackend,
102{
103 // Processes events from the decoder. Primarily these are frame decoded events and DRCs.
104 fn check_events(&mut self) {
105 loop {
106 let stream_info = match &self.decoder {
107 C2Decoder::ImportingDecoder(decoder) => decoder.stream_info().map(|x| x.clone()),
108 C2Decoder::ConvertingDecoder(decoder) => decoder.stream_info().map(|x| x.clone()),
109 };
110 match &mut self.decoder {
111 C2Decoder::ImportingDecoder(decoder) => match decoder.next_event() {
112 Some(DecoderEvent::FrameReady(frame)) => {
113 frame.sync().unwrap();
114 let mut job: C2DecodeJob<V> = Default::default();
115 job.output = Some(frame.video_frame());
116 (*self.work_done_cb.lock().unwrap())(job);
117 }
118 Some(DecoderEvent::FormatChanged) => match stream_info {
119 Some(stream_info) => {
120 (*self.framepool_hint_cb.lock().unwrap())(stream_info.clone());
121 }
122 None => {
123 log::debug!("Could not get stream info after format change!");
124 *self.state.lock().unwrap() = C2State::C2Error;
125 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
126 }
127 },
128 _ => break,
129 },
130 C2Decoder::ConvertingDecoder(decoder) => match decoder.next_event() {
131 Some(DecoderEvent::FrameReady(frame)) => {
132 frame.sync().unwrap();
133 let mut job: C2DecodeJob<V> = Default::default();
134 let mut dst_frame =
135 (*self.alloc_cb.lock().unwrap())().expect("Allocation failed!");
136 let src_frame = &*frame.video_frame();
137 if let Err(err) = convert_video_frame(src_frame, &mut dst_frame) {
138 log::debug!("Error converting VideoFrame! {err}");
139 *self.state.lock().unwrap() = C2State::C2Error;
140 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
141 }
142 job.output = Some(Arc::new(dst_frame));
143 (*self.work_done_cb.lock().unwrap())(job);
144 }
145 Some(DecoderEvent::FormatChanged) => match stream_info {
146 Some(stream_info) => {
147 (*self.framepool_hint_cb.lock().unwrap())(stream_info.clone());
148 self.auxiliary_frame_pool.as_mut().unwrap().resize(&stream_info);
149 }
150 None => {
151 log::debug!("Could not get stream info after format change!");
152 *self.state.lock().unwrap() = C2State::C2Error;
153 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
154 }
155 },
156 _ => break,
157 },
158 }
159 }
160 }
161}
162
163impl<V, B> C2Worker<C2DecodeJob<V>> for C2DecoderWorker<V, B>
164where
165 V: VideoFrame,
166 B: C2DecoderBackend,
167{
168 type Options = <B as C2DecoderBackend>::DecoderOptions;
169
170 fn new(
171 input_fourcc: Fourcc,
172 output_fourcc: Fourcc,
173 awaiting_job_event: Arc<EventFd>,
174 error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
175 work_done_cb: Arc<Mutex<dyn FnMut(C2DecodeJob<V>) + Send + 'static>>,
176 work_queue: Arc<Mutex<VecDeque<C2DecodeJob<V>>>>,
177 state: Arc<Mutex<C2State>>,
178 framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
179 alloc_cb: Arc<Mutex<dyn FnMut() -> Option<V> + Send + 'static>>,
180 options: Self::Options,
181 ) -> Result<Self, String> {
182 let mut backend = B::new(options)?;
183 let backend_fourccs = backend.supported_output_formats();
184 let (auxiliary_frame_pool, decoder) = if backend_fourccs.contains(&output_fourcc) {
185 (
186 None,
187 C2Decoder::ImportingDecoder(
188 backend.get_decoder(EncodedFormat::from(input_fourcc))?,
189 ),
190 )
191 } else {
192 #[cfg(feature = "vaapi")]
193 {
194 let gbm_device = Arc::new(
195 GbmDevice::open(PathBuf::from("/dev/dri/renderD128"))
196 .expect("Could not open GBM device!"),
197 );
198 let framepool = FramePool::new(move |stream_info: &StreamInfo| {
199 // TODO: Query the driver for these alignment params.
200 <Arc<GbmDevice> as Clone>::clone(&gbm_device)
201 .new_frame(
202 Fourcc::from(stream_info.format),
203 stream_info.display_resolution.clone(),
204 stream_info.coded_resolution.clone(),
205 GbmUsage::Decode,
206 )
207 .expect("Could not allocate frame for auxiliary frame pool!")
208 });
209 (
210 Some(framepool),
211 C2Decoder::ConvertingDecoder(
212 backend.get_decoder(EncodedFormat::from(input_fourcc))?,
213 ),
214 )
215 }
216 #[cfg(feature = "v4l2")]
217 {
218 let framepool = FramePool::new(move |stream_info: &StreamInfo| {
219 V4l2MmapVideoFrame::new(
220 Fourcc::from(stream_info.format),
221 stream_info.display_resolution.clone(),
222 )
223 });
224 (
225 Some(framepool),
226 C2Decoder::ConvertingDecoder(
227 backend.get_decoder(EncodedFormat::from(input_fourcc))?,
228 ),
229 )
230 }
231 };
232 Ok(Self {
233 decoder: decoder,
234 auxiliary_frame_pool: auxiliary_frame_pool,
235 epoll_fd: Epoll::new(EpollCreateFlags::empty())
236 .map_err(C2DecoderPollErrorWrapper::Epoll)
237 .unwrap(),
238 awaiting_job_event: awaiting_job_event,
239 error_cb: error_cb,
240 work_done_cb: work_done_cb,
241 framepool_hint_cb: framepool_hint_cb,
242 alloc_cb: alloc_cb,
243 work_queue: work_queue,
244 frame_num: 0,
245 state: state,
246 _phantom: Default::default(),
247 })
248 }
249
250 fn process_loop(&mut self) {
251 self.epoll_fd = Epoll::new(EpollCreateFlags::empty())
252 .map_err(C2DecoderPollErrorWrapper::Epoll)
253 .unwrap();
254 let _ = self
255 .epoll_fd
256 .add(
257 match &self.decoder {
258 C2Decoder::ImportingDecoder(decoder) => decoder.poll_fd(),
259 C2Decoder::ConvertingDecoder(decoder) => decoder.poll_fd(),
260 },
261 EpollEvent::new(EpollFlags::EPOLLIN, 1),
262 )
263 .map_err(C2DecoderPollErrorWrapper::EpollAdd);
264 self.epoll_fd
265 .add(self.awaiting_job_event.as_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 2))
266 .map_err(C2DecoderPollErrorWrapper::EpollAdd)
267 .unwrap();
268
269 while *self.state.lock().unwrap() == C2State::C2Running {
270 // Poll for decoder events or pending job events.
271 let mut events = [EpollEvent::empty()];
272 let _nb_fds = self.epoll_fd.wait(&mut events, EpollTimeout::NONE).unwrap();
273
274 if events == [EpollEvent::new(EpollFlags::EPOLLIN, 2)] {
275 self.awaiting_job_event.read().unwrap();
276 }
277
278 // We want to try sending compressed buffers to the decoder regardless of what event
279 // woke us up, because we either have new work, or we might more output buffers
280 // available.
281 let mut possible_job = (*self.work_queue.lock().unwrap()).pop_front();
282 while let Some(mut job) = possible_job {
283 if job.get_drain() != DrainMode::NoDrain {
284 let flush_result = match &mut self.decoder {
285 C2Decoder::ImportingDecoder(decoder) => decoder.flush(),
286 C2Decoder::ConvertingDecoder(decoder) => decoder.flush(),
287 };
288 if let Err(_) = flush_result {
289 log::debug!("Error handling drain request!");
290 *self.state.lock().unwrap() = C2State::C2Error;
291 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
292 } else {
293 if job.get_drain() == DrainMode::EOSDrain {
294 *self.state.lock().unwrap() = C2State::C2Stopped;
295 }
296 self.check_events();
297 }
298 break;
299 } else {
300 let bitstream = job.input.as_slice();
301 let decode_result = match &mut self.decoder {
302 C2Decoder::ImportingDecoder(decoder) => decoder.decode(
303 self.frame_num,
304 bitstream,
305 &mut *self.alloc_cb.lock().unwrap(),
306 ),
307 C2Decoder::ConvertingDecoder(decoder) => {
308 decoder.decode(self.frame_num, bitstream, &mut || {
309 self.auxiliary_frame_pool.as_mut().unwrap().alloc()
310 })
311 }
312 };
313 match decode_result {
314 Ok(num_bytes) => {
315 self.frame_num += 1;
316 if num_bytes != job.input.len() {
317 job.input = (&job.input[num_bytes..]).to_vec();
318 (*self.work_queue.lock().unwrap()).push_front(job);
319 }
320 }
321 Err(DecodeError::NotEnoughOutputBuffers(_) | DecodeError::CheckEvents) => {
322 (*self.work_queue.lock().unwrap()).push_front(job);
323 break;
324 }
325 Err(e) => {
326 log::debug!("Unhandled error message from decoder {e:?}");
327 *self.state.lock().unwrap() = C2State::C2Error;
328 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
329 break;
330 }
331 }
332 }
333 possible_job = (*self.work_queue.lock().unwrap()).pop_front();
334 }
335 self.check_events();
336 }
337 }
338}