edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·7f487c1·Tahinli·3 months ago·659 commits
| 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 | |
| 5 | use nix::sys::epoll::Epoll; |
| 6 | use nix::sys::epoll::EpollCreateFlags; |
| 7 | use nix::sys::epoll::EpollEvent; |
| 8 | use nix::sys::epoll::EpollFlags; |
| 9 | use nix::sys::epoll::EpollTimeout; |
| 10 | use nix::sys::eventfd::EventFd; |
| 11 | |
| 12 | use std::collections::VecDeque; |
| 13 | use std::marker::PhantomData; |
| 14 | use std::os::fd::AsFd; |
| 15 | use std::sync::atomic::Ordering; |
| 16 | use std::sync::Arc; |
| 17 | use std::sync::Mutex; |
| 18 | use std::time::Duration; |
| 19 | |
| 20 | use crate::c2_wrapper::C2EncodeJob; |
| 21 | use crate::c2_wrapper::C2State; |
| 22 | use crate::c2_wrapper::C2Status; |
| 23 | use crate::c2_wrapper::C2Worker; |
| 24 | use crate::c2_wrapper::DrainMode; |
| 25 | use crate::c2_wrapper::Job; |
| 26 | use crate::decoder::StreamInfo; |
| 27 | use crate::encoder::FrameMetadata; |
| 28 | use crate::encoder::RateControl; |
| 29 | use crate::encoder::RateControl::ConstantBitrate; |
| 30 | use crate::encoder::RateControl::ConstantQuality; |
| 31 | use crate::encoder::Tunings; |
| 32 | use crate::encoder::VideoEncoder; |
| 33 | use crate::image_processing::convert_video_frame; |
| 34 | use crate::image_processing::extend_border_nv12; |
| 35 | #[cfg(feature = "v4l2")] |
| 36 | use crate::video_frame::V4l2VideoFrame; |
| 37 | use crate::video_frame::VideoFrame; |
| 38 | use crate::video_frame::UV_PLANE; |
| 39 | use crate::video_frame::Y_PLANE; |
| 40 | use crate::DecodedFormat; |
| 41 | use crate::EncodedFormat; |
| 42 | use crate::Fourcc; |
| 43 | use crate::Resolution; |
| 44 | |
| 45 | pub 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 | |
| 67 | pub struct C2EncoderWorker<V, B> |
| 68 | where |
| 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 | |
| 89 | impl<V, B> C2EncoderWorker<V, B> |
| 90 | where |
| 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 | |
| 114 | impl<V, B> C2Worker<C2EncodeJob<V>> for C2EncoderWorker<V, B> |
| 115 | where |
| 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 | } |