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