forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

c2_wrapper.rs381 lines, 11.7 KiBHistoryRawDownload
1// Copyright 2024 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::eventfd::EfdFlags;
7use nix::sys::eventfd::EventFd;
8
9use thiserror::Error;
10
11use std::collections::VecDeque;
12use std::marker::PhantomData;
13use std::sync::atomic::AtomicU32;
14use std::sync::Arc;
15use std::sync::Mutex;
16use std::thread;
17use std::thread::JoinHandle;
18use std::vec::Vec;
19
20use crate::decoder::StreamInfo;
21use crate::video_frame::VideoFrame;
22use crate::Fourcc;
23
24pub mod c2_decoder;
25pub mod c2_encoder;
26#[cfg(feature = "v4l2")]
27pub mod c2_v4l2_decoder;
28#[cfg(feature = "v4l2")]
29pub mod c2_v4l2_encoder;
30#[cfg(feature = "vaapi")]
31pub mod c2_vaapi_decoder;
32#[cfg(feature = "vaapi")]
33pub mod c2_vaapi_encoder;
34
35#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
36pub enum DrainMode {
37 // Not draining
38 #[default]
39 NoDrain = -1,
40 // Drain the C2 component and signal an EOS. Currently we also change the state to stop.
41 EOSDrain = 0,
42 // Drain the C2 component, but keep accepting new jobs in the queue immediately after.
43 NoEOSDrain = 1,
44}
45
46#[derive(Debug)]
47pub struct C2DecodeJob<V: VideoFrame> {
48 // Compressed input data
49 // TODO: Use VideoFrame for input too
50 pub input: Vec<u8>,
51 // Decompressed output frame. Note that this needs to be reference counted because we may still
52 // use this frame as a reference frame even while we're displaying it.
53 pub output: Option<Arc<V>>,
54 pub drain: DrainMode,
55 // TODO: Add output delay and color aspect support as needed.
56}
57
58impl<V> Job for C2DecodeJob<V>
59where
60 V: VideoFrame,
61{
62 type Frame = V;
63
64 fn set_drain(&mut self, drain: DrainMode) {
65 self.drain = drain;
66 }
67
68 fn get_drain(&self) -> DrainMode {
69 self.drain
70 }
71}
72
73impl<V: VideoFrame> Default for C2DecodeJob<V> {
74 fn default() -> Self {
75 Self { input: vec![], output: None, drain: DrainMode::NoDrain }
76 }
77}
78
79pub trait Job: Send + 'static {
80 type Frame: VideoFrame;
81
82 fn set_drain(&mut self, drain: DrainMode) -> ();
83 fn get_drain(&self) -> DrainMode;
84}
85
86#[derive(Debug)]
87pub struct C2EncodeJob<V: VideoFrame> {
88 pub input: Option<V>,
89 // TODO: Use VideoFrame for output too
90 pub output: Vec<u8>,
91 // In microseconds.
92 pub timestamp: u64,
93 // TODO: only support CBR right now, follow up with VBR support.
94 pub bitrate: u64,
95 // Framerate is actually negotiated, so the encoder can change this value
96 // based on the timestamps of the frames it receives.
97 pub framerate: Arc<AtomicU32>,
98 pub drain: DrainMode,
99}
100
101impl<V: VideoFrame> Default for C2EncodeJob<V> {
102 fn default() -> Self {
103 Self {
104 input: None,
105 output: vec![],
106 timestamp: 0,
107 bitrate: 0,
108 framerate: Arc::new(AtomicU32::new(0)),
109 drain: DrainMode::NoDrain,
110 }
111 }
112}
113
114impl<V> Job for C2EncodeJob<V>
115where
116 V: VideoFrame,
117{
118 type Frame = V;
119
120 fn set_drain(&mut self, drain: DrainMode) {
121 self.drain = drain;
122 }
123
124 fn get_drain(&self) -> DrainMode {
125 self.drain
126 }
127}
128
129#[derive(Debug, PartialEq, Eq, Copy, Clone)]
130pub enum C2State {
131 C2Running,
132 C2Stopped,
133 // Note that on state C2Error, stop() must be called before we can start()
134 // again.
135 C2Error,
136}
137
138// This is not a very "Rust-y" way of doing error handling, but it will
139// hopefully make the FFI easier to write. Numerical values taken from
140// frameworks/av/media/codec2/core/include/C2.h
141// TODO: Improve error handling by adding more statuses.
142#[derive(Debug, PartialEq, Eq, Copy, Clone)]
143pub enum C2Status {
144 C2Ok = 0,
145 C2BadState = 1, // EPERM
146 C2BadValue = 22, // EINVAL
147}
148
149// J should be either C2DecodeJob or C2EncodeJob.
150pub trait C2Worker<J>
151where
152 J: Send + Job + 'static,
153{
154 type Options: Clone + Send + 'static;
155
156 fn new(
157 input_fourcc: Fourcc,
158 output_fourcc: Fourcc,
159 awaiting_job_event: Arc<EventFd>,
160 error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
161 work_done_cb: Arc<Mutex<dyn FnMut(J) + Send + 'static>>,
162 work_queue: Arc<Mutex<VecDeque<J>>>,
163 state: Arc<Mutex<C2State>>,
164 framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
165 alloc_cb: Arc<Mutex<dyn FnMut() -> Option<<J as Job>::Frame> + Send + 'static>>,
166 options: Self::Options,
167 ) -> Result<Self, String>
168 where
169 Self: Sized;
170
171 fn process_loop(&mut self);
172}
173
174#[derive(Debug, Error)]
175pub enum C2WrapperError {
176 #[error("failed to create EventFd for awaiting job event: {0}")]
177 AwaitingJobEventFd(Errno),
178}
179
180// Note that we do not guarantee thread safety in C2CrosCodecsWrapper.
181pub struct C2Wrapper<J, W>
182where
183 J: Send + Default + Job + 'static,
184 W: C2Worker<J>,
185{
186 awaiting_job_event: Arc<EventFd>,
187 input_fourcc: Fourcc,
188 output_fourcc: Fourcc,
189 error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
190 work_done_cb: Arc<Mutex<dyn FnMut(J) + Send + 'static>>,
191 work_queue: Arc<Mutex<VecDeque<J>>>,
192 state: Arc<Mutex<C2State>>,
193 framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
194 alloc_cb: Arc<Mutex<dyn FnMut() -> Option<<J as Job>::Frame> + Send + 'static>>,
195 options: <W as C2Worker<J>>::Options,
196 worker_thread: Option<JoinHandle<()>>,
197 // The instance of V actually lives in the thread creation closure, not
198 // this struct.
199 _phantom: PhantomData<W>,
200}
201
202impl<J, W> C2Wrapper<J, W>
203where
204 J: Send + Default + Job + 'static,
205 W: C2Worker<J>,
206{
207 pub fn new(
208 input_fourcc: Fourcc,
209 output_fourcc: Fourcc,
210 error_cb: impl FnMut(C2Status) + Send + 'static,
211 work_done_cb: impl FnMut(J) + Send + 'static,
212 framepool_hint_cb: impl FnMut(StreamInfo) + Send + 'static,
213 alloc_cb: impl FnMut() -> Option<<J as Job>::Frame> + Send + 'static,
214 options: <W as C2Worker<J>>::Options,
215 ) -> Self {
216 Self {
217 awaiting_job_event: Arc::new(
218 EventFd::from_flags(EfdFlags::EFD_SEMAPHORE)
219 .map_err(C2WrapperError::AwaitingJobEventFd)
220 .unwrap(),
221 ),
222 input_fourcc: input_fourcc,
223 output_fourcc: output_fourcc,
224 error_cb: Arc::new(Mutex::new(error_cb)),
225 work_done_cb: Arc::new(Mutex::new(work_done_cb)),
226 work_queue: Arc::new(Mutex::new(VecDeque::new())),
227 state: Arc::new(Mutex::new(C2State::C2Stopped)),
228 framepool_hint_cb: Arc::new(Mutex::new(framepool_hint_cb)),
229 alloc_cb: Arc::new(Mutex::new(alloc_cb)),
230 options: options,
231 worker_thread: None,
232 _phantom: Default::default(),
233 }
234 }
235
236 // This isn't part of C2, but it's convenient to check if our worker thread
237 // is still running.
238 pub fn is_alive(&self) -> bool {
239 match &self.worker_thread {
240 Some(worker_thread) => !worker_thread.is_finished(),
241 None => false,
242 }
243 }
244
245 // Start the decoder/encoder.
246 // State will be C2Running after this call.
247 pub fn start(&mut self) -> C2Status {
248 {
249 let mut state = self.state.lock().unwrap();
250 if *state != C2State::C2Stopped {
251 (*self.error_cb.lock().unwrap())(C2Status::C2BadState);
252 return C2Status::C2BadState;
253 }
254 *state = C2State::C2Running;
255 }
256
257 let input_fourcc = self.input_fourcc.clone();
258 let output_fourcc = self.output_fourcc.clone();
259 let error_cb = self.error_cb.clone();
260 let work_done_cb = self.work_done_cb.clone();
261 let work_queue = self.work_queue.clone();
262 let state = self.state.clone();
263 let options = self.options.clone();
264 let awaiting_job_event = self.awaiting_job_event.clone();
265 let framepool_hint_cb = self.framepool_hint_cb.clone();
266 let alloc_cb = self.alloc_cb.clone();
267 self.worker_thread = Some(thread::spawn(move || {
268 let worker = W::new(
269 input_fourcc,
270 output_fourcc,
271 awaiting_job_event,
272 error_cb.clone(),
273 work_done_cb,
274 work_queue,
275 state.clone(),
276 framepool_hint_cb,
277 alloc_cb,
278 options,
279 );
280 match worker {
281 Ok(mut worker) => worker.process_loop(),
282 Err(msg) => {
283 log::debug!("Error instantiating C2Worker {}", msg);
284 *state.lock().unwrap() = C2State::C2Error;
285 (*error_cb.lock().unwrap())(C2Status::C2BadValue);
286 }
287 };
288 }));
289
290 C2Status::C2Ok
291 }
292
293 // Stop the decoder/encoder and abandon in-flight work.
294 // C2's reset() function is equivalent for our purposes.
295 // Note that in event of error, stop() must be called before we can start()
296 // again. This is to ensure we clear out the work queue.
297 // State will be C2Stopped after this call.
298 pub fn stop(&mut self) -> C2Status {
299 *self.state.lock().unwrap() = C2State::C2Stopped;
300 let mut worker_thread: Option<JoinHandle<()>> = None;
301 std::mem::swap(&mut worker_thread, &mut self.worker_thread);
302 self.worker_thread = match worker_thread {
303 Some(worker_thread) => {
304 let _ = worker_thread.join();
305 None
306 }
307 None => None,
308 };
309
310 self.work_queue.lock().unwrap().drain(..);
311
312 self.awaiting_job_event.write(1).unwrap();
313
314 C2Status::C2Ok
315 }
316
317 // Add work to the work queue.
318 // State must be C2Running or this function is invalid.
319 // State will remain C2Running.
320 pub fn queue(&mut self, work_items: Vec<J>) -> C2Status {
321 if *self.state.lock().unwrap() != C2State::C2Running {
322 (*self.error_cb.lock().unwrap())(C2Status::C2BadState);
323 return C2Status::C2BadState;
324 }
325
326 self.work_queue.lock().unwrap().extend(work_items.into_iter());
327
328 self.awaiting_job_event.write(1).unwrap();
329
330 C2Status::C2Ok
331 }
332
333 // Flush work from the queue and return it as |flushed_work|.
334 // State will not change after this call.
335 // TODO: Support different flush modes.
336 pub fn flush(&mut self, flushed_work: &mut Vec<J>) -> C2Status {
337 if *self.state.lock().unwrap() != C2State::C2Running {
338 (*self.error_cb.lock().unwrap())(C2Status::C2BadState);
339 return C2Status::C2BadState;
340 }
341
342 let mut tmp = self.work_queue.lock().unwrap().drain(..).collect::<Vec<J>>();
343 flushed_work.append(&mut tmp);
344
345 C2Status::C2Ok
346 }
347
348 // Signal to the decoder/encoder that it does not need to wait for
349 // additional work to begin processing. This is an unusual name for this
350 // function, but it is the convention that C2 uses.
351 // State must be C2Running or this function is invalid.
352 // State will remain C2Running until the last frames drain, at which point
353 // the state will change to C2Stopped.
354 // TODO: Support different drain modes.
355 pub fn drain(&mut self, mode: DrainMode) -> C2Status {
356 if *self.state.lock().unwrap() != C2State::C2Running {
357 (*self.error_cb.lock().unwrap())(C2Status::C2BadState);
358 return C2Status::C2BadState;
359 }
360
361 let mut drain_job: J = Default::default();
362 drain_job.set_drain(mode);
363 self.work_queue.lock().unwrap().push_back(drain_job);
364
365 self.awaiting_job_event.write(1).unwrap();
366
367 C2Status::C2Ok
368 }
369}
370
371// Instead of C2's release() function, we implement Drop and use RAII to
372// accomplish the same thing
373impl<J, W> Drop for C2Wrapper<J, W>
374where
375 J: Send + Default + Job + 'static,
376 W: C2Worker<J>,
377{
378 fn drop(&mut self) {
379 self.stop();
380 }
381}