| 1 | use super::*; |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | pub(super) const TPL_STRENGTH: f64 = 0.5; |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | pub(super) fn deltaq_res_log2() -> Option<u8> { |
| 34 | match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 35 | u8::MAX => {} |
| 36 | 4 => return None, |
| 37 | r => return Some(r), |
| 38 | } |
| 39 | match crate::envflags::var("EC_AV1_DELTAQ") |
| 40 | .ok() |
| 41 | .as_deref() |
| 42 | .map(str::trim) |
| 43 | { |
| 44 | Some("0") => None, |
| 45 | Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3), |
| 46 | None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4), |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | pub(super) static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX); |
| 56 | |
| 57 | |
| 58 | #[allow(dead_code)] |
| 59 | pub(crate) fn set_deltaq_res(res_log2: Option<u8>) { |
| 60 | DELTAQ_OVERRIDE.store( |
| 61 | res_log2.unwrap_or(u8::MAX), |
| 62 | std::sync::atomic::Ordering::Relaxed, |
| 63 | ); |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | pub(super) fn deltaq_k() -> f64 { |
| 69 | crate::envflags::var("EC_AV1_DELTAQ_K") |
| 70 | .ok() |
| 71 | .and_then(|v| v.trim().parse::<f64>().ok()) |
| 72 | .filter(|k| k.is_finite() && *k >= 0.0) |
| 73 | .unwrap_or(1.0) |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | pub(super) fn deltaq_clamp() -> i32 { |
| 80 | crate::envflags::var("EC_AV1_DELTAQ_CLAMP") |
| 81 | .ok() |
| 82 | .and_then(|v| v.trim().parse::<i32>().ok()) |
| 83 | .filter(|c| (0..=63).contains(c)) |
| 84 | .unwrap_or(16) |
| 85 | } |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | pub(super) fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 { |
| 100 | let base_ac = f64::from(ac_q(8, i32::from(base))); |
| 101 | let target = base_ac * f.max(1e-6).sqrt(); |
| 102 | let exact = (1..=255) |
| 103 | .min_by(|&a, &b| { |
| 104 | let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs(); |
| 105 | d(a).partial_cmp(&d(b)).expect("ac_q is finite") |
| 106 | }) |
| 107 | .expect("the qindex range is not empty") |
| 108 | - i32::from(base); |
| 109 | let want = (exact as f64 * k).round() as i32; |
| 110 | |
| 111 | |
| 112 | |
| 113 | let max_steps = clamp / res; |
| 114 | let steps = (want as f64 / f64::from(res)).round() as i32; |
| 115 | let delta = steps.clamp(-max_steps, max_steps) * res; |
| 116 | (i32::from(base) + delta).clamp(1, 255) as u8 |
| 117 | } |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | pub(super) fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 { |
| 141 | let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6); |
| 142 | let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt(); |
| 143 | let exact = (1..=255) |
| 144 | .min_by(|&a, &b| { |
| 145 | let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs(); |
| 146 | d(a).partial_cmp(&d(b)).expect("dc_q is finite") |
| 147 | }) |
| 148 | .expect("the qindex range is not empty") |
| 149 | - i32::from(base); |
| 150 | let want = exact as f64 * strength; |
| 151 | |
| 152 | |
| 153 | let max_steps = (res * 9 - 1) / res; |
| 154 | let steps = (want / f64::from(res)).round() as i32; |
| 155 | let delta = steps.clamp(-max_steps, max_steps) * res; |
| 156 | (i32::from(base) + delta).clamp(1, 255) as u8 |
| 157 | } |
| 158 | |
| 159 | |
| 160 | |
| 161 | pub(super) fn tpl_frame_ratio(ratio: &[f64]) -> f64 { |
| 162 | if ratio.is_empty() { |
| 163 | return 0.0; |
| 164 | } |
| 165 | let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64; |
| 166 | m.exp() - 1.0 |
| 167 | } |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | pub(super) fn dq_tpl_strength(level: DqLevel) -> Option<f64> { |
| 176 | let m = dq_level_k()[level as usize]; |
| 177 | let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K") |
| 178 | .ok() |
| 179 | .and_then(|v| v.trim().parse::<f64>().ok()) |
| 180 | .filter(|k| k.is_finite() && *k >= 0.0); |
| 181 | let base = match crate::envflags::var("EC_AV1_DQ_TPL") |
| 182 | .ok() |
| 183 | .as_deref() |
| 184 | .map(str::trim) |
| 185 | { |
| 186 | Some("0") => return None, |
| 187 | Some(_) => Some(env_k.unwrap_or(1.0)), |
| 188 | None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))), |
| 189 | }; |
| 190 | base.map(|k| k * m).filter(|k| *k > 0.0) |
| 191 | } |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 199 | pub(crate) enum DqLevel { |
| 200 | |
| 201 | |
| 202 | TopArf = 0, |
| 203 | |
| 204 | MidArf = 1, |
| 205 | |
| 206 | Leaf = 2, |
| 207 | } |
| 208 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | pub(super) fn dq_level_k() -> [f64; 3] { |
| 214 | dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref()) |
| 215 | } |
| 216 | |
| 217 | |
| 218 | |
| 219 | pub(super) fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] { |
| 220 | let mut k = crate::speed::DQ_LEVEL_K; |
| 221 | if let Some(spec) = spec { |
| 222 | for (slot, field) in k.iter_mut().zip(spec.split(':')) { |
| 223 | if let Some(v) = field |
| 224 | .trim() |
| 225 | .parse::<f64>() |
| 226 | .ok() |
| 227 | .filter(|v: &f64| v.is_finite() && *v >= 0.0) |
| 228 | { |
| 229 | *slot = v; |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | k |
| 234 | } |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | pub(super) fn dq_census() -> bool { |
| 241 | crate::envflags::var("EC_AV1_DQ_CENSUS") |
| 242 | .ok() |
| 243 | .as_deref() |
| 244 | .map(str::trim) |
| 245 | == Some("1") |
| 246 | } |
| 247 | |
| 248 | |
| 249 | pub(super) fn dq_summary(offsets: &[i32]) -> String { |
| 250 | let n = offsets.len().max(1); |
| 251 | let (lo, hi) = offsets |
| 252 | .iter() |
| 253 | .fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o))); |
| 254 | let nz = offsets.iter().filter(|&&o| o != 0).count(); |
| 255 | let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64; |
| 256 | let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64; |
| 257 | let mut levels: Vec<i32> = offsets.to_vec(); |
| 258 | levels.sort_unstable(); |
| 259 | levels.dedup(); |
| 260 | format!( |
| 261 | "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}", |
| 262 | offsets.len(), |
| 263 | levels.len() |
| 264 | ) |
| 265 | } |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | pub(super) static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 274 | |
| 275 | |
| 276 | #[allow(dead_code)] |
| 277 | pub(crate) fn take_deltaq_levels() -> usize { |
| 278 | DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 279 | } |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | pub(super) fn sb_q_search<'m>( |
| 287 | sb_q: &[u8], |
| 288 | sb_cols: usize, |
| 289 | base_q_idx: u8, |
| 290 | (sb_r, sb_c): (usize, usize), |
| 291 | base: Search<'m>, |
| 292 | ) -> Search<'m> { |
| 293 | let q = sb_q[sb_r * sb_cols + sb_c]; |
| 294 | let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx))); |
| 295 | Search { |
| 296 | base_q_idx: q, |
| 297 | lambda: base.lambda * ratio * ratio, |
| 298 | ..base |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | pub(super) fn tpl_strength() -> f64 { |
| 303 | std::env::var("EC_AV1_TPL") |
| 304 | .ok() |
| 305 | .and_then(|v| v.parse::<f64>().ok()) |
| 306 | .filter(|k| k.is_finite() && *k >= 0.0) |
| 307 | .unwrap_or(TPL_STRENGTH) |
| 308 | } |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | pub(crate) const TPL_DEPTH: usize = 8; |
| 321 | |
| 322 | |
| 323 | |
| 324 | pub(super) const TPL_POWER: f64 = 0.5; |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | pub(super) fn tpl_propagating() -> bool { |
| 384 | std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0") |
| 385 | } |
| 386 | |
| 387 | pub(crate) fn tpl_depth() -> usize { |
| 388 | std::env::var("EC_AV1_TPL_D") |
| 389 | .ok() |
| 390 | .and_then(|v| v.parse::<usize>().ok()) |
| 391 | .filter(|d| *d >= 1) |
| 392 | .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH)) |
| 393 | .max(1) |
| 394 | } |
| 395 | |
| 396 | |
| 397 | |
| 398 | pub(super) static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | pub(super) fn tpl_coarse_pass(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<((i32, i32), u32)> { |
| 408 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 409 | let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 { |
| 410 | let (sx, sy) = (bx as i32 + mx, by as i32 + my); |
| 411 | if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height { |
| 412 | return u32::MAX; |
| 413 | } |
| 414 | let (sx, sy) = (sx as usize, sy as usize); |
| 415 | let mut sum = 0u32; |
| 416 | for r in 0..16 { |
| 417 | let a = &next[(by + r) * width + bx..][..16]; |
| 418 | let b = &cur[(sy + r) * width + sx..][..16]; |
| 419 | sum += a |
| 420 | .iter() |
| 421 | .zip(b) |
| 422 | .map(|(&p, &q)| u32::from(p.abs_diff(q))) |
| 423 | .sum::<u32>(); |
| 424 | } |
| 425 | sum |
| 426 | }; |
| 427 | let mut out = Vec::with_capacity(cells_x * cells_y); |
| 428 | let mut above = vec![(0i32, 0i32); cells_x]; |
| 429 | for cy in 0..cells_y { |
| 430 | let mut left = (0i32, 0i32); |
| 431 | |
| 432 | #[allow(clippy::needless_range_loop)] |
| 433 | for cx in 0..cells_x { |
| 434 | let (bx, by) = (cx * 16, cy * 16); |
| 435 | let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32)); |
| 436 | for cand in [left, above[cx]] { |
| 437 | if cand != (0, 0) { |
| 438 | let s = sad(bx, by, cand); |
| 439 | if s < best.0 { |
| 440 | best = (s, cand); |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | for step in [8i32, 4, 2, 1] { |
| 445 | let centre = best.1; |
| 446 | for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] { |
| 447 | let mv = (centre.0 + dx, centre.1 + dy); |
| 448 | if mv.0.abs() > 32 || mv.1.abs() > 32 { |
| 449 | continue; |
| 450 | } |
| 451 | let s = sad(bx, by, mv); |
| 452 | if s < best.0 { |
| 453 | best = (s, mv); |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | left = best.1; |
| 458 | above[cx] = best.1; |
| 459 | out.push((best.1, best.0)); |
| 460 | } |
| 461 | } |
| 462 | out |
| 463 | } |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 468 | |
| 469 | pub(super) fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> { |
| 470 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 471 | let mut out = Vec::with_capacity(cells_x * cells_y); |
| 472 | for cy in 0..cells_y { |
| 473 | for cx in 0..cells_x { |
| 474 | let (bx, by) = (cx * 16, cy * 16); |
| 475 | let mut sum = 0u32; |
| 476 | for r in 0..16 { |
| 477 | sum += frame[(by + r) * width + bx..][..16] |
| 478 | .iter() |
| 479 | .map(|&p| u32::from(p)) |
| 480 | .sum::<u32>(); |
| 481 | } |
| 482 | let dc = ((sum + 128) / 256) as u8; |
| 483 | let mut cost = 0u32; |
| 484 | for r in 0..16 { |
| 485 | cost += frame[(by + r) * width + bx..][..16] |
| 486 | .iter() |
| 487 | .map(|&p| u32::from(p.abs_diff(dc))) |
| 488 | .sum::<u32>(); |
| 489 | } |
| 490 | out.push(cost); |
| 491 | } |
| 492 | } |
| 493 | out |
| 494 | } |
| 495 | |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | pub(super) fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> { |
| 501 | let start = std::time::Instant::now(); |
| 502 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 503 | let pass = tpl_coarse_pass(cur, next, width, height); |
| 504 | let mut area = vec![0.0f64; cells_x * cells_y]; |
| 505 | for cy in 0..cells_y { |
| 506 | for cx in 0..cells_x { |
| 507 | let (mv, _) = pass[cy * cells_x + cx]; |
| 508 | let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1); |
| 509 | let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); |
| 510 | for ci in x0 / 16..=x0.div_ceil(16).min(cells_x - 1) { |
| 511 | let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16); |
| 512 | for ri in y0 / 16..=y0.div_ceil(16).min(cells_y - 1) { |
| 513 | let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16); |
| 514 | area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0; |
| 515 | } |
| 516 | } |
| 517 | } |
| 518 | } |
| 519 | TPL_NANOS.fetch_add( |
| 520 | start.elapsed().as_nanos() as u64, |
| 521 | std::sync::atomic::Ordering::Relaxed, |
| 522 | ); |
| 523 | area |
| 524 | } |
| 525 | |
| 526 | |
| 527 | |
| 528 | |
| 529 | |
| 530 | |
| 531 | |
| 532 | |
| 533 | pub(super) fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> { |
| 534 | let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4); |
| 535 | let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6); |
| 536 | let mut out = Vec::with_capacity(sb_cols * sb_rows); |
| 537 | for sr in 0..sb_rows { |
| 538 | for sc in 0..sb_cols { |
| 539 | let mut sum = 0.0; |
| 540 | for r in 0..4 { |
| 541 | for c in 0..4 { |
| 542 | sum += map[(sr * 4 + r) * cells_x + sc * 4 + c]; |
| 543 | } |
| 544 | } |
| 545 | let w_rel = sum / 16.0 / mean; |
| 546 | out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0)); |
| 547 | } |
| 548 | } |
| 549 | if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") { |
| 550 | let mut hist = [0usize; 8]; |
| 551 | for w in map { |
| 552 | hist[((w / mean * 2.0) as usize).min(7)] += 1; |
| 553 | } |
| 554 | let (lo, hi) = out |
| 555 | .iter() |
| 556 | .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f))); |
| 557 | eprintln!( |
| 558 | "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \ |
| 559 | sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative", |
| 560 | map.len(), |
| 561 | TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, |
| 562 | ); |
| 563 | } |
| 564 | out |
| 565 | } |
| 566 | |
| 567 | |
| 568 | |
| 569 | |
| 570 | |
| 571 | |
| 572 | |
| 573 | |
| 574 | |
| 575 | |
| 576 | |
| 577 | |
| 578 | |
| 579 | |
| 580 | |
| 581 | |
| 582 | |
| 583 | |
| 584 | |
| 585 | |
| 586 | |
| 587 | |
| 588 | |
| 589 | pub(super) fn tpl_lambda_factors( |
| 590 | frames: &[&[u8]], |
| 591 | width: usize, |
| 592 | height: usize, |
| 593 | k: f64, |
| 594 | ) -> (Vec<f64>, Vec<f64>) { |
| 595 | let start = std::time::Instant::now(); |
| 596 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 597 | let cells = cells_x * cells_y; |
| 598 | let levels = frames.len(); |
| 599 | let intra: Vec<Vec<u32>> = frames |
| 600 | .iter() |
| 601 | .map(|f| tpl_intra_costs(f, width, height)) |
| 602 | .collect(); |
| 603 | let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels) |
| 604 | .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height)) |
| 605 | .collect(); |
| 606 | let mut mc_dep = vec![vec![0.0f64; cells]; levels]; |
| 607 | for f in (1..levels).rev() { |
| 608 | for cy in 0..cells_y { |
| 609 | for cx in 0..cells_x { |
| 610 | let ci = cy * cells_x + cx; |
| 611 | let (mv, inter) = passes[f - 1][ci]; |
| 612 | let saved = f64::from(intra[f][ci].saturating_sub(inter)); |
| 613 | let propagate = saved + mc_dep[f][ci]; |
| 614 | if propagate <= 0.0 { |
| 615 | continue; |
| 616 | } |
| 617 | |
| 618 | |
| 619 | let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1); |
| 620 | let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); |
| 621 | for rc in x0 / 16..=x0.div_ceil(16).min(cells_x - 1) { |
| 622 | let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16); |
| 623 | for rr in y0 / 16..=y0.div_ceil(16).min(cells_y - 1) { |
| 624 | let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16); |
| 625 | mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0; |
| 626 | } |
| 627 | } |
| 628 | } |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | |
| 633 | |
| 634 | |
| 635 | |
| 636 | let power = std::env::var("EC_AV1_TPL_P") |
| 637 | .ok() |
| 638 | .and_then(|v| v.parse::<f64>().ok()) |
| 639 | .filter(|p| p.is_finite() && *p > 0.0) |
| 640 | .unwrap_or(TPL_POWER); |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | |
| 646 | |
| 647 | |
| 648 | |
| 649 | |
| 650 | |
| 651 | |
| 652 | |
| 653 | |
| 654 | |
| 655 | |
| 656 | let floor_frac = std::env::var("EC_AV1_TPL_FLOOR") |
| 657 | .ok() |
| 658 | .and_then(|v| v.parse::<f64>().ok()) |
| 659 | .filter(|f| f.is_finite() && *f >= 0.0) |
| 660 | .unwrap_or(0.0); |
| 661 | let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0"); |
| 662 | let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0"); |
| 663 | let intra_mean = intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64; |
| 664 | let floor = floor_frac * intra_mean; |
| 665 | let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0); |
| 666 | |
| 667 | |
| 668 | let ratio: Vec<f64> = if sb_agg { |
| 669 | let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4)); |
| 670 | let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows]; |
| 671 | for cy in 0..cells_y { |
| 672 | for cx in 0..cells_x { |
| 673 | let e = &mut sb[(cy / 4) * sb_cols + cx / 4]; |
| 674 | e.0 += mc_dep[0][cy * cells_x + cx]; |
| 675 | e.1 += denom(cy * cells_x + cx); |
| 676 | } |
| 677 | } |
| 678 | (0..cells) |
| 679 | .map(|c| { |
| 680 | let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4]; |
| 681 | dep / den.max(1.0) |
| 682 | }) |
| 683 | .collect() |
| 684 | } else { |
| 685 | (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect() |
| 686 | }; |
| 687 | let mut out: Vec<f64> = ratio |
| 688 | .iter() |
| 689 | .map(|&r| { |
| 690 | let r = if log_beta { (1.0 + r).log2() } else { r }; |
| 691 | (1.0 + k * r).powf(-power) |
| 692 | }) |
| 693 | .collect(); |
| 694 | let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9); |
| 695 | for f in &mut out { |
| 696 | *f = (*f / mean).clamp(0.25, 4.0); |
| 697 | } |
| 698 | TPL_NANOS.fetch_add( |
| 699 | start.elapsed().as_nanos() as u64, |
| 700 | std::sync::atomic::Ordering::Relaxed, |
| 701 | ); |
| 702 | if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") { |
| 703 | let mut hist = [0usize; 8]; |
| 704 | for &f in &out { |
| 705 | hist[((f * 4.0) as usize).min(7)] += 1; |
| 706 | } |
| 707 | let (lo, hi) = out |
| 708 | .iter() |
| 709 | .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f))); |
| 710 | let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count(); |
| 711 | eprintln!( |
| 712 | "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \ |
| 713 | range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative", |
| 714 | TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, |
| 715 | ); |
| 716 | } |
| 717 | (out, ratio) |
| 718 | } |
| 719 | |
| 720 | |
| 721 | |
| 722 | |
| 723 | |
| 724 | |
| 725 | |
| 726 | |
| 727 | |
| 728 | |
| 729 | |
| 730 | #[derive(Debug, Clone, Copy)] |
| 731 | pub(crate) struct PyramidFrame { |
| 732 | |
| 733 | |
| 734 | pub last_slot: u8, |
| 735 | |
| 736 | pub self_slot: u8, |
| 737 | |
| 738 | |
| 739 | pub altref_slot: u8, |
| 740 | |
| 741 | |
| 742 | |
| 743 | |
| 744 | |
| 745 | pub last2_slot: Option<u8>, |
| 746 | |
| 747 | |
| 748 | pub show_frame: bool, |
| 749 | |
| 750 | |
| 751 | |
| 752 | pub dq_level: DqLevel, |
| 753 | |
| 754 | pub sign_bias: crate::mvstack::SignBiasTable, |
| 755 | } |
| 756 | |
| 757 | |
| 758 | |
| 759 | |
| 760 | |
| 761 | |
| 762 | |
| 763 | |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | |
| 774 | |
| 775 | |
| 776 | |
| 777 | pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture { |
| 778 | const SIDE: usize = 16; |
| 779 | let neighbours: Vec<&Picture> = window |
| 780 | .iter() |
| 781 | .filter(|p| p.width == src.width && p.height == src.height) |
| 782 | .collect(); |
| 783 | if neighbours.is_empty() || strength <= 0.0 { |
| 784 | return src.clone(); |
| 785 | } |
| 786 | let mut out = src.clone(); |
| 787 | |
| 788 | |
| 789 | let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| { |
| 790 | let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1); |
| 791 | if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width { |
| 792 | return None; |
| 793 | } |
| 794 | let (sy, sx) = (sy as usize, sx as usize); |
| 795 | let mut acc = 0u64; |
| 796 | for row in 0..SIDE { |
| 797 | let c = &src.y[(by + row) * src.width + bx..][..SIDE]; |
| 798 | let p = &r.y[(sy + row) * r.width + sx..][..SIDE]; |
| 799 | acc += c |
| 800 | .iter() |
| 801 | .zip(p) |
| 802 | .map(|(&a, &b)| u64::from(a.abs_diff(b))) |
| 803 | .sum::<u64>(); |
| 804 | } |
| 805 | Some((acc, (sy, sx))) |
| 806 | }; |
| 807 | |
| 808 | let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> { |
| 809 | let mut best = sad(r, bx, by, (0, 0))?; |
| 810 | let mut centre = (0isize, 0isize); |
| 811 | let mut step = 16isize; |
| 812 | while step >= 1 { |
| 813 | let from = centre; |
| 814 | for (dy, dx) in [ |
| 815 | (-1, -1), |
| 816 | (-1, 0), |
| 817 | (-1, 1), |
| 818 | (0, -1), |
| 819 | (0, 1), |
| 820 | (1, -1), |
| 821 | (1, 0), |
| 822 | (1, 1), |
| 823 | ] { |
| 824 | let mv = (from.0 + dy * step, from.1 + dx * step); |
| 825 | if let Some(s) = sad(r, bx, by, mv) |
| 826 | && s.0 < best.0 { |
| 827 | best = s; |
| 828 | centre = mv; |
| 829 | } |
| 830 | } |
| 831 | step /= 2; |
| 832 | } |
| 833 | Some(best.1) |
| 834 | }; |
| 835 | let (cw, ch) = (src.width / 2, src.height / 2); |
| 836 | for by in (0..src.height).step_by(SIDE) { |
| 837 | for bx in (0..src.width).step_by(SIDE) { |
| 838 | if by + SIDE > src.height || bx + SIDE > src.width { |
| 839 | continue; |
| 840 | } |
| 841 | let mut y_acc = vec![0f64; SIDE * SIDE]; |
| 842 | let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]]; |
| 843 | let mut wsum = 1.0f64; |
| 844 | |
| 845 | |
| 846 | |
| 847 | |
| 848 | let mut cwsum = 1.0f64; |
| 849 | for row in 0..SIDE { |
| 850 | for col in 0..SIDE { |
| 851 | y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]); |
| 852 | } |
| 853 | } |
| 854 | for row in 0..SIDE / 2 { |
| 855 | for col in 0..SIDE / 2 { |
| 856 | let i = (by / 2 + row) * cw + bx / 2 + col; |
| 857 | c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]); |
| 858 | c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]); |
| 859 | } |
| 860 | } |
| 861 | for r in &neighbours { |
| 862 | let Some((sy, sx)) = search(r, bx, by) else { |
| 863 | continue; |
| 864 | }; |
| 865 | let mut sse = 0f64; |
| 866 | for row in 0..SIDE { |
| 867 | for col in 0..SIDE { |
| 868 | let d = f64::from(src.y[(by + row) * src.width + bx + col]) |
| 869 | - f64::from(r.y[(sy + row) * r.width + sx + col]); |
| 870 | sse += d * d; |
| 871 | } |
| 872 | } |
| 873 | let w = (-sse / (SIDE * SIDE) as f64 / strength).exp(); |
| 874 | for row in 0..SIDE { |
| 875 | for col in 0..SIDE { |
| 876 | y_acc[row * SIDE + col] += |
| 877 | w * f64::from(r.y[(sy + row) * r.width + sx + col]); |
| 878 | } |
| 879 | } |
| 880 | |
| 881 | |
| 882 | |
| 883 | |
| 884 | let (cy, cx) = (sy / 2, sx / 2); |
| 885 | if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw { |
| 886 | for row in 0..SIDE / 2 { |
| 887 | for col in 0..SIDE / 2 { |
| 888 | let i = (cy + row) * cw + cx + col; |
| 889 | c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]); |
| 890 | c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]); |
| 891 | } |
| 892 | } |
| 893 | cwsum += w; |
| 894 | } |
| 895 | wsum += w; |
| 896 | } |
| 897 | for row in 0..SIDE { |
| 898 | for col in 0..SIDE { |
| 899 | out.y[(by + row) * src.width + bx + col] = |
| 900 | (y_acc[row * SIDE + col] / wsum).round() as u16; |
| 901 | } |
| 902 | } |
| 903 | for row in 0..SIDE / 2 { |
| 904 | for col in 0..SIDE / 2 { |
| 905 | let i = (by / 2 + row) * cw + bx / 2 + col; |
| 906 | out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16; |
| 907 | out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16; |
| 908 | } |
| 909 | } |
| 910 | } |
| 911 | } |
| 912 | out |
| 913 | } |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 918 | |
| 919 | #[allow(clippy::too_many_arguments)] |
| 920 | pub(crate) fn encode_inter_frame( |
| 921 | picture: &Picture, |
| 922 | reference: &Picture, |
| 923 | base_q_idx: u8, |
| 924 | deadzone: f64, |
| 925 | order_hint: u32, |
| 926 | |
| 927 | |
| 928 | |
| 929 | |
| 930 | |
| 931 | order_hints: [u32; 7], |
| 932 | render: (usize, usize), |
| 933 | |
| 934 | |
| 935 | |
| 936 | |
| 937 | start_cdfs: Option<&crate::cdf_state::Cdfs>, |
| 938 | |
| 939 | |
| 940 | |
| 941 | golden: Option<&Picture>, |
| 942 | |
| 943 | |
| 944 | |
| 945 | altref: Option<&Picture>, |
| 946 | |
| 947 | |
| 948 | |
| 949 | |
| 950 | |
| 951 | last2: Option<&Picture>, |
| 952 | fctx: &crate::decode::FrameCtx, |
| 953 | |
| 954 | |
| 955 | pyramid: Option<PyramidFrame>, |
| 956 | |
| 957 | |
| 958 | |
| 959 | |
| 960 | lookahead: &[Picture], |
| 961 | ) -> Result<Encoded> { |
| 962 | picture.check()?; |
| 963 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| 964 | return Err(Error::unsupported( |
| 965 | "AV1 encode", |
| 966 | "an inter frame is coded only for a picture that is a whole number \ |
| 967 | of 64x64 superblocks -- the inter tile writer never splits a \ |
| 968 | superblock's partition below that", |
| 969 | )); |
| 970 | } |
| 971 | if reference.width != picture.width || reference.height != picture.height { |
| 972 | return Err(Error::unsupported( |
| 973 | "AV1 encode", |
| 974 | "the reference picture must be the same size as the one being coded", |
| 975 | )); |
| 976 | } |
| 977 | |
| 978 | |
| 979 | |
| 980 | |
| 981 | |
| 982 | const LAST_SLOT: u8 = 0; |
| 983 | |
| 984 | |
| 985 | |
| 986 | |
| 987 | let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot); |
| 988 | let last_slot = pyramid.map_or( |
| 989 | if order_hint <= 1 { |
| 990 | LAST_SLOT |
| 991 | } else if (order_hint - 1) % 2 == 1 { |
| 992 | 0 |
| 993 | } else { |
| 994 | 2 |
| 995 | }, |
| 996 | |p| p.last_slot, |
| 997 | ); |
| 998 | |
| 999 | |
| 1000 | |
| 1001 | |
| 1002 | |
| 1003 | |
| 1004 | let (seq, mut header) = inter_frame_headers_slots( |
| 1005 | render.0, |
| 1006 | render.1, |
| 1007 | base_q_idx, |
| 1008 | order_hint, |
| 1009 | last_slot, |
| 1010 | self_slot, |
| 1011 | match pyramid { |
| 1012 | Some(p) => p.altref_slot, |
| 1013 | None if altref.is_some() => self_slot, |
| 1014 | None => GOLDEN_SLOT, |
| 1015 | }, |
| 1016 | )?; |
| 1017 | header.render_width = render.0 as u32; |
| 1018 | header.render_height = render.1 as u32; |
| 1019 | |
| 1020 | |
| 1021 | |
| 1022 | |
| 1023 | header.interpolation_filter = frame_interp_filter(); |
| 1024 | fctx.interp_filter.set(mc::InterpFilterKind::from_header( |
| 1025 | header.interpolation_filter, |
| 1026 | )); |
| 1027 | let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias); |
| 1028 | |
| 1029 | |
| 1030 | |
| 1031 | |
| 1032 | |
| 1033 | |
| 1034 | header.order_hints = order_hints; |
| 1035 | |
| 1036 | |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | if let Some(slot) = pyramid.and_then(|p| p.last2_slot) { |
| 1041 | header.ref_frame_idx[1] = slot; |
| 1042 | } |
| 1043 | header.reference_select = reference_select(); |
| 1044 | |
| 1045 | |
| 1046 | |
| 1047 | |
| 1048 | |
| 1049 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 1050 | |
| 1051 | |
| 1052 | let hp_mv = header.allow_high_precision_mv; |
| 1053 | crate::tile::arm_high_precision_mv(hp_mv); |
| 1054 | if let Some(p) = pyramid { |
| 1055 | header.show_frame = p.show_frame; |
| 1056 | header.showable_frame = !p.show_frame; |
| 1057 | header.ref_frame_sign_bias = p.sign_bias; |
| 1058 | } |
| 1059 | |
| 1060 | |
| 1061 | |
| 1062 | |
| 1063 | let tx_select = tx_select() && tx_select_inter(); |
| 1064 | if tx_select { |
| 1065 | header.tx_mode = TxMode::Select; |
| 1066 | } |
| 1067 | |
| 1068 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 1069 | |
| 1070 | |
| 1071 | |
| 1072 | |
| 1073 | |
| 1074 | |
| 1075 | let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize); |
| 1076 | fctx.seg_mi_dims.set(frame_mi_dims); |
| 1077 | |
| 1078 | |
| 1079 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 1080 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 1081 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 1082 | |
| 1083 | |
| 1084 | |
| 1085 | |
| 1086 | |
| 1087 | let screen = |
| 1088 | seq_screen() && screen_content(&picture_y8, picture.width, true_width, true_height); |
| 1089 | header.allow_screen_content_tools = screen; |
| 1090 | |
| 1091 | |
| 1092 | header.reduced_tx_set = !wide_tx_set(screen); |
| 1093 | |
| 1094 | |
| 1095 | |
| 1096 | |
| 1097 | |
| 1098 | |
| 1099 | |
| 1100 | fctx.reduced_tx_set_inter.set(header.reduced_tx_set); |
| 1101 | |
| 1102 | |
| 1103 | |
| 1104 | |
| 1105 | crate::tile::arm_pricing_cdfs(start_cdfs, screen); |
| 1106 | let mut luma = Plane { |
| 1107 | source: &picture_y8, |
| 1108 | reconstruction: vec![128; picture_y8.len()], |
| 1109 | width: picture.width, |
| 1110 | height: picture.height, |
| 1111 | true_width, |
| 1112 | true_height, |
| 1113 | tile_x0: 0, |
| 1114 | tile_y0: 0, |
| 1115 | tile_x1: picture.width, |
| 1116 | tile_y1: picture.height, |
| 1117 | ctx: CoefCtxMap::default(), |
| 1118 | }; |
| 1119 | let mut chroma = [ |
| 1120 | Plane { |
| 1121 | source: &picture_u8, |
| 1122 | reconstruction: vec![128; picture_u8.len()], |
| 1123 | width: picture.width / 2, |
| 1124 | height: picture.height / 2, |
| 1125 | true_width: true_width / 2, |
| 1126 | true_height: true_height / 2, |
| 1127 | tile_x0: 0, |
| 1128 | tile_y0: 0, |
| 1129 | tile_x1: picture.width / 2, |
| 1130 | tile_y1: picture.height / 2, |
| 1131 | ctx: CoefCtxMap::default(), |
| 1132 | }, |
| 1133 | Plane { |
| 1134 | source: &picture_v8, |
| 1135 | reconstruction: vec![128; picture_v8.len()], |
| 1136 | width: picture.width / 2, |
| 1137 | height: picture.height / 2, |
| 1138 | true_width: true_width / 2, |
| 1139 | true_height: true_height / 2, |
| 1140 | tile_x0: 0, |
| 1141 | tile_y0: 0, |
| 1142 | tile_x1: picture.width / 2, |
| 1143 | tile_y1: picture.height / 2, |
| 1144 | ctx: CoefCtxMap::default(), |
| 1145 | }, |
| 1146 | ]; |
| 1147 | |
| 1148 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 1149 | let top_arf = matches!( |
| 1150 | pyramid, |
| 1151 | Some(p) if p.dq_level == DqLevel::TopArf |
| 1152 | ); |
| 1153 | let arfmode_v = arfmode(); |
| 1154 | let search = Search { |
| 1155 | base_q_idx, |
| 1156 | deadzone, |
| 1157 | lambda: lambda_scale() |
| 1158 | * match pyramid { |
| 1159 | Some(p) if !p.show_frame => hidden_lambda_factor(), |
| 1160 | _ => 1.0, |
| 1161 | } |
| 1162 | * step |
| 1163 | * step, |
| 1164 | modes: &KEY_FRAME_MODES, |
| 1165 | top_k: prune_top_k_inter(), |
| 1166 | screen, |
| 1167 | |
| 1168 | |
| 1169 | |
| 1170 | |
| 1171 | |
| 1172 | arf_leaf_intra: !top_arf || arfmode_v & 1 == 0, |
| 1173 | arf_leaf8: !top_arf || arfmode_v & 2 == 0, |
| 1174 | arf_leaf_compound: !top_arf || arfmode_v & 4 == 0, |
| 1175 | }; |
| 1176 | let mode_bits_table = inter_mode_bits(); |
| 1177 | |
| 1178 | |
| 1179 | |
| 1180 | let tpl_k = tpl_strength(); |
| 1181 | let window: Vec<&Picture> = lookahead |
| 1182 | .iter() |
| 1183 | .take_while(|n| n.width == picture.width && n.height == picture.height) |
| 1184 | .collect(); |
| 1185 | let tpl_sources: Vec<Vec<u8>> = window |
| 1186 | .iter() |
| 1187 | .map(|n| n.y.iter().map(|&v| v as u8).collect()) |
| 1188 | .collect(); |
| 1189 | let tpl_cells_x = picture.width / 16; |
| 1190 | |
| 1191 | |
| 1192 | let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> = (tpl_k > 0.0 && !tpl_sources.is_empty()) |
| 1193 | .then(|| { |
| 1194 | if tpl_propagating() { |
| 1195 | let mut frames: Vec<&[u8]> = vec![&picture_y8]; |
| 1196 | frames.extend(tpl_sources.iter().map(Vec::as_slice)); |
| 1197 | let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k); |
| 1198 | (f, Some(r)) |
| 1199 | } else { |
| 1200 | |
| 1201 | |
| 1202 | |
| 1203 | |
| 1204 | let map = tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height); |
| 1205 | let cells_y = picture.height / 16; |
| 1206 | let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k); |
| 1207 | let f: Vec<f64> = (0..tpl_cells_x * cells_y) |
| 1208 | .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4]) |
| 1209 | .collect(); |
| 1210 | (f, None) |
| 1211 | } |
| 1212 | }); |
| 1213 | let (tpl_factors, tpl_ratio) = match tpl_both { |
| 1214 | Some((f, r)) => (Some(f), r), |
| 1215 | None => (None, None), |
| 1216 | }; |
| 1217 | |
| 1218 | |
| 1219 | |
| 1220 | |
| 1221 | |
| 1222 | |
| 1223 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 1224 | let (cols, rows) = (cols as usize, rows as usize); |
| 1225 | let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 1226 | |
| 1227 | |
| 1228 | |
| 1229 | |
| 1230 | |
| 1231 | |
| 1232 | |
| 1233 | |
| 1234 | |
| 1235 | |
| 1236 | |
| 1237 | let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level); |
| 1238 | let deltaq_res: Option<i32> = tpl_factors |
| 1239 | .as_ref() |
| 1240 | .filter(|_| !screen) |
| 1241 | .and(deltaq_res_log2().map(|r| 1i32 << r)); |
| 1242 | |
| 1243 | |
| 1244 | |
| 1245 | let sb_mean = |m: &[f64], sb: usize| { |
| 1246 | let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols); |
| 1247 | (0..16) |
| 1248 | .map(|i| { |
| 1249 | let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4); |
| 1250 | m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)] |
| 1251 | }) |
| 1252 | .sum::<f64>() |
| 1253 | / 16.0 |
| 1254 | }; |
| 1255 | |
| 1256 | |
| 1257 | |
| 1258 | let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio); |
| 1259 | let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 { |
| 1260 | match (libaom, tpl_ratio.as_deref(), r_frame) { |
| 1261 | (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res), |
| 1262 | _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res), |
| 1263 | } |
| 1264 | }; |
| 1265 | let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) { |
| 1266 | (Some(f), Some(res)) => { |
| 1267 | let libaom = dq_tpl_strength(dq_level); |
| 1268 | let mut g: Vec<u8> = (0..sb_cols * _sb_rows) |
| 1269 | .map(|sb| sb_qindex(f, res, sb, libaom)) |
| 1270 | .collect(); |
| 1271 | |
| 1272 | |
| 1273 | |
| 1274 | |
| 1275 | if sb128_on() { |
| 1276 | for sb_r in 0.._sb_rows { |
| 1277 | for sb_c in 0..sb_cols { |
| 1278 | let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)]; |
| 1279 | g[sb_r * sb_cols + sb_c] = q; |
| 1280 | } |
| 1281 | } |
| 1282 | } |
| 1283 | Some(g) |
| 1284 | } |
| 1285 | _ => None, |
| 1286 | }; |
| 1287 | |
| 1288 | |
| 1289 | |
| 1290 | if dq_census() |
| 1291 | && let Some(f) = &tpl_factors { |
| 1292 | let res = deltaq_res.unwrap_or(4); |
| 1293 | let off = |libaom: Option<f64>| -> Vec<i32> { |
| 1294 | (0..sb_cols * _sb_rows) |
| 1295 | .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx)) |
| 1296 | .collect() |
| 1297 | }; |
| 1298 | let strength = dq_tpl_strength(dq_level); |
| 1299 | let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0)))); |
| 1300 | let coded = match (deltaq_res.is_some(), strength) { |
| 1301 | (false, _) => "none".to_string(), |
| 1302 | (true, None) => "ours".to_string(), |
| 1303 | (true, Some(k)) => format!("libaom k={k}"), |
| 1304 | }; |
| 1305 | eprintln!( |
| 1306 | "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}", |
| 1307 | sb_cols * _sb_rows, |
| 1308 | r_frame.unwrap_or(f64::NAN), |
| 1309 | dq_summary(&ours), |
| 1310 | dq_summary(&aom), |
| 1311 | ); |
| 1312 | } |
| 1313 | if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) { |
| 1314 | header.delta.q_present = true; |
| 1315 | header.delta.q_res = res.trailing_zeros() as u8; |
| 1316 | } |
| 1317 | |
| 1318 | |
| 1319 | let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0); |
| 1320 | if let Some(g) = &sb_q { |
| 1321 | let mut levels: Vec<u8> = g.clone(); |
| 1322 | levels.sort_unstable(); |
| 1323 | levels.dedup(); |
| 1324 | DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed); |
| 1325 | } |
| 1326 | let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize); |
| 1327 | |
| 1328 | let (tile_cols_log2, tile_rows_log2) = armed_tiles(); |
| 1329 | let layout = crate::tile::TileLayout::new( |
| 1330 | header.mi_cols, |
| 1331 | header.mi_rows, |
| 1332 | tile_cols_log2, |
| 1333 | tile_rows_log2, |
| 1334 | ); |
| 1335 | header.tile_info = tile_info_of(&layout, 1); |
| 1336 | let header_tile_info = header.tile_info.clone(); |
| 1337 | |
| 1338 | |
| 1339 | |
| 1340 | |
| 1341 | let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows]; |
| 1342 | |
| 1343 | |
| 1344 | |
| 1345 | |
| 1346 | |
| 1347 | |
| 1348 | |
| 1349 | let (frame_width, frame_height) = (picture.width, picture.height); |
| 1350 | let search_tile = |index: usize, |
| 1351 | fctx: &crate::decode::FrameCtx| |
| 1352 | -> Result<(Vec<(usize, Quadrant)>, TilePixels)> { |
| 1353 | |
| 1354 | |
| 1355 | |
| 1356 | |
| 1357 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 1358 | crate::tile::arm_high_precision_mv(hp_mv); |
| 1359 | crate::tile::arm_pricing_cdfs(start_cdfs, screen); |
| 1360 | let rect = layout.rect(index); |
| 1361 | let mut luma = fresh_plane( |
| 1362 | &picture_y8, |
| 1363 | frame_width, |
| 1364 | frame_height, |
| 1365 | true_width, |
| 1366 | true_height, |
| 1367 | ); |
| 1368 | let mut chroma = [ |
| 1369 | fresh_plane( |
| 1370 | &picture_u8, |
| 1371 | frame_width / 2, |
| 1372 | frame_height / 2, |
| 1373 | true_width / 2, |
| 1374 | true_height / 2, |
| 1375 | ), |
| 1376 | fresh_plane( |
| 1377 | &picture_v8, |
| 1378 | frame_width / 2, |
| 1379 | frame_height / 2, |
| 1380 | true_width / 2, |
| 1381 | true_height / 2, |
| 1382 | ), |
| 1383 | ]; |
| 1384 | clip_planes_to_tile(&mut luma, &mut chroma, rect); |
| 1385 | let mut grid = MiGrid::new(mi_cols, mi_rows); |
| 1386 | grid.set_sign_bias(sign_bias); |
| 1387 | |
| 1388 | |
| 1389 | let mut obmc_refs: [Option<&Picture>; 8] = [None; 8]; |
| 1390 | obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference); |
| 1391 | obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2; |
| 1392 | obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden; |
| 1393 | obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref; |
| 1394 | grid.set_tile_bounds( |
| 1395 | rect.mi_row0 as usize, |
| 1396 | rect.mi_col0 as usize, |
| 1397 | rect.mi_row1 as usize, |
| 1398 | rect.mi_col1 as usize, |
| 1399 | ); |
| 1400 | let mut blocks: Vec<(usize, Quadrant)> = Vec::new(); |
| 1401 | |
| 1402 | |
| 1403 | |
| 1404 | |
| 1405 | |
| 1406 | |
| 1407 | |
| 1408 | let sb128_search = sb128_on(); |
| 1409 | let root_step = if sb128_search { 2 } else { 1 }; |
| 1410 | let mut roots: Vec<(usize, usize)> = Vec::new(); |
| 1411 | { |
| 1412 | let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize); |
| 1413 | let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize); |
| 1414 | let mut r = r0; |
| 1415 | while r < r1 { |
| 1416 | let mut c = c0; |
| 1417 | while c < c1 { |
| 1418 | roots.push((r, c)); |
| 1419 | c += root_step; |
| 1420 | } |
| 1421 | r += root_step; |
| 1422 | } |
| 1423 | } |
| 1424 | for (root_r, root_c) in roots { |
| 1425 | |
| 1426 | let cells: Vec<(usize, usize)> = if sb128_search { |
| 1427 | [(0, 0), (0, 1), (1, 0), (1, 1)] |
| 1428 | .into_iter() |
| 1429 | .map(|(dr, dc)| (root_r + dr, root_c + dc)) |
| 1430 | .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize) |
| 1431 | .collect() |
| 1432 | } else { |
| 1433 | vec![(root_r, root_c)] |
| 1434 | }; |
| 1435 | |
| 1436 | |
| 1437 | let mark128 = blocks.len(); |
| 1438 | let mut root_cost = 0.0f64; |
| 1439 | |
| 1440 | |
| 1441 | let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 1442 | if header.reference_select && b128_compound() && !screen && sb128_search { |
| 1443 | [ |
| 1444 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 1445 | (crate::mvstack::ALTREF_FRAME, altref), |
| 1446 | ] |
| 1447 | .into_iter() |
| 1448 | .filter_map(|(r, pic)| { |
| 1449 | pic.map(|p| { |
| 1450 | ( |
| 1451 | r, |
| 1452 | p, |
| 1453 | crate::mvstack::find_mv_stack_compound( |
| 1454 | &grid, |
| 1455 | root_r * 16, |
| 1456 | root_c * 16, |
| 1457 | 32, |
| 1458 | 32, |
| 1459 | (crate::mvstack::LAST_FRAME, r), |
| 1460 | mi_cols, |
| 1461 | mi_rows, |
| 1462 | grid.sign_bias_table(), |
| 1463 | &[(0, 0); 7], |
| 1464 | None, |
| 1465 | ), |
| 1466 | ) |
| 1467 | }) |
| 1468 | }) |
| 1469 | .collect() |
| 1470 | } else { |
| 1471 | Vec::new() |
| 1472 | }; |
| 1473 | let root128 = (sb128_search && b128_root() && cells.len() == 4) |
| 1474 | .then(|| { |
| 1475 | search_root_128( |
| 1476 | &mut luma, |
| 1477 | &mut chroma, |
| 1478 | &grid, |
| 1479 | (root_r, root_c), |
| 1480 | (rows, cols), |
| 1481 | (header.mi_cols, header.mi_rows), |
| 1482 | search, |
| 1483 | &tpl_factors, |
| 1484 | sb_q.as_ref(), |
| 1485 | sb_cols, |
| 1486 | tpl_cells_x, |
| 1487 | base_q_idx, |
| 1488 | dq_res, |
| 1489 | reference, |
| 1490 | &root_compound, |
| 1491 | fctx, |
| 1492 | ) |
| 1493 | }) |
| 1494 | .flatten(); |
| 1495 | |
| 1496 | |
| 1497 | |
| 1498 | let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed); |
| 1499 | let root_rect = (sb128_search && b128_rect() && cells.len() == 4) |
| 1500 | .then(|| { |
| 1501 | let mut best: Option<(bool, _)> = None; |
| 1502 | for horz in [true, false] { |
| 1503 | if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 { |
| 1504 | continue; |
| 1505 | } |
| 1506 | let Some(found) = search_root_128_rect( |
| 1507 | &mut luma, |
| 1508 | &mut chroma, |
| 1509 | &mut grid, |
| 1510 | (root_r, root_c), |
| 1511 | (rows, cols), |
| 1512 | (header.mi_cols, header.mi_rows), |
| 1513 | search, |
| 1514 | &tpl_factors, |
| 1515 | sb_q.as_ref(), |
| 1516 | sb_cols, |
| 1517 | tpl_cells_x, |
| 1518 | base_q_idx, |
| 1519 | dq_res, |
| 1520 | reference, |
| 1521 | &root_compound, |
| 1522 | horz, |
| 1523 | fctx, |
| 1524 | ) else { |
| 1525 | continue; |
| 1526 | }; |
| 1527 | if best |
| 1528 | .as_ref() |
| 1529 | .is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0) |
| 1530 | { |
| 1531 | best = Some((horz, found)); |
| 1532 | } |
| 1533 | } |
| 1534 | best |
| 1535 | }) |
| 1536 | .flatten(); |
| 1537 | |
| 1538 | |
| 1539 | |
| 1540 | let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed); |
| 1541 | let root_ab = (sb128_search |
| 1542 | && (b128_ab() || forced_ab != 0) |
| 1543 | && cells.len() == 4 |
| 1544 | && forced_rect == 0) |
| 1545 | .then(|| { |
| 1546 | let mut best: Option<(usize, _)> = None; |
| 1547 | for symbol in 4..=7usize { |
| 1548 | if forced_ab != 0 && usize::from(forced_ab) != symbol { |
| 1549 | continue; |
| 1550 | } |
| 1551 | let Some(found) = search_root_128_ab( |
| 1552 | &mut luma, |
| 1553 | &mut chroma, |
| 1554 | &mut grid, |
| 1555 | (root_r, root_c), |
| 1556 | (rows, cols), |
| 1557 | (header.mi_cols, header.mi_rows), |
| 1558 | search, |
| 1559 | &tpl_factors, |
| 1560 | sb_q.as_ref(), |
| 1561 | sb_cols, |
| 1562 | tpl_cells_x, |
| 1563 | base_q_idx, |
| 1564 | reference, |
| 1565 | &root_compound, |
| 1566 | symbol, |
| 1567 | fctx, |
| 1568 | ) else { |
| 1569 | continue; |
| 1570 | }; |
| 1571 | if best |
| 1572 | .as_ref() |
| 1573 | .is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0) |
| 1574 | { |
| 1575 | best = Some((symbol, found)); |
| 1576 | } |
| 1577 | } |
| 1578 | best |
| 1579 | }) |
| 1580 | .flatten(); |
| 1581 | for (sb_r, sb_c) in cells { |
| 1582 | |
| 1583 | |
| 1584 | |
| 1585 | |
| 1586 | |
| 1587 | |
| 1588 | |
| 1589 | let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK); |
| 1590 | let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols |
| 1591 | && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows |
| 1592 | && x64 + SUPERBLOCK <= luma.true_width |
| 1593 | && y64 + SUPERBLOCK <= luma.true_height; |
| 1594 | let edge_inside = b64_edge() |
| 1595 | && crate::tile::has_half( |
| 1596 | sb_c as u32 * crate::tile::SB_MI, |
| 1597 | crate::tile::SB_MI, |
| 1598 | header.mi_cols, |
| 1599 | ) |
| 1600 | && crate::tile::has_half( |
| 1601 | sb_r as u32 * crate::tile::SB_MI, |
| 1602 | crate::tile::SB_MI, |
| 1603 | header.mi_rows, |
| 1604 | ); |
| 1605 | let sb64_legal = b64_root() |
| 1606 | && sb_r * 2 + 1 < rows |
| 1607 | && sb_c * 2 + 1 < cols |
| 1608 | && (whole_inside || edge_inside); |
| 1609 | |
| 1610 | |
| 1611 | |
| 1612 | |
| 1613 | let sb_search = match &tpl_factors { |
| 1614 | |
| 1615 | |
| 1616 | |
| 1617 | Some(_) if sb_q.is_some() => sb_q_search( |
| 1618 | sb_q.as_ref().expect("armed"), |
| 1619 | sb_cols, |
| 1620 | base_q_idx, |
| 1621 | (sb_r, sb_c), |
| 1622 | search, |
| 1623 | ), |
| 1624 | Some(f) if sb64_legal => { |
| 1625 | let mean = (0..16) |
| 1626 | .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4]) |
| 1627 | .sum::<f64>() |
| 1628 | / 16.0; |
| 1629 | Search { |
| 1630 | lambda: search.lambda * mean, |
| 1631 | ..search |
| 1632 | } |
| 1633 | } |
| 1634 | _ => search, |
| 1635 | }; |
| 1636 | let mark = blocks.len(); |
| 1637 | let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None; |
| 1638 | let mut sb_cost = 0.0f64; |
| 1639 | if sb64_legal { |
| 1640 | let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); |
| 1641 | let (mi_row, mi_col) = (sb_r * 16, sb_c * 16); |
| 1642 | let stack = |
| 1643 | find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows); |
| 1644 | |
| 1645 | |
| 1646 | |
| 1647 | |
| 1648 | |
| 1649 | |
| 1650 | |
| 1651 | |
| 1652 | |
| 1653 | let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 1654 | if header.reference_select && b64_compound() && !screen { |
| 1655 | [ |
| 1656 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 1657 | (crate::mvstack::ALTREF_FRAME, altref), |
| 1658 | ] |
| 1659 | .into_iter() |
| 1660 | .filter_map(|(r, pic)| { |
| 1661 | pic.map(|p| { |
| 1662 | ( |
| 1663 | r, |
| 1664 | p, |
| 1665 | crate::mvstack::find_mv_stack_compound( |
| 1666 | &grid, |
| 1667 | mi_row, |
| 1668 | mi_col, |
| 1669 | 16, |
| 1670 | 16, |
| 1671 | (crate::mvstack::LAST_FRAME, r), |
| 1672 | mi_cols, |
| 1673 | mi_rows, |
| 1674 | grid.sign_bias_table(), |
| 1675 | &[(0, 0); 7], |
| 1676 | None, |
| 1677 | ), |
| 1678 | ) |
| 1679 | }) |
| 1680 | }) |
| 1681 | .collect() |
| 1682 | } else { |
| 1683 | Vec::new() |
| 1684 | }; |
| 1685 | if let Some((cost, block)) = search_skip_64( |
| 1686 | &mut luma, |
| 1687 | &mut chroma, |
| 1688 | (x64, y64), |
| 1689 | (SUPERBLOCK, SUPERBLOCK), |
| 1690 | &sb_search, |
| 1691 | b64_residual() && !screen, |
| 1692 | reference, |
| 1693 | &stack, |
| 1694 | &sb_compound, |
| 1695 | fctx, |
| 1696 | ) { |
| 1697 | let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); |
| 1698 | restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base); |
| 1699 | let cost = cost |
| 1700 | + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false); |
| 1701 | sb64 = Some((cost, block, after)); |
| 1702 | } |
| 1703 | } |
| 1704 | |
| 1705 | |
| 1706 | |
| 1707 | |
| 1708 | let early64 = sb64.as_ref().is_some_and(|(c, _, _)| { |
| 1709 | split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, sb_search.lambda) |
| 1710 | }); |
| 1711 | for quadrant in 0..if early64 { 0 } else { 4 } { |
| 1712 | let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 1713 | |
| 1714 | |
| 1715 | |
| 1716 | |
| 1717 | |
| 1718 | |
| 1719 | |
| 1720 | let search = match &tpl_factors { |
| 1721 | |
| 1722 | |
| 1723 | |
| 1724 | |
| 1725 | |
| 1726 | Some(_) if sb_q.is_some() => sb_q_search( |
| 1727 | sb_q.as_ref().expect("armed"), |
| 1728 | sb_cols, |
| 1729 | base_q_idx, |
| 1730 | (sb_r, sb_c), |
| 1731 | search, |
| 1732 | ), |
| 1733 | Some(f) => { |
| 1734 | let mean = (0..4) |
| 1735 | .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2]) |
| 1736 | .sum::<f64>() |
| 1737 | / 4.0; |
| 1738 | Search { |
| 1739 | lambda: search.lambda * mean, |
| 1740 | ..search |
| 1741 | } |
| 1742 | } |
| 1743 | None => search, |
| 1744 | }; |
| 1745 | |
| 1746 | |
| 1747 | if r32 >= rows || c32 >= cols { |
| 1748 | continue; |
| 1749 | } |
| 1750 | |
| 1751 | |
| 1752 | |
| 1753 | |
| 1754 | |
| 1755 | |
| 1756 | |
| 1757 | |
| 1758 | let (has_cols32, has_rows32) = ( |
| 1759 | crate::tile::has_half( |
| 1760 | c32 as u32 * crate::tile::BLOCK_MI, |
| 1761 | crate::tile::BLOCK_MI, |
| 1762 | header.mi_cols, |
| 1763 | ), |
| 1764 | crate::tile::has_half( |
| 1765 | r32 as u32 * crate::tile::BLOCK_MI, |
| 1766 | crate::tile::BLOCK_MI, |
| 1767 | header.mi_rows, |
| 1768 | ), |
| 1769 | ); |
| 1770 | if has_cols32 && has_rows32 { |
| 1771 | let (x, y) = (c32 * BLOCK, r32 * BLOCK); |
| 1772 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); |
| 1773 | let stack = find_mv_stack( |
| 1774 | &grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows, |
| 1775 | ); |
| 1776 | let extra_stacks: Vec<(i8, &Picture, MvStack)> = [ |
| 1777 | (crate::mvstack::LAST2_FRAME, last2), |
| 1778 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 1779 | (crate::mvstack::ALTREF_FRAME, altref), |
| 1780 | ] |
| 1781 | .into_iter() |
| 1782 | .filter_map(|(r, pic)| { |
| 1783 | pic.map(|p| { |
| 1784 | ( |
| 1785 | r, |
| 1786 | p, |
| 1787 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows), |
| 1788 | ) |
| 1789 | }) |
| 1790 | }) |
| 1791 | .collect(); |
| 1792 | let extra: Vec<(i8, &Picture, &MvStack)> = |
| 1793 | extra_stacks.iter().map(|(r, p, st)| (*r, *p, st)).collect(); |
| 1794 | |
| 1795 | |
| 1796 | |
| 1797 | |
| 1798 | let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 1799 | if header.reference_select { |
| 1800 | extra_stacks |
| 1801 | .iter() |
| 1802 | .map(|&(r, p, _)| { |
| 1803 | ( |
| 1804 | r, |
| 1805 | p, |
| 1806 | crate::mvstack::find_mv_stack_compound( |
| 1807 | &grid, |
| 1808 | mi_row, |
| 1809 | mi_col, |
| 1810 | 8, |
| 1811 | 8, |
| 1812 | (crate::mvstack::LAST_FRAME, r), |
| 1813 | mi_cols, |
| 1814 | mi_rows, |
| 1815 | grid.sign_bias_table(), |
| 1816 | &[(0, 0); 7], |
| 1817 | None, |
| 1818 | ), |
| 1819 | ) |
| 1820 | }) |
| 1821 | .collect() |
| 1822 | } else { |
| 1823 | Vec::new() |
| 1824 | }; |
| 1825 | |
| 1826 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 1827 | let (block, mut cost_whole) = search_inter_block( |
| 1828 | &mut luma, |
| 1829 | &mut chroma, |
| 1830 | (x, y), |
| 1831 | &search, |
| 1832 | &mode_bits_table, |
| 1833 | reference, |
| 1834 | &stack, |
| 1835 | &extra, |
| 1836 | &compound, |
| 1837 | &grid, |
| 1838 | (mi_row, mi_col), |
| 1839 | (mi_rows, mi_cols), |
| 1840 | fctx, |
| 1841 | ); |
| 1842 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 1843 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 1844 | |
| 1845 | |
| 1846 | |
| 1847 | |
| 1848 | |
| 1849 | |
| 1850 | |
| 1851 | |
| 1852 | |
| 1853 | |
| 1854 | |
| 1855 | |
| 1856 | |
| 1857 | let leaf_positions: Vec<(usize, usize)> = |
| 1858 | (0..4).map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)).collect(); |
| 1859 | let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| { |
| 1860 | crate::tile::has_half( |
| 1861 | sc as u32 * crate::tile::SUB_MI, |
| 1862 | crate::tile::SUB_MI, |
| 1863 | header.mi_cols, |
| 1864 | ) && crate::tile::has_half( |
| 1865 | sr as u32 * crate::tile::SUB_MI, |
| 1866 | crate::tile::SUB_MI, |
| 1867 | header.mi_rows, |
| 1868 | ) |
| 1869 | }); |
| 1870 | |
| 1871 | |
| 1872 | let breakout = split_breakout_coeffs(); |
| 1873 | let split = (!block.skip |
| 1874 | && !split_rd_breakout(cost_whole, BLOCK, search.lambda) |
| 1875 | && (breakout == 0 || block.luma.len() > 4 * breakout) |
| 1876 | && leaves_legal |
| 1877 | && split_inter_blocks()) |
| 1878 | .then(|| { |
| 1879 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); |
| 1880 | let mut cost = search.lambda * partition_bits(BLOCK, true); |
| 1881 | let mut leaves = Vec::with_capacity(4); |
| 1882 | for &(sr, sc) in &leaf_positions { |
| 1883 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 1884 | let (lx, ly) = (sc * SUB, sr * SUB); |
| 1885 | let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 1886 | let stack = find_mv_stack( |
| 1887 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 1888 | ); |
| 1889 | let cstacks = leaf_compound_stacks( |
| 1890 | &grid, |
| 1891 | mi_row, |
| 1892 | mi_col, |
| 1893 | 4, |
| 1894 | 4, |
| 1895 | mi_cols, |
| 1896 | mi_rows, |
| 1897 | header.reference_select, |
| 1898 | golden, |
| 1899 | altref, |
| 1900 | ); |
| 1901 | let (leaf, leaf_cost) = code_square_inter( |
| 1902 | &mut luma, |
| 1903 | &mut chroma, |
| 1904 | (lx, ly), |
| 1905 | SUB, |
| 1906 | &search, |
| 1907 | &mode_bits_table, |
| 1908 | reference, |
| 1909 | &stack, |
| 1910 | &cstacks, |
| 1911 | &grid, |
| 1912 | (mi_row, mi_col), |
| 1913 | (mi_rows, mi_cols), |
| 1914 | &obmc_refs, |
| 1915 | fctx, |
| 1916 | ); |
| 1917 | let leaf_cost = |
| 1918 | leaf_cost + search.lambda * partition_bits(SUB, false); |
| 1919 | let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 1920 | |
| 1921 | |
| 1922 | |
| 1923 | |
| 1924 | |
| 1925 | |
| 1926 | let eight = (!leaf.skip |
| 1927 | && !split_rd_breakout(leaf_cost, SUB, search.lambda) |
| 1928 | && (breakout == 0 || leaf.luma.len() > breakout) |
| 1929 | && split_inter_8() |
| 1930 | |
| 1931 | |
| 1932 | |
| 1933 | |
| 1934 | |
| 1935 | |
| 1936 | |
| 1937 | |
| 1938 | |
| 1939 | && (search.arf_leaf8 || arfmode_hit_and_no())) |
| 1940 | .then(|| { |
| 1941 | restore(&mut luma, &mut chroma, (lx, ly), SUB, &leaf_base); |
| 1942 | let mut cost8 = search.lambda |
| 1943 | * (partition_bits(SUB, true) |
| 1944 | + 4.0 * partition_bits(8, false)); |
| 1945 | let mut eight = Vec::with_capacity(4); |
| 1946 | for i in 0..4 { |
| 1947 | let (mr, mc) = (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2); |
| 1948 | let stack8 = find_mv_stack( |
| 1949 | &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 1950 | ); |
| 1951 | let cstacks8: Vec<( |
| 1952 | i8, |
| 1953 | &Picture, |
| 1954 | crate::mvstack::CompoundMvStack, |
| 1955 | )> = if header.reference_select && leaf_compound() { |
| 1956 | [ |
| 1957 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 1958 | (crate::mvstack::ALTREF_FRAME, altref), |
| 1959 | ] |
| 1960 | .into_iter() |
| 1961 | .filter_map(|(r, pic)| { |
| 1962 | pic.map(|p| { |
| 1963 | ( |
| 1964 | r, |
| 1965 | p, |
| 1966 | crate::mvstack::find_mv_stack_compound( |
| 1967 | &grid, |
| 1968 | mr, |
| 1969 | mc, |
| 1970 | 2, |
| 1971 | 2, |
| 1972 | (crate::mvstack::LAST_FRAME, r), |
| 1973 | mi_cols, |
| 1974 | mi_rows, |
| 1975 | grid.sign_bias_table(), |
| 1976 | &[(0, 0); 7], |
| 1977 | None, |
| 1978 | ), |
| 1979 | ) |
| 1980 | }) |
| 1981 | }) |
| 1982 | .collect() |
| 1983 | } else { |
| 1984 | Vec::new() |
| 1985 | }; |
| 1986 | let (leaf8, cost) = code_square_inter( |
| 1987 | &mut luma, |
| 1988 | &mut chroma, |
| 1989 | (lx + (i % 2) * 8, ly + (i / 2) * 8), |
| 1990 | 8, |
| 1991 | &search, |
| 1992 | &mode_bits_table, |
| 1993 | reference, |
| 1994 | &stack8, |
| 1995 | &cstacks8, |
| 1996 | &grid, |
| 1997 | (mr, mc), |
| 1998 | (mi_rows, mi_cols), |
| 1999 | &obmc_refs, |
| 2000 | fctx, |
| 2001 | ); |
| 2002 | cost8 += cost; |
| 2003 | record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip); |
| 2004 | eight.push(leaf8); |
| 2005 | } |
| 2006 | (eight, cost8) |
| 2007 | }); |
| 2008 | match eight { |
| 2009 | Some((eight, cost8)) if cost8 < leaf_cost => { |
| 2010 | partition_hit(3); |
| 2011 | cost += cost8; |
| 2012 | leaves.push(BlockCoeffs { |
| 2013 | eight: Some(eight), |
| 2014 | ..BlockCoeffs::default() |
| 2015 | }); |
| 2016 | continue; |
| 2017 | } |
| 2018 | Some(_) => { |
| 2019 | restore(&mut luma, &mut chroma, (lx, ly), SUB, &after_leaf) |
| 2020 | } |
| 2021 | None => {} |
| 2022 | } |
| 2023 | partition_hit(2); |
| 2024 | cost += leaf_cost; |
| 2025 | record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip); |
| 2026 | leaves.push(leaf); |
| 2027 | } |
| 2028 | (leaves, cost) |
| 2029 | }); |
| 2030 | if let Some((leaves, cost)) = split { |
| 2031 | if cost < cost_whole { |
| 2032 | |
| 2033 | |
| 2034 | |
| 2035 | partition_hit(1); |
| 2036 | sb_cost += cost; |
| 2037 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 2038 | continue; |
| 2039 | } |
| 2040 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); |
| 2041 | } |
| 2042 | partition_hit(0); |
| 2043 | sb_cost += cost_whole; |
| 2044 | record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip); |
| 2045 | blocks.push((r32 * cols + c32, Quadrant::Whole(block))); |
| 2046 | } else { |
| 2047 | |
| 2048 | |
| 2049 | let sub_positions: Vec<(usize, usize)> = (0..4) |
| 2050 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 2051 | .filter(|&(sr, sc)| { |
| 2052 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 2053 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 2054 | }) |
| 2055 | .collect(); |
| 2056 | |
| 2057 | |
| 2058 | |
| 2059 | |
| 2060 | |
| 2061 | |
| 2062 | |
| 2063 | |
| 2064 | |
| 2065 | let mut leaves = Vec::with_capacity(sub_positions.len()); |
| 2066 | for (sr, sc) in sub_positions { |
| 2067 | let (has_cols16, has_rows16) = ( |
| 2068 | crate::tile::has_half( |
| 2069 | sc as u32 * crate::tile::SUB_MI, |
| 2070 | crate::tile::SUB_MI, |
| 2071 | header.mi_cols, |
| 2072 | ), |
| 2073 | crate::tile::has_half( |
| 2074 | sr as u32 * crate::tile::SUB_MI, |
| 2075 | crate::tile::SUB_MI, |
| 2076 | header.mi_rows, |
| 2077 | ), |
| 2078 | ); |
| 2079 | if has_cols16 && has_rows16 { |
| 2080 | let (x, y) = (sc * SUB, sr * SUB); |
| 2081 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 2082 | let stack = find_mv_stack( |
| 2083 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 2084 | ); |
| 2085 | let cstacks = leaf_compound_stacks( |
| 2086 | &grid, |
| 2087 | mi_row, |
| 2088 | mi_col, |
| 2089 | 4, |
| 2090 | 4, |
| 2091 | mi_cols, |
| 2092 | mi_rows, |
| 2093 | header.reference_select, |
| 2094 | golden, |
| 2095 | altref, |
| 2096 | ); |
| 2097 | let (block, _) = code_square_inter( |
| 2098 | &mut luma, |
| 2099 | &mut chroma, |
| 2100 | (x, y), |
| 2101 | SUB, |
| 2102 | &search, |
| 2103 | &mode_bits_table, |
| 2104 | reference, |
| 2105 | &stack, |
| 2106 | &cstacks, |
| 2107 | &grid, |
| 2108 | (mi_row, mi_col), |
| 2109 | (mi_rows, mi_cols), |
| 2110 | &obmc_refs, |
| 2111 | fctx, |
| 2112 | ); |
| 2113 | |
| 2114 | |
| 2115 | |
| 2116 | |
| 2117 | |
| 2118 | |
| 2119 | record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip); |
| 2120 | leaves.push(block); |
| 2121 | } else { |
| 2122 | let (x_sub, y_sub) = (sc * SUB, sr * SUB); |
| 2123 | let (mi_row0, mi_col0) = (sr * 4, sc * 4); |
| 2124 | let mut eight = Vec::with_capacity(2); |
| 2125 | for i in 0..4 { |
| 2126 | let leaf_x = x_sub + (i % 2) * 8; |
| 2127 | let leaf_y = y_sub + (i / 2) * 8; |
| 2128 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 2129 | continue; |
| 2130 | } |
| 2131 | let (mi_row, mi_col) = |
| 2132 | (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); |
| 2133 | let stack = find_mv_stack( |
| 2134 | &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 2135 | ); |
| 2136 | let cstacks = leaf_compound_stacks( |
| 2137 | &grid, |
| 2138 | mi_row, |
| 2139 | mi_col, |
| 2140 | 2, |
| 2141 | 2, |
| 2142 | mi_cols, |
| 2143 | mi_rows, |
| 2144 | header.reference_select, |
| 2145 | golden, |
| 2146 | altref, |
| 2147 | ); |
| 2148 | let (leaf, _) = code_square_inter( |
| 2149 | &mut luma, |
| 2150 | &mut chroma, |
| 2151 | (leaf_x, leaf_y), |
| 2152 | 8, |
| 2153 | &search, |
| 2154 | &mode_bits_table, |
| 2155 | reference, |
| 2156 | &stack, |
| 2157 | &cstacks, |
| 2158 | &grid, |
| 2159 | (mi_row, mi_col), |
| 2160 | (mi_rows, mi_cols), |
| 2161 | &obmc_refs, |
| 2162 | fctx, |
| 2163 | ); |
| 2164 | |
| 2165 | |
| 2166 | record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip); |
| 2167 | eight.push(leaf); |
| 2168 | } |
| 2169 | leaves.push(BlockCoeffs { |
| 2170 | eight: Some(eight), |
| 2171 | ..BlockCoeffs::default() |
| 2172 | }); |
| 2173 | } |
| 2174 | } |
| 2175 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 2176 | } |
| 2177 | } |
| 2178 | |
| 2179 | if let Some((cost64, block, after)) = sb64 |
| 2180 | && (early64 |
| 2181 | || cost64 |
| 2182 | < sb_cost |
| 2183 | + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true)) |
| 2184 | { |
| 2185 | B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2186 | if block.inter.is_some_and(|i| i.ref1.is_some()) { |
| 2187 | B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2188 | } |
| 2189 | if !whole_inside { |
| 2190 | B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2191 | } |
| 2192 | blocks.truncate(mark); |
| 2193 | restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after); |
| 2194 | |
| 2195 | |
| 2196 | |
| 2197 | record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip); |
| 2198 | blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block))); |
| 2199 | for q in 1..4 { |
| 2200 | let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2); |
| 2201 | blocks.push((r32 * cols + c32, Quadrant::Covered)); |
| 2202 | } |
| 2203 | root_cost += cost64; |
| 2204 | } else { |
| 2205 | root_cost += sb_cost; |
| 2206 | } |
| 2207 | } |
| 2208 | |
| 2209 | |
| 2210 | |
| 2211 | |
| 2212 | |
| 2213 | |
| 2214 | |
| 2215 | let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new(); |
| 2216 | if let Some((c, l, b, a)) = root128 { |
| 2217 | cands.push((c, l, 0, vec![b], a)); |
| 2218 | } |
| 2219 | if let Some((horz, (c, l, halves, a))) = root_rect { |
| 2220 | cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a)); |
| 2221 | } |
| 2222 | if let Some((symbol, (c, l, pieces, a))) = root_ab { |
| 2223 | cands.push((c, l, symbol, pieces.to_vec(), a)); |
| 2224 | } |
| 2225 | |
| 2226 | |
| 2227 | if forced_rect != 0 { |
| 2228 | cands.retain(|c| c.2 == 1 || c.2 == 2); |
| 2229 | } |
| 2230 | if forced_ab != 0 { |
| 2231 | cands.retain(|c| c.2 == usize::from(forced_ab)); |
| 2232 | } |
| 2233 | cands.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 2234 | |
| 2235 | |
| 2236 | |
| 2237 | |
| 2238 | |
| 2239 | |
| 2240 | |
| 2241 | |
| 2242 | let split_dq = |
| 2243 | delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c)); |
| 2244 | if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next() |
| 2245 | && (cost128 |
| 2246 | < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq) |
| 2247 | |
| 2248 | |
| 2249 | || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed) |
| 2250 | || forced_rect != 0 |
| 2251 | || forced_ab != 0) |
| 2252 | { |
| 2253 | let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); |
| 2254 | blocks.truncate(mark128); |
| 2255 | restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after); |
| 2256 | let at = (root_r * 2) * cols + root_c * 2; |
| 2257 | match shape { |
| 2258 | 0 => { |
| 2259 | B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2260 | let block = halves.into_iter().next().expect("the NONE arm's block"); |
| 2261 | record_mi( |
| 2262 | &mut grid, |
| 2263 | root_r * 16, |
| 2264 | root_c * 16, |
| 2265 | 32, |
| 2266 | block.inter, |
| 2267 | block.skip, |
| 2268 | ); |
| 2269 | blocks.push((at, Quadrant::Whole128(block))); |
| 2270 | } |
| 2271 | |
| 2272 | |
| 2273 | symbol @ 4..=7 => { |
| 2274 | B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2275 | for (((mr, mc), (w, h)), piece) in |
| 2276 | ab128_pieces(symbol, (root_r * 16, root_c * 16)) |
| 2277 | .iter() |
| 2278 | .zip(&halves) |
| 2279 | { |
| 2280 | record_mi_rect( |
| 2281 | &mut grid, |
| 2282 | *mr, |
| 2283 | *mc, |
| 2284 | (w / 4, h / 4), |
| 2285 | piece.inter, |
| 2286 | piece.skip, |
| 2287 | ); |
| 2288 | } |
| 2289 | blocks.push((at, Quadrant::Ab128(symbol as u8, halves))); |
| 2290 | } |
| 2291 | symbol => { |
| 2292 | let horz = symbol == 1; |
| 2293 | if horz { |
| 2294 | B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2295 | } else { |
| 2296 | B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2297 | } |
| 2298 | let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) }; |
| 2299 | for (i, half) in halves.iter().enumerate() { |
| 2300 | let (mr, mc) = if horz { |
| 2301 | (root_r * 16 + i * 16, root_c * 16) |
| 2302 | } else { |
| 2303 | (root_r * 16, root_c * 16 + i * 16) |
| 2304 | }; |
| 2305 | record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip); |
| 2306 | } |
| 2307 | blocks.push((at, Quadrant::Rect128(horz, halves))); |
| 2308 | } |
| 2309 | } |
| 2310 | for q in 1..16 { |
| 2311 | let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4); |
| 2312 | blocks.push((r32 * cols + c32, Quadrant::Covered)); |
| 2313 | } |
| 2314 | } |
| 2315 | } |
| 2316 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 2317 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 2318 | let luma_rect = (x0, y0, x1, y1); |
| 2319 | let chroma_rect = (x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2)); |
| 2320 | let pixels = TilePixels { |
| 2321 | luma_rect, |
| 2322 | chroma_rect, |
| 2323 | luma: take_rect(&luma.reconstruction, frame_width, luma_rect), |
| 2324 | chroma: [ |
| 2325 | take_rect(&chroma[0].reconstruction, frame_width / 2, chroma_rect), |
| 2326 | take_rect(&chroma[1].reconstruction, frame_width / 2, chroma_rect), |
| 2327 | ], |
| 2328 | }; |
| 2329 | Ok((blocks, pixels)) |
| 2330 | }; |
| 2331 | |
| 2332 | |
| 2333 | let mut searched_blocks = Vec::new(); |
| 2334 | for (tile_blocks, pixels) in search_tiles(layout.count(), fctx, search_tile)? { |
| 2335 | put_rect(&mut luma.reconstruction, frame_width, pixels.luma_rect, &pixels.luma); |
| 2336 | for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) { |
| 2337 | put_rect(&mut plane.reconstruction, frame_width / 2, pixels.chroma_rect, bytes); |
| 2338 | } |
| 2339 | searched_blocks.push(tile_blocks); |
| 2340 | } |
| 2341 | for (at, quadrant) in searched_blocks.into_iter().flatten() { |
| 2342 | blocks[at] = quadrant; |
| 2343 | } |
| 2344 | |
| 2345 | |
| 2346 | |
| 2347 | |
| 2348 | |
| 2349 | if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") { |
| 2350 | let whole = blocks |
| 2351 | .iter() |
| 2352 | .filter(|q| matches!(q, Quadrant::Whole128(_))) |
| 2353 | .count(); |
| 2354 | let roots = blocks |
| 2355 | .iter() |
| 2356 | .filter(|q| !matches!(q, Quadrant::Covered)) |
| 2357 | .count(); |
| 2358 | |
| 2359 | |
| 2360 | |
| 2361 | let residual = blocks |
| 2362 | .iter() |
| 2363 | .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip)) |
| 2364 | .count(); |
| 2365 | |
| 2366 | |
| 2367 | let compound = blocks |
| 2368 | .iter() |
| 2369 | .filter( |
| 2370 | |q| matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some())), |
| 2371 | ) |
| 2372 | .count(); |
| 2373 | |
| 2374 | |
| 2375 | let horz = blocks |
| 2376 | .iter() |
| 2377 | .filter(|q| matches!(q, Quadrant::Rect128(true, _))) |
| 2378 | .count(); |
| 2379 | let vert = blocks |
| 2380 | .iter() |
| 2381 | .filter(|q| matches!(q, Quadrant::Rect128(false, _))) |
| 2382 | .count(); |
| 2383 | let rect_compound = blocks |
| 2384 | .iter() |
| 2385 | .filter(|q| { |
| 2386 | matches!(q, Quadrant::Rect128(_, hs) |
| 2387 | if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some()))) |
| 2388 | }) |
| 2389 | .count(); |
| 2390 | |
| 2391 | |
| 2392 | |
| 2393 | let ab: [usize; 4] = std::array::from_fn(|i| { |
| 2394 | blocks |
| 2395 | .iter() |
| 2396 | .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4)) |
| 2397 | .count() |
| 2398 | }); |
| 2399 | eprintln!( |
| 2400 | "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \ |
| 2401 | {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \ |
| 2402 | compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \ |
| 2403 | {roots} coded blocks ({:.1}% of the frame's area at 128)", |
| 2404 | ab[0], |
| 2405 | ab[1], |
| 2406 | ab[2], |
| 2407 | ab[3], |
| 2408 | 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64 |
| 2409 | / blocks.len().max(1) as f64, |
| 2410 | ); |
| 2411 | } |
| 2412 | let modes = blocks |
| 2413 | .iter() |
| 2414 | .flat_map(Quadrant::blocks) |
| 2415 | .map(|b| b.mode) |
| 2416 | .collect::<Vec<_>>(); |
| 2417 | let inter_block_share = blocks |
| 2418 | .iter() |
| 2419 | .flat_map(Quadrant::blocks) |
| 2420 | .filter(|b| b.inter.is_some()) |
| 2421 | .count() as f64 |
| 2422 | / modes.len() as f64; |
| 2423 | for block in blocks.iter().flat_map(Quadrant::blocks) { |
| 2424 | if let Some(info) = block.inter { |
| 2425 | let r = (info.ref_frame as usize).min(7); |
| 2426 | REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2427 | } |
| 2428 | } |
| 2429 | #[cfg(test)] |
| 2430 | record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); |
| 2431 | |
| 2432 | |
| 2433 | |
| 2434 | |
| 2435 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 2436 | let mut cdfs = start_cdfs |
| 2437 | .cloned() |
| 2438 | .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); |
| 2439 | |
| 2440 | |
| 2441 | |
| 2442 | cdfs.reduced_tx_set = header.reduced_tx_set; |
| 2443 | let start_cdfs = CdfSnapshot(cdfs); |
| 2444 | let reference_select_bit = header.reference_select; |
| 2445 | let switchable_motion_mode = header.is_motion_mode_switchable; |
| 2446 | let warped_motion = header.allow_warped_motion; |
| 2447 | let order_hint_bits = seq.order_hint_bits; |
| 2448 | let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32; |
| 2449 | let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32; |
| 2450 | |
| 2451 | |
| 2452 | |
| 2453 | let store_tile = layout.largest_tile(); |
| 2454 | let end_cdfs = std::cell::RefCell::new(None); |
| 2455 | |
| 2456 | |
| 2457 | let code_tiles = |bits: u8, |
| 2458 | sb_cols: usize, |
| 2459 | cdef_grid: &[u8], |
| 2460 | units: &[Option<crate::restoration::WienerInfo>]| |
| 2461 | -> Result<Vec<Vec<u8>>> { |
| 2462 | let (out, stored) = write_tiles(layout.count(), store_tile, |index| { |
| 2463 | crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); |
| 2464 | crate::tile::arm_delta_q( |
| 2465 | deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0), |
| 2466 | sb_cols, |
| 2467 | sb_q.clone().unwrap_or_default(), |
| 2468 | base_q_idx, |
| 2469 | ); |
| 2470 | crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec()); |
| 2471 | crate::tile::arm_sb128(sb128_on()); |
| 2472 | crate::tile::arm_sign_bias(sign_bias); |
| 2473 | |
| 2474 | crate::tile::arm_reference_select(reference_select_bit); |
| 2475 | crate::tile::arm_motion_mode(switchable_motion_mode); |
| 2476 | crate::tile::arm_warped_motion(warped_motion); |
| 2477 | crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); |
| 2478 | crate::tile::arm_high_precision_mv(hp_mv); |
| 2479 | crate::tile::arm_screen(screen); |
| 2480 | crate::tile::arm_frame_mi_dims(frame_mi_dims); |
| 2481 | crate::tile::arm_filter_intra(filter_intra_on()); |
| 2482 | let mut cdfs = start_cdfs.0.clone(); |
| 2483 | crate::tile::arm_pricing_cdfs(Some(&cdfs), screen); |
| 2484 | |
| 2485 | |
| 2486 | |
| 2487 | |
| 2488 | let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); |
| 2489 | mv_grid.set_sign_bias(sign_bias); |
| 2490 | let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs( |
| 2491 | mi_cols, |
| 2492 | mi_rows, |
| 2493 | base_q_idx, |
| 2494 | &blocks, |
| 2495 | tx_select, |
| 2496 | &mut cdfs, |
| 2497 | layout.rect(index), |
| 2498 | &mut mv_grid, |
| 2499 | )?; |
| 2500 | Ok((bytes, Some(cdfs))) |
| 2501 | })?; |
| 2502 | if let Some(cdfs) = stored { |
| 2503 | *end_cdfs.borrow_mut() = Some(cdfs); |
| 2504 | } |
| 2505 | Ok(out) |
| 2506 | }; |
| 2507 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| 2508 | |
| 2509 | |
| 2510 | |
| 2511 | |
| 2512 | |
| 2513 | |
| 2514 | |
| 2515 | |
| 2516 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 2517 | let trial_ref = if (reference.width, reference.height) == (fw, fh) { |
| 2518 | reference.clone() |
| 2519 | } else { |
| 2520 | Picture { |
| 2521 | width: fw, |
| 2522 | height: fh, |
| 2523 | y: crop_plane(&reference.y, reference.width, fw, fh), |
| 2524 | u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2), |
| 2525 | v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), |
| 2526 | } |
| 2527 | }; |
| 2528 | |
| 2529 | |
| 2530 | |
| 2531 | let trial_golden = golden.map(|g| { |
| 2532 | if (g.width, g.height) == (fw, fh) { |
| 2533 | g.clone() |
| 2534 | } else { |
| 2535 | Picture { |
| 2536 | width: fw, |
| 2537 | height: fh, |
| 2538 | y: crop_plane(&g.y, g.width, fw, fh), |
| 2539 | u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2), |
| 2540 | v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2), |
| 2541 | } |
| 2542 | } |
| 2543 | }); |
| 2544 | let trial_altref = altref.map(|a| { |
| 2545 | if (a.width, a.height) == (fw, fh) { |
| 2546 | a.clone() |
| 2547 | } else { |
| 2548 | Picture { |
| 2549 | width: fw, |
| 2550 | height: fh, |
| 2551 | y: crop_plane(&a.y, a.width, fw, fh), |
| 2552 | u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2), |
| 2553 | v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2), |
| 2554 | } |
| 2555 | } |
| 2556 | }); |
| 2557 | let trial_last2 = last2.map(|l| { |
| 2558 | if (l.width, l.height) == (fw, fh) { |
| 2559 | l.clone() |
| 2560 | } else { |
| 2561 | Picture { |
| 2562 | width: fw, |
| 2563 | height: fh, |
| 2564 | y: crop_plane(&l.y, l.width, fw, fh), |
| 2565 | u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2), |
| 2566 | v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2), |
| 2567 | } |
| 2568 | } |
| 2569 | }); |
| 2570 | let mut refs: [Option<&Picture>; 8] = [None; 8]; |
| 2571 | refs[1] = Some(&trial_ref); |
| 2572 | refs[2] = trial_last2.as_ref(); |
| 2573 | refs[4] = trial_golden.as_ref(); |
| 2574 | refs[7] = trial_altref.as_ref(); |
| 2575 | let refpix = crate::decode::RefPix::ready(refs); |
| 2576 | |
| 2577 | |
| 2578 | |
| 2579 | |
| 2580 | if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { |
| 2581 | let sse: u64 = luma |
| 2582 | .reconstruction |
| 2583 | .chunks(luma.width) |
| 2584 | .take(luma.true_height) |
| 2585 | .zip(picture_y8.chunks(luma.width)) |
| 2586 | .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width])) |
| 2587 | .map(|(&r, &s)| { |
| 2588 | let d = i64::from(r) - i64::from(s); |
| 2589 | (d * d) as u64 |
| 2590 | }) |
| 2591 | .sum(); |
| 2592 | eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}"); |
| 2593 | } |
| 2594 | let post = |luma: &Plane<'_>, tag: &str| { |
| 2595 | if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { |
| 2596 | return; |
| 2597 | } |
| 2598 | let sse: u64 = luma |
| 2599 | .reconstruction |
| 2600 | .chunks(luma.width) |
| 2601 | .take(luma.true_height) |
| 2602 | .zip(picture_y8.chunks(luma.width)) |
| 2603 | .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width])) |
| 2604 | .map(|(&r, &s)| { |
| 2605 | let d = i64::from(r) - i64::from(s); |
| 2606 | (d * d) as u64 |
| 2607 | }) |
| 2608 | .sum(); |
| 2609 | eprintln!("{tag} q={base_q_idx} luma sse={sse}"); |
| 2610 | }; |
| 2611 | pick_and_apply_filters( |
| 2612 | &mut header, |
| 2613 | &mut luma, |
| 2614 | &mut chroma, |
| 2615 | [&picture_y8, &picture_u8, &picture_v8], |
| 2616 | |
| 2617 | |
| 2618 | |
| 2619 | |
| 2620 | true, |
| 2621 | &mut tiles, |
| 2622 | search.lambda, |
| 2623 | fctx, |
| 2624 | &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows), |
| 2625 | |
| 2626 | |
| 2627 | |
| 2628 | |
| 2629 | |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |
| 2630 | |lf, cdef, h, tiles: &[Vec<u8>], lr| { |
| 2631 | let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); |
| 2632 | crate::decode::decode_inter_frame_tiles_lr( |
| 2633 | &payloads, |
| 2634 | &header_tile_info, |
| 2635 | h.mi_cols, |
| 2636 | h.mi_rows, |
| 2637 | base_q_idx, |
| 2638 | h.frame_width, |
| 2639 | h.frame_height, |
| 2640 | &refpix, |
| 2641 | cdef, |
| 2642 | lf, |
| 2643 | h.allow_high_precision_mv, |
| 2644 | h.force_integer_mv, |
| 2645 | Some(fctx.interp_filter.get()), |
| 2646 | seq.enable_dual_filter, |
| 2647 | h.reference_select, |
| 2648 | |
| 2649 | |
| 2650 | h.reduced_tx_set, |
| 2651 | tx_select, |
| 2652 | lr, |
| 2653 | |
| 2654 | |
| 2655 | |
| 2656 | Some(start_cdfs.0.clone()), |
| 2657 | sign_bias, |
| 2658 | h.allow_screen_content_tools, |
| 2659 | switchable_motion_mode, |
| 2660 | h.allow_warped_motion, |
| 2661 | seq.enable_filter_intra, |
| 2662 | |
| 2663 | |
| 2664 | |
| 2665 | h.delta, |
| 2666 | fctx, |
| 2667 | ) |
| 2668 | }, |
| 2669 | )?; |
| 2670 | post(&luma, "EC_POSTFILTER"); |
| 2671 | let mut cdfs = end_cdfs |
| 2672 | .into_inner() |
| 2673 | .unwrap_or_else(|| start_cdfs.0.clone()); |
| 2674 | cdfs.reset_counts(); |
| 2675 | let next_cdfs = CdfSnapshot(cdfs); |
| 2676 | let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); |
| 2677 | header.tile_info.tile_size_bytes = tile_size_bytes; |
| 2678 | let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); |
| 2679 | let mut stream = temporal_delimiter(); |
| 2680 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 2681 | |
| 2682 | let [u, v] = chroma; |
| 2683 | Ok(Encoded { |
| 2684 | stream, |
| 2685 | modes, |
| 2686 | inter_block_share, |
| 2687 | reconstruction: Picture { |
| 2688 | width: luma.width, |
| 2689 | height: luma.height, |
| 2690 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 2691 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 2692 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 2693 | }, |
| 2694 | tile, |
| 2695 | mi_cols: header.mi_cols, |
| 2696 | mi_rows: header.mi_rows, |
| 2697 | base_q_idx, |
| 2698 | tx_select, |
| 2699 | switchable_motion_mode, |
| 2700 | screen, |
| 2701 | reduced_tx_set: header.reduced_tx_set, |
| 2702 | start_cdfs: Box::new(start_cdfs), |
| 2703 | next_cdfs: Box::new(next_cdfs), |
| 2704 | loop_filter: header.loop_filter, |
| 2705 | cdef: header.cdef, |
| 2706 | loop_restoration: header.loop_restoration, |
| 2707 | |
| 2708 | |
| 2709 | allow_intrabc: false, |
| 2710 | delta: header.delta, |
| 2711 | }) |
| 2712 | } |
| 2713 | |
| 2714 | |
| 2715 | |
| 2716 | |
| 2717 | |
| 2718 | #[derive(Clone, Debug)] |
| 2719 | pub struct EncodedSequence { |
| 2720 | |
| 2721 | |
| 2722 | |
| 2723 | |
| 2724 | pub stream: Vec<u8>, |
| 2725 | |
| 2726 | |
| 2727 | |
| 2728 | |
| 2729 | pub frames: Vec<Encoded>, |
| 2730 | |
| 2731 | |
| 2732 | |
| 2733 | pub coding_order: Vec<usize>, |
| 2734 | } |
| 2735 | |
| 2736 | |
| 2737 | |
| 2738 | |
| 2739 | |
| 2740 | |
| 2741 | |
| 2742 | |
| 2743 | |
| 2744 | |
| 2745 | |
| 2746 | |
| 2747 | |
| 2748 | pub(crate) fn encode_sequence_with_ctx( |
| 2749 | pictures: &[Picture], |
| 2750 | base_q_idx: u8, |
| 2751 | deadzone: f64, |
| 2752 | fctx: &crate::decode::FrameCtx, |
| 2753 | ) -> Result<EncodedSequence> { |
| 2754 | let Some((first, rest)) = pictures.split_first() else { |
| 2755 | return Err(Error::unsupported( |
| 2756 | "AV1 encode", |
| 2757 | "a sequence needs at least one picture", |
| 2758 | )); |
| 2759 | }; |
| 2760 | first.check_even()?; |
| 2761 | let render = (first.width, first.height); |
| 2762 | |
| 2763 | |
| 2764 | |
| 2765 | |
| 2766 | |
| 2767 | |
| 2768 | |
| 2769 | |
| 2770 | |
| 2771 | |
| 2772 | |
| 2773 | |
| 2774 | |
| 2775 | |
| 2776 | |
| 2777 | let pyramid = crate::encoder::Pyramid::from_env() |
| 2778 | .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON) |
| 2779 | .filter(|_| !picture_is_screen(first)); |
| 2780 | LAST_SEQ_PYRAMID.with(|c| c.set(pyramid)); |
| 2781 | if let Some(pyramid) = pyramid { |
| 2782 | for picture in rest { |
| 2783 | picture.check_even()?; |
| 2784 | if (picture.width, picture.height) != render { |
| 2785 | return Err(Error::unsupported( |
| 2786 | "AV1 encode", |
| 2787 | "every picture in a sequence must be the same size as the first", |
| 2788 | )); |
| 2789 | } |
| 2790 | } |
| 2791 | return crate::encoder::Av1Encoder::encode_sequence_pyramid( |
| 2792 | pictures, |
| 2793 | base_q_idx, |
| 2794 | pyramid, |
| 2795 | armed_tiles(), |
| 2796 | ); |
| 2797 | } |
| 2798 | |
| 2799 | |
| 2800 | |
| 2801 | |
| 2802 | |
| 2803 | let key = encode_key_frame_inner( |
| 2804 | &first.padded_to(SUPERBLOCK), |
| 2805 | base_q_idx, |
| 2806 | deadzone, |
| 2807 | &KEY_FRAME_MODES, |
| 2808 | split_blocks(), |
| 2809 | render, |
| 2810 | unspecified_color_config(), |
| 2811 | fctx, |
| 2812 | )?; |
| 2813 | let mut stream = key.stream.clone(); |
| 2814 | |
| 2815 | |
| 2816 | |
| 2817 | let golden = key.reconstruction.clone(); |
| 2818 | |
| 2819 | |
| 2820 | let mut prev2: Option<Picture> = None; |
| 2821 | let mut carried = key.next_cdfs.clone(); |
| 2822 | let mut reference = key.reconstruction.clone(); |
| 2823 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 2824 | for (i, picture) in rest.iter().enumerate() { |
| 2825 | picture.check_even()?; |
| 2826 | |
| 2827 | |
| 2828 | |
| 2829 | |
| 2830 | let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..] |
| 2831 | .iter() |
| 2832 | .take(tpl_depth() - 1) |
| 2833 | .map(|n| n.padded_to(SUPERBLOCK)) |
| 2834 | .collect(); |
| 2835 | if (picture.width, picture.height) != render { |
| 2836 | return Err(Error::unsupported( |
| 2837 | "AV1 encode", |
| 2838 | "every picture in a sequence must be the same size as the first", |
| 2839 | )); |
| 2840 | } |
| 2841 | let order_hint = (i + 1) as u32; |
| 2842 | let inter = encode_inter_frame( |
| 2843 | &picture.padded_to(SUPERBLOCK), |
| 2844 | &reference, |
| 2845 | base_q_idx, |
| 2846 | deadzone, |
| 2847 | order_hint, |
| 2848 | flat_order_hints(order_hint, 0, prev2.is_some()), |
| 2849 | render, |
| 2850 | Some(&carried.0), |
| 2851 | Some(&golden), |
| 2852 | prev2.as_ref(), |
| 2853 | None, |
| 2854 | fctx, |
| 2855 | None, |
| 2856 | &lookahead, |
| 2857 | )?; |
| 2858 | stream.extend_from_slice(&inter.stream); |
| 2859 | carried = inter.next_cdfs.clone(); |
| 2860 | prev2 = Some(std::mem::replace( |
| 2861 | &mut reference, |
| 2862 | inter.reconstruction.clone(), |
| 2863 | )); |
| 2864 | frames.push(crop_encoded(&inter, render.0, render.1)); |
| 2865 | } |
| 2866 | Ok(EncodedSequence { |
| 2867 | stream, |
| 2868 | coding_order: (0..frames.len()).collect(), |
| 2869 | frames, |
| 2870 | }) |
| 2871 | } |