edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ef5832f·Tahinli·3 months ago·597 commits
| 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 | |
| 5 | use std::fmt; |
| 6 | |
| 7 | pub mod av1; |
| 8 | pub mod h264; |
| 9 | pub mod h265; |
| 10 | pub mod vp8; |
| 11 | pub mod vp9; |
| 12 | |
| 13 | pub mod stateful; |
| 14 | pub mod stateless; |
| 15 | |
| 16 | use crate::codec::av1::synthesizer::SynthesizerError as AV1SynthesizerError; |
| 17 | use crate::codec::h264::synthesizer::SynthesizerError as H264SynthesizerError; |
| 18 | use crate::codec::h265::synthesizer::SynthesizerError as H265SynthesizerError; |
| 19 | use crate::encoder::stateful::StatefulBackendError; |
| 20 | use crate::encoder::stateless::StatelessBackendError; |
| 21 | use crate::FrameLayout; |
| 22 | |
| 23 | /// Specifies the encoder operation |
| 24 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 25 | pub enum RateControl { |
| 26 | /// The encoder shall maintain the constant bitrate |
| 27 | ConstantBitrate(u64), |
| 28 | |
| 29 | /// The encoder shall maintain codec specific quality parameter constant (eg. QP for H.264) |
| 30 | /// disregarding bitrate. |
| 31 | ConstantQuality(u32), |
| 32 | } |
| 33 | |
| 34 | impl RateControl { |
| 35 | #[allow(dead_code)] |
| 36 | pub(crate) fn is_same_variant(left: &Self, right: &Self) -> bool { |
| 37 | std::mem::discriminant(left) == std::mem::discriminant(right) |
| 38 | } |
| 39 | |
| 40 | pub(crate) fn bitrate_target(&self) -> Option<u64> { |
| 41 | match self { |
| 42 | RateControl::ConstantBitrate(target) => Some(*target), |
| 43 | RateControl::ConstantQuality(_) => None, |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | #[derive(Clone)] |
| 49 | pub enum PredictionStructure { |
| 50 | /// Simplest prediction structure, suitable eg. for RTC. Interframe is produced at the start of |
| 51 | /// the stream and every time when `limit` frames are reached. Following interframe frames |
| 52 | /// are frames relying solely on the last frame. |
| 53 | LowDelay { limit: u16 }, |
| 54 | } |
| 55 | |
| 56 | /// Dynamic parameters of the encoded stream that client may choose to change during the encoding |
| 57 | /// session without recreating the entire encoder instance. |
| 58 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 59 | pub struct Tunings { |
| 60 | /// The stream's [`RateControl`] |
| 61 | pub rate_control: RateControl, |
| 62 | /// Stream framerate in frames per second |
| 63 | pub framerate: u32, |
| 64 | /// Minimum value of codec specific quality parameter constant (eg. QP for H.264) |
| 65 | pub min_quality: u32, |
| 66 | /// Maximum value of codec specific quality parameter constant (eg. QP for H.264) |
| 67 | pub max_quality: u32, |
| 68 | } |
| 69 | |
| 70 | impl Default for Tunings { |
| 71 | fn default() -> Self { |
| 72 | Self { |
| 73 | rate_control: RateControl::ConstantBitrate(200_000), |
| 74 | framerate: 30, |
| 75 | min_quality: 0, |
| 76 | max_quality: u32::MAX, |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Encoder's input metadata |
| 82 | #[derive(Debug, Clone)] |
| 83 | pub struct FrameMetadata { |
| 84 | pub timestamp: u64, |
| 85 | pub layout: FrameLayout, |
| 86 | pub force_keyframe: bool, |
| 87 | } |
| 88 | |
| 89 | /// Encoder's coded output with contained frame. |
| 90 | pub struct CodedBitstreamBuffer { |
| 91 | /// [`FrameMetadata`] of the frame that is compressed in [`Self::bitstream`] |
| 92 | pub metadata: FrameMetadata, |
| 93 | |
| 94 | /// Bitstream with compressed frame together with optionally other compressed control messages |
| 95 | pub bitstream: Vec<u8>, |
| 96 | } |
| 97 | |
| 98 | impl CodedBitstreamBuffer { |
| 99 | pub fn new(metadata: FrameMetadata, bitstream: Vec<u8>) -> Self { |
| 100 | Self { metadata, bitstream } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | impl From<CodedBitstreamBuffer> for Vec<u8> { |
| 105 | fn from(value: CodedBitstreamBuffer) -> Self { |
| 106 | value.bitstream |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | #[derive(Debug)] |
| 111 | pub enum EncodeError { |
| 112 | Unsupported, |
| 113 | InvalidInternalState, |
| 114 | StatelessBackendError(StatelessBackendError), |
| 115 | StatefulBackendError(StatefulBackendError), |
| 116 | H264SynthesizerError(H264SynthesizerError), |
| 117 | H265SynthesizerError(H265SynthesizerError), |
| 118 | AV1SynthesizerError(AV1SynthesizerError), |
| 119 | } |
| 120 | |
| 121 | impl fmt::Display for EncodeError { |
| 122 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 123 | match self { |
| 124 | EncodeError::Unsupported => write!(f, "unsupported"), |
| 125 | EncodeError::InvalidInternalState => { |
| 126 | write!(f, "invalid internal state. This is likely a bug.") |
| 127 | } |
| 128 | EncodeError::StatelessBackendError(x) => write!(f, "{}", x.to_string()), |
| 129 | EncodeError::StatefulBackendError(x) => write!(f, "{}", x.to_string()), |
| 130 | EncodeError::H264SynthesizerError(x) => write!(f, "{}", x.to_string()), |
| 131 | EncodeError::H265SynthesizerError(x) => write!(f, "{}", x.to_string()), |
| 132 | EncodeError::AV1SynthesizerError(x) => write!(f, "{}", x.to_string()), |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | impl From<StatelessBackendError> for EncodeError { |
| 138 | fn from(err: StatelessBackendError) -> Self { |
| 139 | EncodeError::StatelessBackendError(err) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | impl From<StatefulBackendError> for EncodeError { |
| 144 | fn from(err: StatefulBackendError) -> Self { |
| 145 | EncodeError::StatefulBackendError(err) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | impl From<H264SynthesizerError> for EncodeError { |
| 150 | fn from(err: H264SynthesizerError) -> Self { |
| 151 | EncodeError::H264SynthesizerError(err) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | impl From<H265SynthesizerError> for EncodeError { |
| 156 | fn from(err: H265SynthesizerError) -> Self { |
| 157 | EncodeError::H265SynthesizerError(err) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | impl From<AV1SynthesizerError> for EncodeError { |
| 162 | fn from(err: AV1SynthesizerError) -> Self { |
| 163 | EncodeError::AV1SynthesizerError(err) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | pub type EncodeResult<T> = Result<T, EncodeError>; |
| 168 | |
| 169 | /// Generic video encoder interface. |
| 170 | pub trait VideoEncoder<Handle> { |
| 171 | /// Changes dynamic parameters (aka [`Tunings`]) of the encoded stream. The change may not be |
| 172 | /// effective right away. Depending on the used prediction structure, the `Predictor` may |
| 173 | /// choose to delay the change until entire or a some part of the structure had been encoded. |
| 174 | /// |
| 175 | /// Note: Currently changing the variant of [`RateControl`] is not supported. |
| 176 | fn tune(&mut self, tunings: Tunings) -> EncodeResult<()>; |
| 177 | |
| 178 | /// Enqueues the frame for encoding. The implementation will drop the handle after it is no |
| 179 | /// longer be needed. The encoder is not required to immediately start processing the frame |
| 180 | /// and yield output bitstream. It is allowed to hold frames until certain conditions are met |
| 181 | /// eg. for specified prediction structures or referencing in order to further optimize |
| 182 | /// the compression rate of the bitstream. |
| 183 | fn encode(&mut self, meta: FrameMetadata, handle: Handle) -> Result<(), EncodeError>; |
| 184 | |
| 185 | /// Drains the encoder. This means that encoder is required to finish processing of all the |
| 186 | /// frames in the internal queue and yield output bitstream by the end of the call. The output |
| 187 | /// bitstream then can be polled using [`Self::poll`] function. |
| 188 | /// |
| 189 | /// Drain does not enforce the flush of the internal state, ie. the enqueued frame handles |
| 190 | /// do not have to be returned to user (dropped) and key frame is not enforced on the next |
| 191 | /// frame. |
| 192 | fn drain(&mut self) -> EncodeResult<()>; |
| 193 | |
| 194 | /// Polls on the encoder for the available output bitstream with compressed frames that where |
| 195 | /// submitted with [`Self::encode`]. |
| 196 | /// |
| 197 | /// The call may also trigger a further processing aside of returning output. Therefore it |
| 198 | /// *recommended* that this function is called frequently. |
| 199 | fn poll(&mut self) -> EncodeResult<Option<CodedBitstreamBuffer>>; |
| 200 | } |
| 201 | |
| 202 | pub fn simple_encode_loop<H>( |
| 203 | encoder: &mut impl VideoEncoder<H>, |
| 204 | frame_producer: &mut impl Iterator<Item = (FrameMetadata, H)>, |
| 205 | mut coded_consumer: impl FnMut(CodedBitstreamBuffer), |
| 206 | ) -> EncodeResult<()> { |
| 207 | for (meta, handle) in frame_producer.by_ref() { |
| 208 | encoder.encode(meta, handle)?; |
| 209 | while let Some(coded) = encoder.poll()? { |
| 210 | coded_consumer(coded); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | encoder.drain()?; |
| 215 | while let Some(coded) = encoder.poll()? { |
| 216 | coded_consumer(coded); |
| 217 | } |
| 218 | |
| 219 | Ok(()) |
| 220 | } |
| 221 | |
| 222 | #[cfg(test)] |
| 223 | pub(crate) mod tests { |
| 224 | #[cfg(feature = "v4l2")] |
| 225 | use crate::encoder::FrameMetadata; |
| 226 | #[cfg(feature = "v4l2")] |
| 227 | use crate::utils::UserPtrFrame; |
| 228 | #[cfg(feature = "v4l2")] |
| 229 | use crate::Fourcc; |
| 230 | #[cfg(feature = "v4l2")] |
| 231 | use crate::FrameLayout; |
| 232 | |
| 233 | pub fn get_test_frame_t(ts: u64, max_ts: u64) -> f32 { |
| 234 | 2.0 * std::f32::consts::PI * (ts as f32) / (max_ts as f32) |
| 235 | } |
| 236 | |
| 237 | pub fn gen_test_frame<F>(frame_width: usize, frame_height: usize, t: f32, mut set_pix: F) |
| 238 | where |
| 239 | F: FnMut(usize, usize, [f32; 3]), |
| 240 | { |
| 241 | let width = frame_width as f32; |
| 242 | let height = frame_height as f32; |
| 243 | let (sin, cos) = f32::sin_cos(t); |
| 244 | let (sin2, cos2) = (sin.powi(2), cos.powi(2)); |
| 245 | |
| 246 | // Pick the dot position |
| 247 | let dot_col = height * (1.1 + 2.0 * sin * cos) / 2.2; |
| 248 | let dot_row = width * (1.1 + sin) / 2.2; |
| 249 | let dot_size2 = (width.min(height) * 0.05).powi(2); |
| 250 | |
| 251 | // Luma |
| 252 | for frame_row in 0..frame_height { |
| 253 | #[allow(clippy::needless_range_loop)] |
| 254 | for frame_col in 0..frame_width { |
| 255 | let row = frame_row as f32; |
| 256 | let col = frame_col as f32; |
| 257 | |
| 258 | let dist = (dot_col - col).powi(2) + (dot_row - row).powi(2); |
| 259 | |
| 260 | let y = if dist < dot_size2 { 0.0 } else { (row + col) / (width + height) }; |
| 261 | |
| 262 | let (u, v) = if dist < dot_size2 { |
| 263 | (0.5, 0.5) |
| 264 | } else { |
| 265 | ((row / width) * sin2, (col / height) * cos2) |
| 266 | }; |
| 267 | |
| 268 | set_pix(frame_col, frame_row, [y, u, v]); |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | pub fn fill_test_frame_nm12( |
| 274 | width: usize, |
| 275 | height: usize, |
| 276 | strides: [usize; 2], |
| 277 | t: f32, |
| 278 | y_plane: &mut [u8], |
| 279 | uv_plane: &mut [u8], |
| 280 | ) { |
| 281 | gen_test_frame(width, height, t, |col, row, yuv| { |
| 282 | /// Maximum value of color component for NV12 |
| 283 | const MAX_COMP_VAL: f32 = 0xff as f32; |
| 284 | |
| 285 | let (y, u, v) = ( |
| 286 | (yuv[0] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u8, |
| 287 | (yuv[1] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u8, |
| 288 | (yuv[2] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u8, |
| 289 | ); |
| 290 | let y_pos = row * strides[0] + col; |
| 291 | |
| 292 | y_plane[y_pos] = y; |
| 293 | |
| 294 | // Subsample with upper left pixel |
| 295 | if col % 2 == 0 && row % 2 == 0 { |
| 296 | let u_pos = (row / 2) * strides[1] + col; |
| 297 | let v_pos = u_pos + 1; |
| 298 | |
| 299 | uv_plane[u_pos] = u; |
| 300 | uv_plane[v_pos] = v; |
| 301 | } |
| 302 | }); |
| 303 | } |
| 304 | |
| 305 | pub fn fill_test_frame_nv12( |
| 306 | width: usize, |
| 307 | height: usize, |
| 308 | strides: [usize; 2], |
| 309 | offsets: [usize; 2], |
| 310 | t: f32, |
| 311 | raw: &mut [u8], |
| 312 | ) { |
| 313 | let (y_plane, uv_plane) = raw.split_at_mut(offsets[1]); |
| 314 | let y_plane = &mut y_plane[offsets[0]..]; |
| 315 | |
| 316 | fill_test_frame_nm12(width, height, strides, t, y_plane, uv_plane) |
| 317 | } |
| 318 | |
| 319 | pub fn fill_test_frame_p010( |
| 320 | width: usize, |
| 321 | height: usize, |
| 322 | strides: [usize; 2], |
| 323 | offsets: [usize; 2], |
| 324 | t: f32, |
| 325 | raw: &mut [u8], |
| 326 | ) { |
| 327 | gen_test_frame(width, height, t, |col, row, yuv| { |
| 328 | /// Maximum value of color component for P010 |
| 329 | const MAX_COMP_VAL: f32 = 0x3ff as f32; |
| 330 | |
| 331 | let (y, u, v) = ( |
| 332 | (yuv[0] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u16, |
| 333 | (yuv[1] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u16, |
| 334 | (yuv[2] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u16, |
| 335 | ); |
| 336 | let y_pos = offsets[0] + row * strides[0] + 2 * col; |
| 337 | |
| 338 | raw[y_pos] = ((y << 6) & 0xa0) as u8; |
| 339 | raw[y_pos + 1] = (y >> 2) as u8; |
| 340 | |
| 341 | // Subsample with upper left pixel |
| 342 | if col % 2 == 0 && row % 2 == 0 { |
| 343 | let u_pos = offsets[1] + (row / 2) * strides[1] + 2 * col; |
| 344 | let v_pos = u_pos + 2; |
| 345 | |
| 346 | raw[u_pos] = ((u << 6) & 0xa0) as u8; |
| 347 | raw[u_pos + 1] = (u >> 2) as u8; |
| 348 | raw[v_pos] = ((v << 6) & 0xa0) as u8; |
| 349 | raw[v_pos + 1] = (v >> 2) as u8; |
| 350 | } |
| 351 | }); |
| 352 | } |
| 353 | |
| 354 | #[cfg(feature = "v4l2")] |
| 355 | pub fn userptr_test_frame_generator( |
| 356 | frame_count: u64, |
| 357 | layout: FrameLayout, |
| 358 | buffer_size: usize, |
| 359 | ) -> impl Iterator<Item = (FrameMetadata, UserPtrFrame)> { |
| 360 | (0..frame_count).map(move |timestamp| { |
| 361 | let frame = UserPtrFrame::alloc(layout.clone(), buffer_size); |
| 362 | |
| 363 | let t = get_test_frame_t(timestamp, frame_count); |
| 364 | |
| 365 | if (frame.layout.format.0 == Fourcc::from(b"NM12") |
| 366 | || frame.layout.format.0 == Fourcc::from(b"NV12")) |
| 367 | && frame.layout.planes.len() == 2 |
| 368 | && frame.buffers.len() == 2 |
| 369 | { |
| 370 | // SAFETY: Slice matches the allocation |
| 371 | let y_plane = unsafe { |
| 372 | std::slice::from_raw_parts_mut( |
| 373 | frame.buffers[frame.layout.planes[0].buffer_index], |
| 374 | frame.mem_layout.size(), |
| 375 | ) |
| 376 | }; |
| 377 | // SAFETY: Slice matches the allocation |
| 378 | let uv_plane = unsafe { |
| 379 | std::slice::from_raw_parts_mut( |
| 380 | frame.buffers[frame.layout.planes[1].buffer_index], |
| 381 | frame.mem_layout.size(), |
| 382 | ) |
| 383 | }; |
| 384 | |
| 385 | fill_test_frame_nm12( |
| 386 | frame.layout.size.width as usize, |
| 387 | frame.layout.size.height as usize, |
| 388 | [frame.layout.planes[0].stride, frame.layout.planes[1].stride], |
| 389 | t, |
| 390 | y_plane, |
| 391 | uv_plane, |
| 392 | ); |
| 393 | } else if frame.layout.format.0 == Fourcc::from(b"NV12") |
| 394 | && frame.layout.planes.len() == 1 |
| 395 | && frame.buffers.len() == 1 |
| 396 | { |
| 397 | // SAFETY: Slice matches the allocation |
| 398 | let raw = unsafe { |
| 399 | std::slice::from_raw_parts_mut( |
| 400 | frame.buffers[frame.layout.planes[0].buffer_index] |
| 401 | .add(frame.layout.planes[0].offset), |
| 402 | frame.mem_layout.size(), |
| 403 | ) |
| 404 | }; |
| 405 | |
| 406 | let uv_stride = frame.layout.planes[0].stride; |
| 407 | let uv_offset = frame.layout.planes[0].stride * (frame.layout.size.height as usize); |
| 408 | |
| 409 | fill_test_frame_nv12( |
| 410 | frame.layout.size.width as usize, |
| 411 | frame.layout.size.height as usize, |
| 412 | [frame.layout.planes[0].stride, uv_stride], |
| 413 | [frame.layout.planes[0].offset, uv_offset], |
| 414 | t, |
| 415 | raw, |
| 416 | ); |
| 417 | } else { |
| 418 | panic!("Unrecognized frame layout used during test"); |
| 419 | } |
| 420 | |
| 421 | let meta = |
| 422 | FrameMetadata { timestamp, layout: frame.layout.clone(), force_keyframe: false }; |
| 423 | |
| 424 | (meta, frame) |
| 425 | }) |
| 426 | } |
| 427 | } |