edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·231663e·Tahinli·3 months ago·1475 commits
| 1 | //! The encoder API and the wavefront that makes one call use every core. |
| 2 | //! |
| 3 | //! # Parallelism |
| 4 | //! |
| 5 | //! `entropy_coding_sync_enabled_flag` (WPP) is on. Each CTB row is a substream |
| 6 | //! with its own entry point; a worker may start row `r` once row `r - 1` is two |
| 7 | //! CTBs ahead, which is exactly the dependency intra prediction has (a block |
| 8 | //! reaches at most one CTB to the right on the line above) and exactly what the |
| 9 | //! CABAC context sync in 9.3.2.1 assumes. Rows are handed to `threads` workers |
| 10 | //! round-robin, and every worker owns: |
| 11 | //! |
| 12 | //! - its own band of the reconstruction (`chunks_mut`, no sharing), |
| 13 | //! - its own substream buffer and CABAC engine, |
| 14 | //! - a published bottom line ([`RowBoundary`]) the row below reads through |
| 15 | //! atomics, plus a progress counter. |
| 16 | //! |
| 17 | //! No `unsafe`, no scoped raw pointers, no rayon: the only shared mutable state |
| 18 | //! is one atomic byte per boundary sample and one atomic counter per row. |
| 19 | //! |
| 20 | //! # What comes out |
| 21 | //! |
| 22 | //! One Annex-B access unit per picture, carrying VPS, SPS and PPS every time — |
| 23 | //! every picture is an IDR, so every picture is a seek point, and a seek point |
| 24 | //! whose parameter sets are elsewhere is not one. |
| 25 | |
| 26 | use crate::ctu::{CtuEncoder, RowBoundary, RowState, SourcePlanes}; |
| 27 | use crate::deblock::{TuMap, deblock}; |
| 28 | use ec_core::color::ContentLight; |
| 29 | use ec_core::error::{Error, Result}; |
| 30 | use ec_core::frame::{PixelFormat, Plane, VideoFrame}; |
| 31 | use ec_h265_syntax::nal::{NalHeader, NalUnitType, escape_rbsp, write_annex_b}; |
| 32 | use ec_h265_syntax::ps::{ConformanceWindow, ProfileTierLevel}; |
| 33 | use ec_h265_syntax::slice::SliceHeader; |
| 34 | use ec_h265_syntax::vui::{VideoSignalType, VuiParameters}; |
| 35 | use ec_h265_syntax::{Pps, Sps, Vps, sei}; |
| 36 | use std::sync::Mutex; |
| 37 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 38 | |
| 39 | use crate::cabac::{CabacEncoder, Contexts}; |
| 40 | |
| 41 | /// How the encoder picks QP for a picture. |
| 42 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 43 | pub enum RateControl { |
| 44 | /// One fixed quantiser for every picture. |
| 45 | ConstantQp(i32), |
| 46 | /// Aim for `bits` per picture: a model picks the QP, and a picture that |
| 47 | /// lands more than 25% off is coded a second time at a corrected QP. |
| 48 | TargetBits(u64), |
| 49 | } |
| 50 | |
| 51 | /// Whether 4x4 transform units may skip the transform and code residual |
| 52 | /// samples directly (`transform_skip_enabled_flag`). |
| 53 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 54 | pub enum TransformSkip { |
| 55 | /// No transform skip; every default stream is byte-identical. |
| 56 | Off, |
| 57 | /// Skip the transform on every 4x4 TU that has non-zero residual. |
| 58 | AlwaysFor4x4, |
| 59 | } |
| 60 | |
| 61 | /// Encoder settings. |
| 62 | #[derive(Debug, Clone)] |
| 63 | pub struct EncoderConfig { |
| 64 | /// Displayed width; the coded picture is padded up to a whole number of |
| 65 | /// minimum coding blocks and cropped back by the conformance window. |
| 66 | pub width: u32, |
| 67 | /// Displayed height. |
| 68 | pub height: u32, |
| 69 | /// Quantiser or bit target. |
| 70 | pub rate_control: RateControl, |
| 71 | /// Worker threads; 0 means "as many as the machine has". |
| 72 | pub threads: usize, |
| 73 | /// Coding tree block size, 32 (default) or 64. |
| 74 | /// |
| 75 | /// The wavefront hands one CTB *row* to a worker, so the row count is the |
| 76 | /// parallelism this encoder has: 1080 lines are 17 rows at 64 but 34 at 32. |
| 77 | /// Rows are dealt round-robin, so on a twelve-core machine 17 rows means |
| 78 | /// five workers take two rows while seven take one — half the machine idles |
| 79 | /// through the second half of the picture. 34 rows deal three-and-three. |
| 80 | /// Measured on 1080p at QP 27: the two sizes encode at the same speed on one |
| 81 | /// thread (1.80 fps each), but on twelve 32 runs 9.03 fps against 64's 7.92, |
| 82 | /// for 1.0% more bits and 0.02 dB less PSNR — the whole difference is |
| 83 | /// wavefront occupancy, which is why 32 is the default. 64 takes its bits |
| 84 | /// back when the picture is tall enough to fill the workers anyway (2160 |
| 85 | /// lines are 34 rows at 64) or when nothing is waiting for the encode. |
| 86 | pub ctb_size: usize, |
| 87 | /// How many of the 35 intra modes get a full rate-distortion trial, on top |
| 88 | /// of the most probable mode, which always gets one. |
| 89 | /// |
| 90 | /// Swept against x265 at matched features on four real clips (BD-PSNR |
| 91 | /// luma / all-plane, wall time for the whole four-QP ladder): |
| 92 | /// |
| 93 | /// | k | film 3840x1608 | web 1138x640 | screen 2560x1440 | phone 1080p | |
| 94 | /// |---|----------------|-------------------|------------------|-------------| |
| 95 | /// | 1 | -0.840 / -0.815 38s | -0.728 / -0.733 8s | | | |
| 96 | /// | 2 | -0.731 / -0.730 40s | -0.603 / -0.632 9s | -2.521 / -2.420 29s | -0.435 / -0.444 11s | |
| 97 | /// | 3 | -0.703 / -0.709 43s | -0.556 / -0.596 10s | -2.493 / -2.402 31s | -0.401 / -0.416 11s | |
| 98 | /// | 4 | -0.693 / -0.705 46s | -0.530 / -0.574 10s | | | |
| 99 | /// | 5 | -0.685 / -0.703 49s | -0.507 / -0.556 11s | -2.465 / -2.360 35s | -0.366 / -0.387 13s | |
| 100 | /// | 8 | -0.684 / -0.710 59s | -0.471 / -0.525 14s | -2.453 / -2.368 41s | -0.340 / -0.361 16s | |
| 101 | /// |
| 102 | /// Every clip improves monotonically up to 5, which is why 5 is the |
| 103 | /// default. Eight buys nothing on the film clip (+0.001 luma, and its |
| 104 | /// all-plane figure goes *backwards*) for another 20% of wall time, so the |
| 105 | /// knee is where the default sits. `EC_H265_RDO_CANDIDATES` in the gate |
| 106 | /// test re-runs the sweep. |
| 107 | pub rdo_candidates: usize, |
| 108 | /// Whether the chroma prediction mode is chosen by rate-distortion over the |
| 109 | /// five modes the syntax allows, instead of always taking the derived mode. |
| 110 | /// |
| 111 | /// Off by default: measured against x265 on four real clips it is a wash, |
| 112 | /// and on screen capture it is a loss (BD-PSNR luma / all-plane, derived |
| 113 | /// mode -> search, `chroma_rd_weight: 1.0`): |
| 114 | /// |
| 115 | /// | clip | derived | search | |
| 116 | /// |------|---------|--------| |
| 117 | /// | 4K film | -0.685 / -0.703 | -0.757 / **-0.606** | |
| 118 | /// | 1138x640 web | -0.507 / -0.556 | -0.584 / **-0.505** | |
| 119 | /// | 1440p screen capture | **-2.465 / -2.360** | -2.617 / -2.460 | |
| 120 | /// | 1080p phone | -0.366 / **-0.387** | -0.477 / -0.384 | |
| 121 | /// |
| 122 | /// Luma falls on every clip because the extra chroma bits come out of the |
| 123 | /// same budget at a fixed QP; all-plane gains 0.10 dB and 0.05 dB on the two |
| 124 | /// camera clips, is flat on the third and loses 0.10 dB on the screen |
| 125 | /// capture, for 10-15% more encode time. The average is +0.01 dB all-plane, |
| 126 | /// which is not a default. [`EncoderConfig::chroma_rd_weight`] was swept at |
| 127 | /// 0.25/0.5/1.0/2.0 and did not change the shape of that table: the screen |
| 128 | /// capture loses at every weight, so the cause is not the lambda. |
| 129 | pub chroma_mode_search: bool, |
| 130 | /// Weight on chroma SSD in that decision, against the luma lambda. Swept |
| 131 | /// at 0.25/0.5/1.0/2.0 on three clips; 1.0 is the best of them everywhere |
| 132 | /// the search wins at all (4K film all-plane: -0.606 at 1.0 against -0.649 |
| 133 | /// at 0.25, -0.619 at 0.5, -0.657 at 2.0). |
| 134 | pub chroma_rd_weight: f64, |
| 135 | /// Smallest coding unit the search will produce, 8 or 16. Sixteen is a |
| 136 | /// *coarser* search that is not always faster: on real pictures the 8x8 |
| 137 | /// blocks pay for their search in residual bits (measured: -27% bits and |
| 138 | /// +1.5 dB at QP 22 on a 1080p camera frame, at the same wall time), which |
| 139 | /// is why 8 is the default. |
| 140 | pub min_cu_size: usize, |
| 141 | /// Whether an 8x8 coding unit may split into four 4x4 intra partitions |
| 142 | /// (PART_NxN). On: measured at +2.14 dB BD-PSNR on a 2560x1440 screen |
| 143 | /// capture (-2.619 dB against x265 without it, -0.479 dB with) and |
| 144 | /// +0.007 dB on 1080p film, so it never loses. |
| 145 | pub intra_nxn: bool, |
| 146 | |
| 147 | /// Whether a sub-block's first sign is hidden in the parity of its |
| 148 | /// absolute levels (`sign_data_hiding_enabled_flag`). Buys one bypass bin |
| 149 | /// per qualifying sub-block for a level nudged by one. |
| 150 | /// |
| 151 | /// Off: measured at -0.033 dB BD-PSNR on a 2560x1440 screen capture and |
| 152 | /// -0.043 dB on 1080p film. Hiding is not optional per sub-block, so every |
| 153 | /// qualifying one pays for the bin whether the nudge is cheap or not, and |
| 154 | /// with levels that come straight from the quantiser's rounding the nudges |
| 155 | /// cost more than the signs save. Worth re-measuring once RDOQ lands: that |
| 156 | /// is where the gain in other encoders comes from. |
| 157 | pub sign_hiding: bool, |
| 158 | |
| 159 | /// Whether quantised levels get a rate-distortion search (RDOQ) that |
| 160 | /// offers each small level the magnitudes below it and takes one when the |
| 161 | /// squared error it gives up costs less than the bits it saves. |
| 162 | /// |
| 163 | /// On: worth +0.122 dB BD-PSNR on a 2560x1440 screen capture (-0.479 -> |
| 164 | /// -0.357 against x265) and +0.114 dB on 1080p film (+0.246 -> +0.360), |
| 165 | /// with the all-plane figures moving the same way. The rate is the CABAC |
| 166 | /// coder's own price for the whole block, so dropping a level is priced |
| 167 | /// with the significance map and last position that follow from it. |
| 168 | pub rdoq: bool, |
| 169 | /// Whether RDOQ's per-candidate bit cost comes from an estimated |
| 170 | /// per-context fractional-bit table (x265/HM `entropyBits`-style: the |
| 171 | /// entropy of the bin under its context's current probability state) |
| 172 | /// instead of replaying the exact adaptive-CABAC coder for every trial. |
| 173 | /// Changes output bytes (the estimate is not exact). On by default: |
| 174 | /// measured 1.6x faster on `ec-bench`'s h265 encode row and, on the |
| 175 | /// synthetic `bd_psnr_vs_x265` clip, a small BD-PSNR-YUV *gain* over the |
| 176 | /// exact-replay path (+7.948 vs +7.880 dB against x265) rather than a |
| 177 | /// loss. `false` restores exact per-trial CABAC replay for A/B. |
| 178 | pub rdoq_estimate: bool, |
| 179 | /// Whether 4x4 TUs may skip the integer transform. |
| 180 | pub transform_skip: TransformSkip, |
| 181 | /// Whether the transform tree may split once (rate-quantisation transform): |
| 182 | /// the luma TU of a 2Nx2N coding unit may be coded as four half-size |
| 183 | /// children when that costs less in `J = SSD + lambda * bits`. |
| 184 | /// |
| 185 | /// On by default: measured against x265 over the four-point ladder it is |
| 186 | /// worth +0.010 dB BD-PSNR on film and +0.080 dB on screen capture, which |
| 187 | /// is where our gap against x265 is (see `lanes/h265-rqt-r1.report.md`). |
| 188 | pub rqt: bool, |
| 189 | /// Whether a 64x64 coding tree block may stay one coding unit instead of |
| 190 | /// always splitting to 32x32. Only reachable with `ctb_size` 64. |
| 191 | /// |
| 192 | /// A 64x64 intra coding unit still predicts and transforms in four 32x32 |
| 193 | /// blocks -- 32x32 is HEVC's largest transform -- so what it buys is three |
| 194 | /// split flags and three mode signallings, and what it costs is one luma |
| 195 | /// direction for the whole 64x64. Measured in `lanes/h265-cu64-r1.report.md`. |
| 196 | /// |
| 197 | /// On by default: against x265 over the four-point ladder it is worth |
| 198 | /// +0.007 dB BD-PSNR on film and +0.098 dB on screen capture over always |
| 199 | /// splitting a 64x64 tree block, and the default `ctb_size` of 32 leaves |
| 200 | /// it unreachable anyway. |
| 201 | pub cu64: bool, |
| 202 | /// What the samples mean, written into the VUI. |
| 203 | pub video_signal_type: Option<VideoSignalType>, |
| 204 | /// Sample aspect ratio. |
| 205 | pub sample_aspect_ratio: Option<(u16, u16)>, |
| 206 | /// `(num_units_in_tick, time_scale)`; also picks the level. |
| 207 | pub timing: Option<(u32, u32)>, |
| 208 | /// HDR mastering metadata, written as prefix SEI. |
| 209 | pub content_light: ContentLight, |
| 210 | /// Run the in-loop deblocking filter over the finished picture. |
| 211 | /// |
| 212 | /// An intra picture predicts from its unfiltered reconstruction, so this |
| 213 | /// changes only what a decoder shows -- and what the reconstruction and its |
| 214 | /// picture hash therefore have to say. |
| 215 | pub deblock: bool, |
| 216 | /// Emit the decoded picture hash SEI (MD5 of the reconstruction). |
| 217 | pub picture_hash: bool, |
| 218 | /// Return the reconstruction alongside the bitstream. |
| 219 | pub keep_recon: bool, |
| 220 | } |
| 221 | |
| 222 | impl EncoderConfig { |
| 223 | /// Defaults for `width x height`: constant QP 27, every core, 32x32 CTBs |
| 224 | /// (see [`EncoderConfig::ctb_size`] for why 32 and not 64). |
| 225 | pub fn new(width: u32, height: u32) -> EncoderConfig { |
| 226 | EncoderConfig { |
| 227 | width, |
| 228 | height, |
| 229 | rate_control: RateControl::ConstantQp(27), |
| 230 | threads: 0, |
| 231 | ctb_size: 32, |
| 232 | rdo_candidates: 5, |
| 233 | chroma_mode_search: false, |
| 234 | chroma_rd_weight: 1.0, |
| 235 | min_cu_size: 8, |
| 236 | intra_nxn: true, |
| 237 | sign_hiding: false, |
| 238 | rdoq: true, |
| 239 | rdoq_estimate: true, |
| 240 | transform_skip: TransformSkip::Off, |
| 241 | rqt: true, |
| 242 | cu64: true, |
| 243 | video_signal_type: None, |
| 244 | sample_aspect_ratio: None, |
| 245 | timing: None, |
| 246 | content_light: ContentLight::default(), |
| 247 | deblock: true, |
| 248 | picture_hash: false, |
| 249 | keep_recon: false, |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | /// One coded picture. |
| 255 | #[derive(Debug, Clone)] |
| 256 | pub struct EncodedPicture { |
| 257 | /// The access unit, Annex-B framed: VPS, SPS, PPS, optional SEI, IDR slice. |
| 258 | pub au: Vec<u8>, |
| 259 | /// The quantiser the picture was coded at. |
| 260 | pub qp: i32, |
| 261 | /// The reconstruction, cropped to the displayed size, when |
| 262 | /// [`EncoderConfig::keep_recon`] asked for it. Bit-identical to what a |
| 263 | /// conformant decoder produces, because the in-loop filters are off. |
| 264 | pub recon: Option<VideoFrame>, |
| 265 | } |
| 266 | |
| 267 | /// An intra-only HEVC encoder. |
| 268 | pub struct Encoder { |
| 269 | cfg: EncoderConfig, |
| 270 | vps: Vps, |
| 271 | sps: Sps, |
| 272 | pps: Pps, |
| 273 | coded_width: usize, |
| 274 | coded_height: usize, |
| 275 | threads: usize, |
| 276 | } |
| 277 | |
| 278 | /// Bits per pixel this encoder spends at QP 27, the anchor the bit-target model |
| 279 | /// walks from (measured on 1080p fixtures; the incumbent's own figure was 0.6). |
| 280 | const BPP_AT_QP27: f64 = 0.6; |
| 281 | |
| 282 | impl Encoder { |
| 283 | /// Build an encoder, refusing dimensions it cannot code. |
| 284 | pub fn new(cfg: EncoderConfig) -> Result<Encoder> { |
| 285 | if cfg.width < 16 || cfg.height < 16 { |
| 286 | return Err(Error::unsupported( |
| 287 | format!("HEVC encode of {}x{}", cfg.width, cfg.height), |
| 288 | "pictures below 16x16 have no coding tree", |
| 289 | )); |
| 290 | } |
| 291 | if cfg.ctb_size != 64 && cfg.ctb_size != 32 { |
| 292 | return Err(Error::unsupported( |
| 293 | format!("HEVC coding tree block of {}", cfg.ctb_size), |
| 294 | "this encoder codes 64x64 or 32x32 trees", |
| 295 | )); |
| 296 | } |
| 297 | // The coded picture is a whole number of minimum coding blocks (8x8); |
| 298 | // the conformance window crops the padding back off. |
| 299 | let coded_width = (cfg.width as usize).next_multiple_of(8); |
| 300 | let coded_height = (cfg.height as usize).next_multiple_of(8); |
| 301 | let fps = cfg |
| 302 | .timing |
| 303 | .map(|(units, scale)| f64::from(scale) / f64::from(units.max(1))) |
| 304 | .unwrap_or(30.0); |
| 305 | let ptl = ProfileTierLevel::main(ProfileTierLevel::level_for( |
| 306 | coded_width as u32, |
| 307 | coded_height as u32, |
| 308 | fps, |
| 309 | )); |
| 310 | let vps = Vps { |
| 311 | id: 0, |
| 312 | ptl, |
| 313 | max_dec_pic_buffering_minus1: 0, |
| 314 | max_num_reorder_pics: 0, |
| 315 | }; |
| 316 | let log2_ctb = cfg.ctb_size.trailing_zeros(); |
| 317 | let sps = Sps { |
| 318 | vps_id: 0, |
| 319 | id: 0, |
| 320 | chroma_format_idc: 1, |
| 321 | separate_colour_plane: false, |
| 322 | pic_width_in_luma_samples: coded_width as u32, |
| 323 | pic_height_in_luma_samples: coded_height as u32, |
| 324 | conf_win: ConformanceWindow { |
| 325 | left: 0, |
| 326 | right: (coded_width - cfg.width as usize) as u32 / 2, |
| 327 | top: 0, |
| 328 | bottom: (coded_height - cfg.height as usize) as u32 / 2, |
| 329 | }, |
| 330 | bit_depth_luma_minus8: 0, |
| 331 | bit_depth_chroma_minus8: 0, |
| 332 | log2_max_poc_lsb_minus4: 4, |
| 333 | max_dec_pic_buffering_minus1: 0, |
| 334 | max_num_reorder_pics: 0, |
| 335 | log2_min_cb_size_minus3: 0, |
| 336 | log2_diff_max_min_cb_size: log2_ctb - 3, |
| 337 | log2_min_tb_size_minus2: 0, |
| 338 | log2_diff_max_min_tb_size: 3, |
| 339 | max_transform_hierarchy_depth_inter: 0, |
| 340 | max_transform_hierarchy_depth_intra: if cfg.rqt { 1 } else { 0 }, |
| 341 | scaling_list_enabled: false, |
| 342 | amp_enabled: false, |
| 343 | // No in-loop filters: see `Encoder` docs and the PPS below. |
| 344 | sao_enabled: false, |
| 345 | pcm_enabled: false, |
| 346 | pcm: None, |
| 347 | num_short_term_ref_pic_sets: 0, |
| 348 | short_term_ref_pic_sets: Vec::new(), |
| 349 | long_term_ref_pics_present: false, |
| 350 | num_long_term_ref_pics_sps: 0, |
| 351 | long_term_ref_pics_sps: Vec::new(), |
| 352 | temporal_mvp_enabled: false, |
| 353 | strong_intra_smoothing: true, |
| 354 | ptl, |
| 355 | vui: Some(VuiParameters { |
| 356 | sample_aspect_ratio: cfg.sample_aspect_ratio, |
| 357 | video_signal_type: cfg.video_signal_type, |
| 358 | timing: cfg.timing, |
| 359 | }), |
| 360 | }; |
| 361 | let pps = Pps { |
| 362 | id: 0, |
| 363 | sps_id: 0, |
| 364 | entropy_coding_sync_enabled: true, |
| 365 | // SAO is off; deblocking follows `EncoderConfig::deblock`. An |
| 366 | // intra-only stream predicts from its own *unfiltered* |
| 367 | // reconstruction (8.4.4.2.1), so the deblocking filter changes |
| 368 | // neither side's prediction: running it over the finished picture |
| 369 | // here keeps the reconstruction bit-identical to a decoder's |
| 370 | // output, and the picture hash that rides on it honest. |
| 371 | sign_data_hiding_enabled: cfg.sign_hiding, |
| 372 | transform_skip_enabled: cfg.transform_skip != TransformSkip::Off, |
| 373 | deblocking_filter_control_present: true, |
| 374 | deblocking_filter_disabled: !cfg.deblock, |
| 375 | loop_filter_across_slices_enabled: false, |
| 376 | ..Pps::default() |
| 377 | }; |
| 378 | let threads = if cfg.threads == 0 { |
| 379 | std::thread::available_parallelism().map_or(1, |n| n.get()) |
| 380 | } else { |
| 381 | cfg.threads |
| 382 | }; |
| 383 | Ok(Encoder { |
| 384 | cfg, |
| 385 | vps, |
| 386 | sps, |
| 387 | pps, |
| 388 | coded_width, |
| 389 | coded_height, |
| 390 | threads, |
| 391 | }) |
| 392 | } |
| 393 | |
| 394 | /// The sequence parameter set this encoder writes. |
| 395 | pub fn sps(&self) -> &Sps { |
| 396 | &self.sps |
| 397 | } |
| 398 | |
| 399 | /// Encode one picture as an IDR access unit. |
| 400 | /// |
| 401 | /// The frame must be [`PixelFormat::I420`] at the configured size; padding |
| 402 | /// to the coded size is this encoder's job, not the caller's. |
| 403 | pub fn encode_idr(&self, frame: &VideoFrame) -> Result<EncodedPicture> { |
| 404 | if frame.format != PixelFormat::I420 { |
| 405 | return Err(Error::unsupported( |
| 406 | format!("HEVC encode of {:?}", frame.format), |
| 407 | "this encoder codes 8-bit 4:2:0 planar", |
| 408 | )); |
| 409 | } |
| 410 | if frame.width != self.cfg.width || frame.height != self.cfg.height { |
| 411 | return Err(Error::corrupt(format!( |
| 412 | "HEVC encode: frame is {}x{}, encoder configured for {}x{}", |
| 413 | frame.width, frame.height, self.cfg.width, self.cfg.height |
| 414 | ))); |
| 415 | } |
| 416 | let planes: Vec<(&[u8], usize)> = frame |
| 417 | .planes |
| 418 | .iter() |
| 419 | .map(|p: &Plane| (&p.data[..], p.stride)) |
| 420 | .collect(); |
| 421 | self.encode_idr_planes( |
| 422 | planes[0].0, |
| 423 | planes[0].1, |
| 424 | planes[1].0, |
| 425 | planes[1].1, |
| 426 | planes[2].0, |
| 427 | planes[2].1, |
| 428 | ) |
| 429 | } |
| 430 | |
| 431 | /// Encode one picture from raw I420 planes with their strides. |
| 432 | /// |
| 433 | /// This is the surface a compatibility shim maps onto: the planes are the |
| 434 | /// *displayed* picture, and the conformance window handles the rest. |
| 435 | pub fn encode_idr_planes( |
| 436 | &self, |
| 437 | y: &[u8], |
| 438 | y_stride: usize, |
| 439 | cb: &[u8], |
| 440 | cb_stride: usize, |
| 441 | cr: &[u8], |
| 442 | cr_stride: usize, |
| 443 | ) -> Result<EncodedPicture> { |
| 444 | let padded = self.pad_source(y, y_stride, cb, cb_stride, cr, cr_stride)?; |
| 445 | let (mut qp, target) = match self.cfg.rate_control { |
| 446 | RateControl::ConstantQp(qp) => (qp.clamp(0, 51), None), |
| 447 | RateControl::TargetBits(bits) => { |
| 448 | let pixels = (self.cfg.width as f64) * (self.cfg.height as f64); |
| 449 | let target_bpp = (bits as f64 / pixels).max(1e-4); |
| 450 | let qp = 27.0 + 6.0 * (BPP_AT_QP27 / target_bpp).log2(); |
| 451 | ((qp.round() as i32).clamp(0, 51), Some(bits)) |
| 452 | } |
| 453 | }; |
| 454 | let mut coded = self.code_picture(&padded, qp)?; |
| 455 | if let Some(target) = target { |
| 456 | let actual = coded.au.len() as f64 * 8.0; |
| 457 | let target = target as f64; |
| 458 | if (actual - target).abs() / target > 0.25 { |
| 459 | // One correction pass, from the measured slope rather than the |
| 460 | // model: 6 QP steps is a factor of two in rate. |
| 461 | let correction = 6.0 * (actual / target).log2(); |
| 462 | let corrected = (qp as f64 + correction.clamp(-12.0, 12.0)).round() as i32; |
| 463 | let corrected = corrected.clamp(0, 51); |
| 464 | if corrected != qp { |
| 465 | qp = corrected; |
| 466 | coded = self.code_picture(&padded, qp)?; |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | Ok(coded) |
| 471 | } |
| 472 | |
| 473 | /// Encode a batch of pictures, each as its own IDR access unit. |
| 474 | /// |
| 475 | /// The wavefront inside a single picture already uses every core, so this is |
| 476 | /// a convenience for callers with a list, not a second layer of threads. |
| 477 | pub fn encode_batch<'a, I>(&self, frames: I) -> Result<Vec<EncodedPicture>> |
| 478 | where |
| 479 | I: IntoIterator<Item = &'a VideoFrame>, |
| 480 | { |
| 481 | frames.into_iter().map(|f| self.encode_idr(f)).collect() |
| 482 | } |
| 483 | |
| 484 | /// Copy the source into coded-size planes, replicating the edge into the |
| 485 | /// padding rather than filling it with black: the padding is coded and then |
| 486 | /// cropped away, and a black border would bleed into the last real column |
| 487 | /// through the prediction and the transform that straddles it. |
| 488 | fn pad_source( |
| 489 | &self, |
| 490 | y: &[u8], |
| 491 | y_stride: usize, |
| 492 | cb: &[u8], |
| 493 | cb_stride: usize, |
| 494 | cr: &[u8], |
| 495 | cr_stride: usize, |
| 496 | ) -> Result<PaddedSource> { |
| 497 | let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); |
| 498 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 499 | let (coded_w, coded_h) = (self.coded_width, self.coded_height); |
| 500 | let plane = |src: &[u8], |
| 501 | stride: usize, |
| 502 | width: usize, |
| 503 | height: usize, |
| 504 | out_w: usize, |
| 505 | out_h: usize| |
| 506 | -> Result<Vec<u8>> { |
| 507 | if stride < width || src.len() < (height - 1) * stride + width { |
| 508 | return Err(Error::corrupt( |
| 509 | "HEVC encode: source plane shorter than its stated size".to_string(), |
| 510 | )); |
| 511 | } |
| 512 | let mut out = vec![0u8; out_w * out_h]; |
| 513 | for row in 0..out_h { |
| 514 | let src_row = row.min(height - 1); |
| 515 | let line = &src[src_row * stride..src_row * stride + width]; |
| 516 | let dst = &mut out[row * out_w..row * out_w + out_w]; |
| 517 | dst[..width].copy_from_slice(line); |
| 518 | let edge = line[width - 1]; |
| 519 | dst[width..].fill(edge); |
| 520 | } |
| 521 | Ok(out) |
| 522 | }; |
| 523 | Ok(PaddedSource { |
| 524 | y: plane(y, y_stride, w, h, coded_w, coded_h)?, |
| 525 | cb: plane(cb, cb_stride, cw, ch, coded_w / 2, coded_h / 2)?, |
| 526 | cr: plane(cr, cr_stride, cw, ch, coded_w / 2, coded_h / 2)?, |
| 527 | }) |
| 528 | } |
| 529 | |
| 530 | /// Code one picture at `qp`, wavefront across CTB rows. |
| 531 | fn code_picture(&self, src: &PaddedSource, qp: i32) -> Result<EncodedPicture> { |
| 532 | let (width, height) = (self.coded_width, self.coded_height); |
| 533 | let ctb = self.cfg.ctb_size; |
| 534 | let cols = width.div_ceil(ctb); |
| 535 | let rows = height.div_ceil(ctb); |
| 536 | |
| 537 | let mut rec_y = vec![0u8; width * height]; |
| 538 | let mut rec_cb = vec![0u8; width / 2 * height / 2]; |
| 539 | let mut rec_cr = vec![0u8; width / 2 * height / 2]; |
| 540 | |
| 541 | let boundaries: Vec<RowBoundary> = (0..rows).map(|_| RowBoundary::new(width)).collect(); |
| 542 | let progress: Vec<Progress> = (0..rows).map(|_| Progress(AtomicUsize::new(0))).collect(); |
| 543 | let wpp_contexts: Vec<Mutex<Option<Contexts>>> = |
| 544 | (0..rows).map(|_| Mutex::new(None)).collect(); |
| 545 | let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect(); |
| 546 | // Each row publishes the transform-block sizes of its band, which the |
| 547 | // deblocking filter reads its edges off once the picture is whole. |
| 548 | let tu_bands: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect(); |
| 549 | |
| 550 | // One band of the reconstruction per CTB row, handed out by index. |
| 551 | let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect(); |
| 552 | let mut bands_cb: Vec<&mut [u8]> = rec_cb.chunks_mut(ctb / 2 * (width / 2)).collect(); |
| 553 | let mut bands_cr: Vec<&mut [u8]> = rec_cr.chunks_mut(ctb / 2 * (width / 2)).collect(); |
| 554 | let threads = self.threads.min(rows).max(1); |
| 555 | // Round-robin: worker t owns rows t, t + threads, ... Each row's |
| 556 | // predecessor therefore belongs to another worker that is never waiting |
| 557 | // on it, so the wavefront cannot deadlock. |
| 558 | let mut per_worker: Vec<Vec<RowAssignment<'_>>> = |
| 559 | (0..threads).map(|_| Vec::new()).collect(); |
| 560 | for row in (0..rows).rev() { |
| 561 | let y = bands_y.pop().expect("one band per row"); |
| 562 | let cb = bands_cb.pop().expect("one band per row"); |
| 563 | let cr = bands_cr.pop().expect("one band per row"); |
| 564 | per_worker[row % threads].push((row, y, cb, cr)); |
| 565 | } |
| 566 | for worker in per_worker.iter_mut() { |
| 567 | worker.reverse(); |
| 568 | } |
| 569 | |
| 570 | let slice_qp = qp; |
| 571 | std::thread::scope(|scope| { |
| 572 | for worker_rows in per_worker { |
| 573 | let boundaries = &boundaries; |
| 574 | let progress = &progress; |
| 575 | let wpp_contexts = &wpp_contexts; |
| 576 | let substreams = &substreams; |
| 577 | let tu_bands = &tu_bands; |
| 578 | let src = &src; |
| 579 | scope.spawn(move || { |
| 580 | for (row, band_y, band_cb, band_cr) in worker_rows { |
| 581 | let band_y0 = row * ctb; |
| 582 | // Wait for the row above to be two CTBs ahead, which is |
| 583 | // both the prediction reach and the CABAC sync point. |
| 584 | if row > 0 { |
| 585 | wait_for(&progress[row - 1], 2.min(cols)); |
| 586 | } |
| 587 | let contexts = if row == 0 || cols < 2 { |
| 588 | Contexts::new(slice_qp) |
| 589 | } else { |
| 590 | wpp_contexts[row - 1] |
| 591 | .lock() |
| 592 | .ok() |
| 593 | .and_then(|c| c.clone()) |
| 594 | .unwrap_or_else(|| Contexts::new(slice_qp)) |
| 595 | }; |
| 596 | let mut enc = CabacEncoder::new(contexts); |
| 597 | let mut coder = CtuEncoder::new( |
| 598 | SourcePlanes { |
| 599 | y: &src.y, |
| 600 | cb: &src.cb, |
| 601 | cr: &src.cr, |
| 602 | }, |
| 603 | RowState { |
| 604 | rec_y: band_y, |
| 605 | rec_cb: band_cb, |
| 606 | rec_cr: band_cr, |
| 607 | publish: &boundaries[row], |
| 608 | above: if row == 0 { |
| 609 | None |
| 610 | } else { |
| 611 | Some(&boundaries[row - 1]) |
| 612 | }, |
| 613 | }, |
| 614 | width, |
| 615 | height, |
| 616 | ctb, |
| 617 | band_y0, |
| 618 | slice_qp, |
| 619 | true, |
| 620 | self.cfg.rdo_candidates, |
| 621 | self.cfg.chroma_mode_search, |
| 622 | self.cfg.chroma_rd_weight, |
| 623 | self.cfg.intra_nxn, |
| 624 | self.cfg.sign_hiding, |
| 625 | self.cfg.rdoq, |
| 626 | self.cfg.rdoq_estimate, |
| 627 | self.cfg.transform_skip != TransformSkip::Off, |
| 628 | self.cfg.rqt, |
| 629 | self.cfg.cu64, |
| 630 | self.cfg.min_cu_size.max(8).trailing_zeros(), |
| 631 | ); |
| 632 | for col in 0..cols { |
| 633 | if row > 0 { |
| 634 | wait_for(&progress[row - 1], (col + 2).min(cols)); |
| 635 | } |
| 636 | coder.encode_ctu(col, &mut enc); |
| 637 | if col == 1 { |
| 638 | // 9.3.2.1: the row below syncs from the state |
| 639 | // after the second CTB of this row. |
| 640 | if let Ok(mut slot) = wpp_contexts[row].lock() { |
| 641 | *slot = Some(enc.contexts.clone()); |
| 642 | } |
| 643 | } |
| 644 | progress[row].0.store(col + 1, Ordering::Release); |
| 645 | let last_in_picture = row + 1 == rows && col + 1 == cols; |
| 646 | enc.encode_terminate(u32::from(last_in_picture)); |
| 647 | if !last_in_picture && col + 1 == cols { |
| 648 | // end_of_subset_one_bit, then byte alignment. |
| 649 | enc.encode_terminate(1); |
| 650 | } |
| 651 | } |
| 652 | if let Ok(mut slot) = substreams[row].lock() { |
| 653 | *slot = enc.finish(); |
| 654 | } |
| 655 | if let Ok(mut slot) = tu_bands[row].lock() { |
| 656 | *slot = coder.tu_log2_band().to_vec(); |
| 657 | } |
| 658 | } |
| 659 | }); |
| 660 | } |
| 661 | }); |
| 662 | |
| 663 | let substreams: Vec<Vec<u8>> = substreams |
| 664 | .into_iter() |
| 665 | .map(|m| m.into_inner().unwrap_or_default()) |
| 666 | .collect(); |
| 667 | if self.cfg.deblock { |
| 668 | let mut tus = TuMap::new(width, height); |
| 669 | for (row, band) in tu_bands.into_iter().enumerate() { |
| 670 | let band = band.into_inner().unwrap_or_default(); |
| 671 | let band_y0 = row * ctb; |
| 672 | let band_rows = (height - band_y0).min(ctb) / 4; |
| 673 | tus.absorb_band(band_y0, band_rows, &band); |
| 674 | } |
| 675 | deblock( |
| 676 | &mut rec_y, |
| 677 | &mut rec_cb, |
| 678 | &mut rec_cr, |
| 679 | width, |
| 680 | height, |
| 681 | qp, |
| 682 | &tus, |
| 683 | ); |
| 684 | } |
| 685 | |
| 686 | let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr); |
| 687 | let recon = self |
| 688 | .cfg |
| 689 | .keep_recon |
| 690 | .then(|| self.crop_recon(&rec_y, &rec_cb, &rec_cr)); |
| 691 | Ok(EncodedPicture { au, qp, recon }) |
| 692 | } |
| 693 | |
| 694 | /// Parameter sets, optional SEI, and the slice, in Annex-B framing. |
| 695 | fn assemble_au( |
| 696 | &self, |
| 697 | qp: i32, |
| 698 | substreams: &[Vec<u8>], |
| 699 | rec_y: &[u8], |
| 700 | rec_cb: &[u8], |
| 701 | rec_cr: &[u8], |
| 702 | ) -> Vec<u8> { |
| 703 | let mut au = Vec::with_capacity(substreams.iter().map(|s| s.len()).sum::<usize>() + 256); |
| 704 | write_annex_b( |
| 705 | &mut au, |
| 706 | NalHeader::new(NalUnitType::Vps), |
| 707 | &self.vps.to_rbsp(), |
| 708 | true, |
| 709 | ); |
| 710 | write_annex_b( |
| 711 | &mut au, |
| 712 | NalHeader::new(NalUnitType::Sps), |
| 713 | &self.sps.to_rbsp(), |
| 714 | true, |
| 715 | ); |
| 716 | write_annex_b( |
| 717 | &mut au, |
| 718 | NalHeader::new(NalUnitType::Pps), |
| 719 | &self.pps.to_rbsp(), |
| 720 | true, |
| 721 | ); |
| 722 | if let Some(rbsp) = sei::hdr_metadata_rbsp(self.cfg.content_light) { |
| 723 | write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true); |
| 724 | } |
| 725 | |
| 726 | // Entry points count the bytes as they appear in the NAL, emulation |
| 727 | // prevention included. Each substream ends on a byte whose last written |
| 728 | // bit is the flush's one bit, so no escape sequence straddles a |
| 729 | // boundary and each substream can be measured on its own. |
| 730 | let mut escaped: Vec<Vec<u8>> = Vec::with_capacity(substreams.len()); |
| 731 | for stream in substreams { |
| 732 | let mut out = Vec::with_capacity(stream.len() + 8); |
| 733 | escape_rbsp(stream, &mut out); |
| 734 | escaped.push(out); |
| 735 | } |
| 736 | let mut header = SliceHeader::intra(&self.pps, qp - 26); |
| 737 | header.entry_point_offsets = escaped |
| 738 | .iter() |
| 739 | .take(escaped.len().saturating_sub(1)) |
| 740 | .map(|s| s.len() as u32) |
| 741 | .collect(); |
| 742 | let mut writer = ec_core::bitio::BitWriter::with_capacity(64); |
| 743 | header.write(&mut writer, &self.sps, &self.pps, NalUnitType::IdrWRadl); |
| 744 | let mut rbsp = writer.into_bytes(); |
| 745 | for stream in substreams { |
| 746 | rbsp.extend_from_slice(stream); |
| 747 | } |
| 748 | write_annex_b(&mut au, NalHeader::new(NalUnitType::IdrWRadl), &rbsp, true); |
| 749 | |
| 750 | if self.cfg.picture_hash { |
| 751 | let (w, h) = (self.coded_width, self.coded_height); |
| 752 | let rbsp = sei::decoded_picture_hash_rbsp(&[ |
| 753 | (rec_y, w, w, h), |
| 754 | (rec_cb, w / 2, w / 2, h / 2), |
| 755 | (rec_cr, w / 2, w / 2, h / 2), |
| 756 | ]); |
| 757 | write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false); |
| 758 | } |
| 759 | au |
| 760 | } |
| 761 | |
| 762 | fn crop_recon(&self, rec_y: &[u8], rec_cb: &[u8], rec_cr: &[u8]) -> VideoFrame { |
| 763 | let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); |
| 764 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 765 | let crop = |src: &[u8], stride: usize, width: usize, height: usize| -> Vec<u8> { |
| 766 | let mut out = Vec::with_capacity(width * height); |
| 767 | for row in 0..height { |
| 768 | out.extend_from_slice(&src[row * stride..row * stride + width]); |
| 769 | } |
| 770 | out |
| 771 | }; |
| 772 | let planes = vec![ |
| 773 | Plane::new(crop(rec_y, self.coded_width, w, h), w), |
| 774 | Plane::new(crop(rec_cb, self.coded_width / 2, cw, ch), cw), |
| 775 | Plane::new(crop(rec_cr, self.coded_width / 2, cw, ch), cw), |
| 776 | ]; |
| 777 | VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes) |
| 778 | .expect("cropped planes are exactly the size I420 asks for") |
| 779 | } |
| 780 | } |
| 781 | |
| 782 | /// A progress counter on its own cache line. |
| 783 | /// |
| 784 | /// Twelve workers polling twelve counters packed eight to a line spend their |
| 785 | /// time invalidating each other's caches instead of coding; the padding is the |
| 786 | /// difference between a wavefront and a contention benchmark. |
| 787 | #[repr(align(64))] |
| 788 | struct Progress(AtomicUsize); |
| 789 | |
| 790 | /// Spin, then yield, then sleep until a row's progress counter reaches `target`. |
| 791 | /// |
| 792 | /// A worker that spins hard is a worker holding a core the wavefront needs |
| 793 | /// somewhere else, so the wait backs off to a sleep at roughly the granularity |
| 794 | /// of one coding tree block. |
| 795 | fn wait_for(counter: &Progress, target: usize) { |
| 796 | let mut spins = 0u32; |
| 797 | while counter.0.load(Ordering::Acquire) < target { |
| 798 | if spins < 128 { |
| 799 | std::hint::spin_loop(); |
| 800 | } else if spins < 256 { |
| 801 | std::thread::yield_now(); |
| 802 | } else { |
| 803 | std::thread::sleep(std::time::Duration::from_micros(50)); |
| 804 | } |
| 805 | spins += 1; |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | /// One CTB row handed to a worker: its index and its band of each plane. |
| 810 | type RowAssignment<'a> = (usize, &'a mut [u8], &'a mut [u8], &'a mut [u8]); |
| 811 | |
| 812 | struct PaddedSource { |
| 813 | y: Vec<u8>, |
| 814 | cb: Vec<u8>, |
| 815 | cr: Vec<u8>, |
| 816 | } |