| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | use crate::ctu::{CtuEncoder, RowBoundary, RowState, SourcePlanes}; |
| 27 | use ec_core::color::ContentLight; |
| 28 | use ec_core::error::{Error, Result}; |
| 29 | use ec_core::frame::{PixelFormat, Plane, VideoFrame}; |
| 30 | use ec_h265_syntax::nal::{NalHeader, NalUnitType, escape_rbsp, write_annex_b}; |
| 31 | use ec_h265_syntax::ps::{ConformanceWindow, ProfileTierLevel}; |
| 32 | use ec_h265_syntax::slice::SliceHeader; |
| 33 | use ec_h265_syntax::vui::{VideoSignalType, VuiParameters}; |
| 34 | use ec_h265_syntax::{Pps, Sps, Vps, sei}; |
| 35 | use std::sync::Mutex; |
| 36 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 37 | |
| 38 | use crate::cabac::{CabacEncoder, Contexts}; |
| 39 | |
| 40 | |
| 41 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 42 | pub enum RateControl { |
| 43 | |
| 44 | ConstantQp(i32), |
| 45 | |
| 46 | |
| 47 | TargetBits(u64), |
| 48 | } |
| 49 | |
| 50 | |
| 51 | #[derive(Debug, Clone)] |
| 52 | pub struct EncoderConfig { |
| 53 | |
| 54 | |
| 55 | pub width: u32, |
| 56 | |
| 57 | pub height: u32, |
| 58 | |
| 59 | pub rate_control: RateControl, |
| 60 | |
| 61 | pub threads: usize, |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | pub ctb_size: usize, |
| 76 | |
| 77 | |
| 78 | pub rdo_candidates: usize, |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | pub min_cu_size: usize, |
| 85 | |
| 86 | pub video_signal_type: Option<VideoSignalType>, |
| 87 | |
| 88 | pub sample_aspect_ratio: Option<(u16, u16)>, |
| 89 | |
| 90 | pub timing: Option<(u32, u32)>, |
| 91 | |
| 92 | pub content_light: ContentLight, |
| 93 | |
| 94 | pub picture_hash: bool, |
| 95 | |
| 96 | pub keep_recon: bool, |
| 97 | } |
| 98 | |
| 99 | impl EncoderConfig { |
| 100 | |
| 101 | |
| 102 | pub fn new(width: u32, height: u32) -> EncoderConfig { |
| 103 | EncoderConfig { |
| 104 | width, |
| 105 | height, |
| 106 | rate_control: RateControl::ConstantQp(27), |
| 107 | threads: 0, |
| 108 | ctb_size: 32, |
| 109 | rdo_candidates: 2, |
| 110 | min_cu_size: 8, |
| 111 | video_signal_type: None, |
| 112 | sample_aspect_ratio: None, |
| 113 | timing: None, |
| 114 | content_light: ContentLight::default(), |
| 115 | picture_hash: false, |
| 116 | keep_recon: false, |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | |
| 122 | #[derive(Debug, Clone)] |
| 123 | pub struct EncodedPicture { |
| 124 | |
| 125 | pub au: Vec<u8>, |
| 126 | |
| 127 | pub qp: i32, |
| 128 | |
| 129 | |
| 130 | |
| 131 | pub recon: Option<VideoFrame>, |
| 132 | } |
| 133 | |
| 134 | |
| 135 | pub struct Encoder { |
| 136 | cfg: EncoderConfig, |
| 137 | vps: Vps, |
| 138 | sps: Sps, |
| 139 | pps: Pps, |
| 140 | coded_width: usize, |
| 141 | coded_height: usize, |
| 142 | threads: usize, |
| 143 | } |
| 144 | |
| 145 | |
| 146 | |
| 147 | const BPP_AT_QP27: f64 = 0.6; |
| 148 | |
| 149 | impl Encoder { |
| 150 | |
| 151 | pub fn new(cfg: EncoderConfig) -> Result<Encoder> { |
| 152 | if cfg.width < 16 || cfg.height < 16 { |
| 153 | return Err(Error::unsupported( |
| 154 | format!("HEVC encode of {}x{}", cfg.width, cfg.height), |
| 155 | "pictures below 16x16 have no coding tree", |
| 156 | )); |
| 157 | } |
| 158 | if cfg.ctb_size != 64 && cfg.ctb_size != 32 { |
| 159 | return Err(Error::unsupported( |
| 160 | format!("HEVC coding tree block of {}", cfg.ctb_size), |
| 161 | "this encoder codes 64x64 or 32x32 trees", |
| 162 | )); |
| 163 | } |
| 164 | |
| 165 | |
| 166 | let coded_width = (cfg.width as usize).next_multiple_of(8); |
| 167 | let coded_height = (cfg.height as usize).next_multiple_of(8); |
| 168 | let fps = cfg |
| 169 | .timing |
| 170 | .map(|(units, scale)| f64::from(scale) / f64::from(units.max(1))) |
| 171 | .unwrap_or(30.0); |
| 172 | let ptl = ProfileTierLevel::main(ProfileTierLevel::level_for( |
| 173 | coded_width as u32, |
| 174 | coded_height as u32, |
| 175 | fps, |
| 176 | )); |
| 177 | let vps = Vps { |
| 178 | id: 0, |
| 179 | ptl, |
| 180 | max_dec_pic_buffering_minus1: 0, |
| 181 | max_num_reorder_pics: 0, |
| 182 | }; |
| 183 | let log2_ctb = cfg.ctb_size.trailing_zeros(); |
| 184 | let sps = Sps { |
| 185 | vps_id: 0, |
| 186 | id: 0, |
| 187 | chroma_format_idc: 1, |
| 188 | separate_colour_plane: false, |
| 189 | pic_width_in_luma_samples: coded_width as u32, |
| 190 | pic_height_in_luma_samples: coded_height as u32, |
| 191 | conf_win: ConformanceWindow { |
| 192 | left: 0, |
| 193 | right: (coded_width - cfg.width as usize) as u32 / 2, |
| 194 | top: 0, |
| 195 | bottom: (coded_height - cfg.height as usize) as u32 / 2, |
| 196 | }, |
| 197 | bit_depth_luma_minus8: 0, |
| 198 | bit_depth_chroma_minus8: 0, |
| 199 | log2_max_poc_lsb_minus4: 4, |
| 200 | max_dec_pic_buffering_minus1: 0, |
| 201 | max_num_reorder_pics: 0, |
| 202 | log2_min_cb_size_minus3: 0, |
| 203 | log2_diff_max_min_cb_size: log2_ctb - 3, |
| 204 | log2_min_tb_size_minus2: 0, |
| 205 | log2_diff_max_min_tb_size: 3, |
| 206 | max_transform_hierarchy_depth_inter: 0, |
| 207 | max_transform_hierarchy_depth_intra: 0, |
| 208 | scaling_list_enabled: false, |
| 209 | amp_enabled: false, |
| 210 | |
| 211 | sao_enabled: false, |
| 212 | pcm_enabled: false, |
| 213 | pcm: None, |
| 214 | num_short_term_ref_pic_sets: 0, |
| 215 | short_term_ref_pic_sets: Vec::new(), |
| 216 | long_term_ref_pics_present: false, |
| 217 | num_long_term_ref_pics_sps: 0, |
| 218 | long_term_ref_pics_sps: Vec::new(), |
| 219 | temporal_mvp_enabled: false, |
| 220 | strong_intra_smoothing: true, |
| 221 | ptl, |
| 222 | vui: Some(VuiParameters { |
| 223 | sample_aspect_ratio: cfg.sample_aspect_ratio, |
| 224 | video_signal_type: cfg.video_signal_type, |
| 225 | timing: cfg.timing, |
| 226 | }), |
| 227 | }; |
| 228 | let pps = Pps { |
| 229 | id: 0, |
| 230 | sps_id: 0, |
| 231 | entropy_coding_sync_enabled: true, |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | deblocking_filter_control_present: true, |
| 240 | deblocking_filter_disabled: true, |
| 241 | loop_filter_across_slices_enabled: false, |
| 242 | ..Pps::default() |
| 243 | }; |
| 244 | let threads = if cfg.threads == 0 { |
| 245 | std::thread::available_parallelism().map_or(1, |n| n.get()) |
| 246 | } else { |
| 247 | cfg.threads |
| 248 | }; |
| 249 | Ok(Encoder { |
| 250 | cfg, |
| 251 | vps, |
| 252 | sps, |
| 253 | pps, |
| 254 | coded_width, |
| 255 | coded_height, |
| 256 | threads, |
| 257 | }) |
| 258 | } |
| 259 | |
| 260 | |
| 261 | pub fn sps(&self) -> &Sps { |
| 262 | &self.sps |
| 263 | } |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | pub fn encode_idr(&self, frame: &VideoFrame) -> Result<EncodedPicture> { |
| 270 | if frame.format != PixelFormat::I420 { |
| 271 | return Err(Error::unsupported( |
| 272 | format!("HEVC encode of {:?}", frame.format), |
| 273 | "this encoder codes 8-bit 4:2:0 planar", |
| 274 | )); |
| 275 | } |
| 276 | if frame.width != self.cfg.width || frame.height != self.cfg.height { |
| 277 | return Err(Error::corrupt(format!( |
| 278 | "HEVC encode: frame is {}x{}, encoder configured for {}x{}", |
| 279 | frame.width, frame.height, self.cfg.width, self.cfg.height |
| 280 | ))); |
| 281 | } |
| 282 | let planes: Vec<(&[u8], usize)> = frame |
| 283 | .planes |
| 284 | .iter() |
| 285 | .map(|p: &Plane| (&p.data[..], p.stride)) |
| 286 | .collect(); |
| 287 | self.encode_idr_planes( |
| 288 | planes[0].0, |
| 289 | planes[0].1, |
| 290 | planes[1].0, |
| 291 | planes[1].1, |
| 292 | planes[2].0, |
| 293 | planes[2].1, |
| 294 | ) |
| 295 | } |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | pub fn encode_idr_planes( |
| 302 | &self, |
| 303 | y: &[u8], |
| 304 | y_stride: usize, |
| 305 | cb: &[u8], |
| 306 | cb_stride: usize, |
| 307 | cr: &[u8], |
| 308 | cr_stride: usize, |
| 309 | ) -> Result<EncodedPicture> { |
| 310 | let padded = self.pad_source(y, y_stride, cb, cb_stride, cr, cr_stride)?; |
| 311 | let (mut qp, target) = match self.cfg.rate_control { |
| 312 | RateControl::ConstantQp(qp) => (qp.clamp(0, 51), None), |
| 313 | RateControl::TargetBits(bits) => { |
| 314 | let pixels = (self.cfg.width as f64) * (self.cfg.height as f64); |
| 315 | let target_bpp = (bits as f64 / pixels).max(1e-4); |
| 316 | let qp = 27.0 + 6.0 * (BPP_AT_QP27 / target_bpp).log2(); |
| 317 | ((qp.round() as i32).clamp(0, 51), Some(bits)) |
| 318 | } |
| 319 | }; |
| 320 | let mut coded = self.code_picture(&padded, qp)?; |
| 321 | if let Some(target) = target { |
| 322 | let actual = coded.au.len() as f64 * 8.0; |
| 323 | let target = target as f64; |
| 324 | if (actual - target).abs() / target > 0.25 { |
| 325 | |
| 326 | |
| 327 | let correction = 6.0 * (actual / target).log2(); |
| 328 | let corrected = (qp as f64 + correction.clamp(-12.0, 12.0)).round() as i32; |
| 329 | let corrected = corrected.clamp(0, 51); |
| 330 | if corrected != qp { |
| 331 | qp = corrected; |
| 332 | coded = self.code_picture(&padded, qp)?; |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | Ok(coded) |
| 337 | } |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | pub fn encode_batch<'a, I>(&self, frames: I) -> Result<Vec<EncodedPicture>> |
| 344 | where |
| 345 | I: IntoIterator<Item = &'a VideoFrame>, |
| 346 | { |
| 347 | frames.into_iter().map(|f| self.encode_idr(f)).collect() |
| 348 | } |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | fn pad_source( |
| 355 | &self, |
| 356 | y: &[u8], |
| 357 | y_stride: usize, |
| 358 | cb: &[u8], |
| 359 | cb_stride: usize, |
| 360 | cr: &[u8], |
| 361 | cr_stride: usize, |
| 362 | ) -> Result<PaddedSource> { |
| 363 | let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); |
| 364 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 365 | let (coded_w, coded_h) = (self.coded_width, self.coded_height); |
| 366 | let plane = |src: &[u8], |
| 367 | stride: usize, |
| 368 | width: usize, |
| 369 | height: usize, |
| 370 | out_w: usize, |
| 371 | out_h: usize| |
| 372 | -> Result<Vec<u8>> { |
| 373 | if stride < width || src.len() < (height - 1) * stride + width { |
| 374 | return Err(Error::corrupt( |
| 375 | "HEVC encode: source plane shorter than its stated size".to_string(), |
| 376 | )); |
| 377 | } |
| 378 | let mut out = vec![0u8; out_w * out_h]; |
| 379 | for row in 0..out_h { |
| 380 | let src_row = row.min(height - 1); |
| 381 | let line = &src[src_row * stride..src_row * stride + width]; |
| 382 | let dst = &mut out[row * out_w..row * out_w + out_w]; |
| 383 | dst[..width].copy_from_slice(line); |
| 384 | let edge = line[width - 1]; |
| 385 | dst[width..].fill(edge); |
| 386 | } |
| 387 | Ok(out) |
| 388 | }; |
| 389 | Ok(PaddedSource { |
| 390 | y: plane(y, y_stride, w, h, coded_w, coded_h)?, |
| 391 | cb: plane(cb, cb_stride, cw, ch, coded_w / 2, coded_h / 2)?, |
| 392 | cr: plane(cr, cr_stride, cw, ch, coded_w / 2, coded_h / 2)?, |
| 393 | }) |
| 394 | } |
| 395 | |
| 396 | |
| 397 | fn code_picture(&self, src: &PaddedSource, qp: i32) -> Result<EncodedPicture> { |
| 398 | let (width, height) = (self.coded_width, self.coded_height); |
| 399 | let ctb = self.cfg.ctb_size; |
| 400 | let cols = width.div_ceil(ctb); |
| 401 | let rows = height.div_ceil(ctb); |
| 402 | |
| 403 | let mut rec_y = vec![0u8; width * height]; |
| 404 | let mut rec_cb = vec![0u8; width / 2 * height / 2]; |
| 405 | let mut rec_cr = vec![0u8; width / 2 * height / 2]; |
| 406 | |
| 407 | let boundaries: Vec<RowBoundary> = (0..rows).map(|_| RowBoundary::new(width)).collect(); |
| 408 | let progress: Vec<Progress> = (0..rows).map(|_| Progress(AtomicUsize::new(0))).collect(); |
| 409 | let wpp_contexts: Vec<Mutex<Option<Contexts>>> = |
| 410 | (0..rows).map(|_| Mutex::new(None)).collect(); |
| 411 | let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect(); |
| 412 | |
| 413 | |
| 414 | let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect(); |
| 415 | let mut bands_cb: Vec<&mut [u8]> = rec_cb.chunks_mut(ctb / 2 * (width / 2)).collect(); |
| 416 | let mut bands_cr: Vec<&mut [u8]> = rec_cr.chunks_mut(ctb / 2 * (width / 2)).collect(); |
| 417 | let threads = self.threads.min(rows).max(1); |
| 418 | |
| 419 | |
| 420 | |
| 421 | let mut per_worker: Vec<Vec<RowAssignment<'_>>> = |
| 422 | (0..threads).map(|_| Vec::new()).collect(); |
| 423 | for row in (0..rows).rev() { |
| 424 | let y = bands_y.pop().expect("one band per row"); |
| 425 | let cb = bands_cb.pop().expect("one band per row"); |
| 426 | let cr = bands_cr.pop().expect("one band per row"); |
| 427 | per_worker[row % threads].push((row, y, cb, cr)); |
| 428 | } |
| 429 | for worker in per_worker.iter_mut() { |
| 430 | worker.reverse(); |
| 431 | } |
| 432 | |
| 433 | let slice_qp = qp; |
| 434 | std::thread::scope(|scope| { |
| 435 | for worker_rows in per_worker { |
| 436 | let boundaries = &boundaries; |
| 437 | let progress = &progress; |
| 438 | let wpp_contexts = &wpp_contexts; |
| 439 | let substreams = &substreams; |
| 440 | let src = &src; |
| 441 | scope.spawn(move || { |
| 442 | for (row, band_y, band_cb, band_cr) in worker_rows { |
| 443 | let band_y0 = row * ctb; |
| 444 | |
| 445 | |
| 446 | if row > 0 { |
| 447 | wait_for(&progress[row - 1], 2.min(cols)); |
| 448 | } |
| 449 | let contexts = if row == 0 || cols < 2 { |
| 450 | Contexts::new(slice_qp) |
| 451 | } else { |
| 452 | wpp_contexts[row - 1] |
| 453 | .lock() |
| 454 | .ok() |
| 455 | .and_then(|c| c.clone()) |
| 456 | .unwrap_or_else(|| Contexts::new(slice_qp)) |
| 457 | }; |
| 458 | let mut enc = CabacEncoder::new(contexts); |
| 459 | let mut coder = CtuEncoder::new( |
| 460 | SourcePlanes { |
| 461 | y: &src.y, |
| 462 | cb: &src.cb, |
| 463 | cr: &src.cr, |
| 464 | }, |
| 465 | RowState { |
| 466 | rec_y: band_y, |
| 467 | rec_cb: band_cb, |
| 468 | rec_cr: band_cr, |
| 469 | publish: &boundaries[row], |
| 470 | above: if row == 0 { |
| 471 | None |
| 472 | } else { |
| 473 | Some(&boundaries[row - 1]) |
| 474 | }, |
| 475 | }, |
| 476 | width, |
| 477 | height, |
| 478 | ctb, |
| 479 | band_y0, |
| 480 | slice_qp, |
| 481 | true, |
| 482 | self.cfg.rdo_candidates, |
| 483 | self.cfg.min_cu_size.max(8).trailing_zeros(), |
| 484 | ); |
| 485 | for col in 0..cols { |
| 486 | if row > 0 { |
| 487 | wait_for(&progress[row - 1], (col + 2).min(cols)); |
| 488 | } |
| 489 | coder.encode_ctu(col, &mut enc); |
| 490 | if col == 1 { |
| 491 | |
| 492 | |
| 493 | if let Ok(mut slot) = wpp_contexts[row].lock() { |
| 494 | *slot = Some(enc.contexts.clone()); |
| 495 | } |
| 496 | } |
| 497 | progress[row].0.store(col + 1, Ordering::Release); |
| 498 | let last_in_picture = row + 1 == rows && col + 1 == cols; |
| 499 | enc.encode_terminate(u32::from(last_in_picture)); |
| 500 | if !last_in_picture && col + 1 == cols { |
| 501 | |
| 502 | enc.encode_terminate(1); |
| 503 | } |
| 504 | } |
| 505 | if let Ok(mut slot) = substreams[row].lock() { |
| 506 | *slot = enc.finish(); |
| 507 | } |
| 508 | } |
| 509 | }); |
| 510 | } |
| 511 | }); |
| 512 | |
| 513 | let substreams: Vec<Vec<u8>> = substreams |
| 514 | .into_iter() |
| 515 | .map(|m| m.into_inner().unwrap_or_default()) |
| 516 | .collect(); |
| 517 | let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr); |
| 518 | let recon = self |
| 519 | .cfg |
| 520 | .keep_recon |
| 521 | .then(|| self.crop_recon(&rec_y, &rec_cb, &rec_cr)); |
| 522 | Ok(EncodedPicture { au, qp, recon }) |
| 523 | } |
| 524 | |
| 525 | |
| 526 | fn assemble_au( |
| 527 | &self, |
| 528 | qp: i32, |
| 529 | substreams: &[Vec<u8>], |
| 530 | rec_y: &[u8], |
| 531 | rec_cb: &[u8], |
| 532 | rec_cr: &[u8], |
| 533 | ) -> Vec<u8> { |
| 534 | let mut au = Vec::with_capacity(substreams.iter().map(|s| s.len()).sum::<usize>() + 256); |
| 535 | write_annex_b( |
| 536 | &mut au, |
| 537 | NalHeader::new(NalUnitType::Vps), |
| 538 | &self.vps.to_rbsp(), |
| 539 | true, |
| 540 | ); |
| 541 | write_annex_b( |
| 542 | &mut au, |
| 543 | NalHeader::new(NalUnitType::Sps), |
| 544 | &self.sps.to_rbsp(), |
| 545 | true, |
| 546 | ); |
| 547 | write_annex_b( |
| 548 | &mut au, |
| 549 | NalHeader::new(NalUnitType::Pps), |
| 550 | &self.pps.to_rbsp(), |
| 551 | true, |
| 552 | ); |
| 553 | if let Some(rbsp) = sei::hdr_metadata_rbsp(self.cfg.content_light) { |
| 554 | write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true); |
| 555 | } |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | |
| 561 | let mut escaped: Vec<Vec<u8>> = Vec::with_capacity(substreams.len()); |
| 562 | for stream in substreams { |
| 563 | let mut out = Vec::with_capacity(stream.len() + 8); |
| 564 | escape_rbsp(stream, &mut out); |
| 565 | escaped.push(out); |
| 566 | } |
| 567 | let mut header = SliceHeader::intra(&self.pps, qp - 26); |
| 568 | header.entry_point_offsets = escaped |
| 569 | .iter() |
| 570 | .take(escaped.len().saturating_sub(1)) |
| 571 | .map(|s| s.len() as u32) |
| 572 | .collect(); |
| 573 | let mut writer = ec_core::bitio::BitWriter::with_capacity(64); |
| 574 | header.write(&mut writer, &self.sps, &self.pps, NalUnitType::IdrWRadl); |
| 575 | let mut rbsp = writer.into_bytes(); |
| 576 | for stream in substreams { |
| 577 | rbsp.extend_from_slice(stream); |
| 578 | } |
| 579 | write_annex_b(&mut au, NalHeader::new(NalUnitType::IdrWRadl), &rbsp, true); |
| 580 | |
| 581 | if self.cfg.picture_hash { |
| 582 | let (w, h) = (self.coded_width, self.coded_height); |
| 583 | let rbsp = sei::decoded_picture_hash_rbsp(&[ |
| 584 | (rec_y, w, w, h), |
| 585 | (rec_cb, w / 2, w / 2, h / 2), |
| 586 | (rec_cr, w / 2, w / 2, h / 2), |
| 587 | ]); |
| 588 | write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false); |
| 589 | } |
| 590 | au |
| 591 | } |
| 592 | |
| 593 | fn crop_recon(&self, rec_y: &[u8], rec_cb: &[u8], rec_cr: &[u8]) -> VideoFrame { |
| 594 | let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); |
| 595 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 596 | let crop = |src: &[u8], stride: usize, width: usize, height: usize| -> Vec<u8> { |
| 597 | let mut out = Vec::with_capacity(width * height); |
| 598 | for row in 0..height { |
| 599 | out.extend_from_slice(&src[row * stride..row * stride + width]); |
| 600 | } |
| 601 | out |
| 602 | }; |
| 603 | let planes = vec![ |
| 604 | Plane::new(crop(rec_y, self.coded_width, w, h), w), |
| 605 | Plane::new(crop(rec_cb, self.coded_width / 2, cw, ch), cw), |
| 606 | Plane::new(crop(rec_cr, self.coded_width / 2, cw, ch), cw), |
| 607 | ]; |
| 608 | VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes) |
| 609 | .expect("cropped planes are exactly the size I420 asks for") |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | |
| 614 | |
| 615 | |
| 616 | |
| 617 | |
| 618 | #[repr(align(64))] |
| 619 | struct Progress(AtomicUsize); |
| 620 | |
| 621 | |
| 622 | |
| 623 | |
| 624 | |
| 625 | |
| 626 | fn wait_for(counter: &Progress, target: usize) { |
| 627 | let mut spins = 0u32; |
| 628 | while counter.0.load(Ordering::Acquire) < target { |
| 629 | if spins < 128 { |
| 630 | std::hint::spin_loop(); |
| 631 | } else if spins < 256 { |
| 632 | std::thread::yield_now(); |
| 633 | } else { |
| 634 | std::thread::sleep(std::time::Duration::from_micros(50)); |
| 635 | } |
| 636 | spins += 1; |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | |
| 641 | type RowAssignment<'a> = (usize, &'a mut [u8], &'a mut [u8], &'a mut [u8]); |
| 642 | |
| 643 | struct PaddedSource { |
| 644 | y: Vec<u8>, |
| 645 | cb: Vec<u8>, |
| 646 | cr: Vec<u8>, |
| 647 | } |