forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

c2_encoder.rs272 lines, 10.9 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::sys::epoll::Epoll;
6use nix::sys::epoll::EpollCreateFlags;
7use nix::sys::epoll::EpollEvent;
8use nix::sys::epoll::EpollFlags;
9use nix::sys::epoll::EpollTimeout;
10use nix::sys::eventfd::EventFd;
11
12use std::collections::VecDeque;
13use std::marker::PhantomData;
14use std::os::fd::AsFd;
15use std::sync::atomic::Ordering;
16use std::sync::Arc;
17use std::sync::Mutex;
18use std::time::Duration;
19
20use crate::c2_wrapper::C2EncodeJob;
21use crate::c2_wrapper::C2State;
22use crate::c2_wrapper::C2Status;
23use crate::c2_wrapper::C2Worker;
24use crate::c2_wrapper::DrainMode;
25use crate::c2_wrapper::Job;
26use crate::decoder::StreamInfo;
27use crate::encoder::FrameMetadata;
28use crate::encoder::RateControl;
29use crate::encoder::RateControl::ConstantBitrate;
30use crate::encoder::RateControl::ConstantQuality;
31use crate::encoder::Tunings;
32use crate::encoder::VideoEncoder;
33use crate::image_processing::convert_video_frame;
34use crate::image_processing::extend_border_nv12;
35#[cfg(feature = "v4l2")]
36use crate::video_frame::V4l2VideoFrame;
37use crate::video_frame::VideoFrame;
38use crate::video_frame::UV_PLANE;
39use crate::video_frame::Y_PLANE;
40use crate::DecodedFormat;
41use crate::EncodedFormat;
42use crate::Fourcc;
43use crate::Resolution;
44
45pub trait C2EncoderBackend {
46 type EncoderOptions: Clone + Send + 'static;
47
48 fn new(options: Self::EncoderOptions) -> Result<Self, String>
49 where
50 Self: Sized;
51
52 // Returns a new encoder, the visible resolution, and the coded resolution.
53 #[cfg(feature = "vaapi")]
54 fn get_encoder<V: VideoFrame>(
55 &mut self,
56 input_format: DecodedFormat,
57 output_format: EncodedFormat,
58 ) -> Result<(Box<dyn VideoEncoder<V>>, Resolution, Resolution), String>;
59 #[cfg(feature = "v4l2")]
60 fn get_encoder<V: VideoFrame>(
61 &mut self,
62 input_format: DecodedFormat,
63 output_format: EncodedFormat,
64 ) -> Result<(Box<dyn VideoEncoder<V4l2VideoFrame<V>>>, Resolution, Resolution), String>;
65}
66
67pub struct C2EncoderWorker<V, B>
68where
69 V: VideoFrame,
70 B: C2EncoderBackend,
71{
72 #[cfg(feature = "vaapi")]
73 encoder: Box<dyn VideoEncoder<V>>,
74 #[cfg(feature = "v4l2")]
75 encoder: Box<dyn VideoEncoder<V4l2VideoFrame<V>>>,
76 awaiting_job_event: Arc<EventFd>,
77 error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
78 work_done_cb: Arc<Mutex<dyn FnMut(C2EncodeJob<V>) + Send + 'static>>,
79 alloc_cb: Arc<Mutex<dyn FnMut() -> Option<V> + Send + 'static>>,
80 work_queue: Arc<Mutex<VecDeque<C2EncodeJob<V>>>>,
81 in_flight_queue: VecDeque<C2EncodeJob<V>>,
82 state: Arc<Mutex<C2State>>,
83 current_tunings: Tunings,
84 visible_resolution: Resolution,
85 coded_resolution: Resolution,
86 _phantom: PhantomData<B>,
87}
88
89impl<V, B> C2EncoderWorker<V, B>
90where
91 V: VideoFrame,
92 B: C2EncoderBackend,
93{
94 fn poll_complete_frames(&mut self) {
95 loop {
96 match self.encoder.poll() {
97 Ok(Some(coded)) => {
98 let mut job = self.in_flight_queue.pop_front().unwrap();
99 job.output = coded.bitstream;
100 (*self.work_done_cb.lock().unwrap())(job);
101 }
102 Err(err) => {
103 log::debug!("Error during encode! {:?}", err);
104 *self.state.lock().unwrap() = C2State::C2Error;
105 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
106 break;
107 }
108 _ => break,
109 }
110 }
111 }
112}
113
114impl<V, B> C2Worker<C2EncodeJob<V>> for C2EncoderWorker<V, B>
115where
116 V: VideoFrame,
117 B: C2EncoderBackend,
118{
119 type Options = B::EncoderOptions;
120
121 fn new(
122 input_fourcc: Fourcc,
123 output_fourcc: Fourcc,
124 awaiting_job_event: Arc<EventFd>,
125 error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
126 work_done_cb: Arc<Mutex<dyn FnMut(C2EncodeJob<V>) + Send + 'static>>,
127 work_queue: Arc<Mutex<VecDeque<C2EncodeJob<V>>>>,
128 state: Arc<Mutex<C2State>>,
129 framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
130 alloc_cb: Arc<Mutex<dyn FnMut() -> Option<V> + Send + 'static>>,
131 options: Self::Options,
132 ) -> Result<Self, String> {
133 let mut backend = B::new(options)?;
134 let (encoder, visible_resolution, coded_resolution) = backend
135 .get_encoder(DecodedFormat::from(input_fourcc), EncodedFormat::from(output_fourcc))?;
136 (*framepool_hint_cb.lock().unwrap())(StreamInfo {
137 format: DecodedFormat::from(input_fourcc),
138 coded_resolution: coded_resolution.clone(),
139 display_resolution: visible_resolution.clone(),
140 // Needs to be equal to the pipeline depth, which is decided by the client. Ideally, we
141 // will never need these temp frames though if Gralloc works properly.
142 min_num_frames: 0,
143 });
144
145 Ok(Self {
146 encoder: encoder,
147 awaiting_job_event: awaiting_job_event,
148 error_cb: error_cb,
149 work_done_cb: work_done_cb,
150 work_queue: work_queue,
151 in_flight_queue: VecDeque::new(),
152 state: state,
153 alloc_cb: alloc_cb,
154 current_tunings: Default::default(),
155 visible_resolution: visible_resolution,
156 coded_resolution: coded_resolution,
157 _phantom: Default::default(),
158 })
159 }
160
161 fn process_loop(&mut self) {
162 let epoll_fd = Epoll::new(EpollCreateFlags::empty()).expect("Failed to create Epoll");
163 let _ = epoll_fd
164 .add(self.awaiting_job_event.as_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 1))
165 .expect("Failed to add job event to Epoll");
166
167 while *self.state.lock().unwrap() == C2State::C2Running {
168 let mut events = [EpollEvent::empty()];
169 // We need an actual timeout because the encoder is poll based rather than async.
170 let _ = epoll_fd
171 .wait(&mut events, EpollTimeout::try_from(Duration::from_millis(10)).unwrap())
172 .expect("Epoll wait failed");
173 if events != [EpollEvent::new(EpollFlags::EPOLLIN, 1)] {
174 self.poll_complete_frames();
175 continue;
176 }
177
178 self.awaiting_job_event.read().unwrap();
179
180 // Unlike the decoder, we can assume a 1:1 relationship between jobs in the work_queue
181 // and wake-up events. The encoders are not asynchronous, so the only events we will
182 // ever wake-up for are jobs being added to the work_queue.
183 let mut job = (*self.work_queue.lock().unwrap())
184 .pop_front()
185 .expect("Missing job from work queue!");
186 if job.get_drain() != DrainMode::NoDrain {
187 if let Err(err) = self.encoder.drain() {
188 log::debug!("Error draining encoder! {:?}", err);
189 *self.state.lock().unwrap() = C2State::C2Error;
190 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
191 break;
192 }
193 if job.get_drain() == DrainMode::EOSDrain {
194 *self.state.lock().unwrap() = C2State::C2Stopped;
195 }
196 } else {
197 let frame_y_stride = job.input.as_ref().unwrap().get_plane_pitch()[0];
198 let frame_y_size = job.input.as_ref().unwrap().get_plane_size()[0];
199 let can_import_frame = frame_y_stride == self.coded_resolution.width as usize
200 && frame_y_size >= self.coded_resolution.get_area();
201 let frame = if can_import_frame {
202 job.input.take().unwrap()
203 } else {
204 let mut tmp = (*self.alloc_cb.lock().unwrap())().expect("Allocation failed!");
205
206 if let Err(_) = convert_video_frame(job.input.as_ref().unwrap(), &mut tmp) {
207 log::debug!("Failed to copy input frame to properly aligned buffer!");
208 *self.state.lock().unwrap() = C2State::C2Error;
209 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
210 break;
211 }
212 {
213 let tmp_mapping = tmp.map_mut().expect("Failed to map tmp frame!");
214 let tmp_planes = tmp_mapping.get();
215 extend_border_nv12(
216 *tmp_planes[Y_PLANE].borrow_mut(),
217 *tmp_planes[UV_PLANE].borrow_mut(),
218 self.visible_resolution.width as usize,
219 self.visible_resolution.height as usize,
220 self.coded_resolution.width as usize,
221 self.coded_resolution.height as usize,
222 );
223 }
224
225 tmp
226 };
227
228 let curr_bitrate = match self.current_tunings.rate_control {
229 ConstantBitrate(bitrate) => bitrate,
230 ConstantQuality(_) => {
231 log::debug!("CQ encoding not currently supported");
232 *self.state.lock().unwrap() = C2State::C2Error;
233 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
234 break;
235 }
236 };
237 let new_framerate = job.framerate.load(Ordering::Relaxed);
238 if job.bitrate != curr_bitrate || new_framerate != self.current_tunings.framerate {
239 self.current_tunings.rate_control = RateControl::ConstantBitrate(job.bitrate);
240 self.current_tunings.framerate = new_framerate;
241 if let Err(err) = self.encoder.tune(self.current_tunings.clone()) {
242 log::debug!("Error adjusting tunings! {:?}", err);
243 *self.state.lock().unwrap() = C2State::C2Error;
244 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
245 break;
246 }
247 };
248
249 let meta = FrameMetadata {
250 timestamp: job.timestamp,
251 layout: Default::default(),
252 force_keyframe: false,
253 };
254 #[cfg(feature = "vaapi")]
255 let encode_result = self.encoder.encode(meta, frame);
256 #[cfg(feature = "v4l2")]
257 let encode_result = self.encoder.encode(meta, V4l2VideoFrame(frame));
258 match encode_result {
259 Ok(_) => self.in_flight_queue.push_back(job),
260 Err(err) => {
261 log::debug!("Error encoding frame! {:?}", err);
262 *self.state.lock().unwrap() = C2State::C2Error;
263 (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
264 break;
265 }
266 }
267 }
268
269 self.poll_complete_frames();
270 }
271 }
272}