| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig}; |
| 17 | use ec_core::{Error, Result}; |
| 18 | |
| 19 | use crate::encode::{ |
| 20 | Encoded, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, encode_key_frame_inner, |
| 21 | split_blocks, |
| 22 | }; |
| 23 | use crate::intra::KEY_FRAME_MODES; |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | const DEADZONE: f64 = 0.5; |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 38 | pub enum Colour { |
| 39 | |
| 40 | |
| 41 | |
| 42 | #[default] |
| 43 | Bt709Limited, |
| 44 | |
| 45 | |
| 46 | Bt601Limited, |
| 47 | |
| 48 | |
| 49 | Unspecified, |
| 50 | } |
| 51 | |
| 52 | impl Colour { |
| 53 | fn color_config(self) -> ColorConfig { |
| 54 | let (color_primaries, transfer_characteristics, matrix_coefficients) = match self { |
| 55 | Colour::Bt709Limited => (1, 1, 1), |
| 56 | Colour::Bt601Limited => (6, 6, 6), |
| 57 | Colour::Unspecified => (2, 2, 2), |
| 58 | }; |
| 59 | ColorConfig { |
| 60 | bit_depth: 8, |
| 61 | mono_chrome: false, |
| 62 | num_planes: 3, |
| 63 | color_primaries, |
| 64 | transfer_characteristics, |
| 65 | matrix_coefficients, |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | color_range: false, |
| 71 | subsampling_x: 1, |
| 72 | subsampling_y: 1, |
| 73 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 74 | separate_uv_delta_q: false, |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 87 | pub enum RateTarget { |
| 88 | |
| 89 | |
| 90 | QIndex(u8), |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | Quality(u8), |
| 99 | |
| 100 | |
| 101 | |
| 102 | BytesPerFrame(u32), |
| 103 | } |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | fn quality_to_q_idx(quality: u8) -> u8 { |
| 111 | let quality = f64::from(quality.min(100)); |
| 112 | (240.0 - quality * 2.0).round() as u8 |
| 113 | } |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | #[derive(Debug, Clone, Copy)] |
| 125 | struct RateLoop { |
| 126 | target_bytes: u32, |
| 127 | q: f64, |
| 128 | } |
| 129 | |
| 130 | impl RateLoop { |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | const STEP_CLAMP: f64 = 12.0; |
| 136 | |
| 137 | |
| 138 | const GAIN: f64 = 1.0 / 0.0154; |
| 139 | |
| 140 | fn new(target_bytes: u32, start_q: f64) -> Self { |
| 141 | Self { |
| 142 | target_bytes, |
| 143 | q: start_q, |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | fn q_idx(&self) -> u8 { |
| 148 | self.q.round().clamp(0.0, 255.0) as u8 |
| 149 | } |
| 150 | |
| 151 | |
| 152 | fn update(&mut self, actual_bytes: usize) { |
| 153 | if self.target_bytes == 0 || actual_bytes == 0 { |
| 154 | return; |
| 155 | } |
| 156 | let ratio = actual_bytes as f64 / f64::from(self.target_bytes); |
| 157 | let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP); |
| 158 | self.q = (self.q + step).clamp(0.0, 255.0); |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | #[derive(Debug, Clone, Copy)] |
| 173 | pub struct EncoderConfig { |
| 174 | |
| 175 | pub width: usize, |
| 176 | |
| 177 | pub height: usize, |
| 178 | |
| 179 | pub base_q_idx: u8, |
| 180 | |
| 181 | |
| 182 | |
| 183 | pub gop: usize, |
| 184 | |
| 185 | pub colour: Colour, |
| 186 | } |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | #[derive(Debug, Clone)] |
| 192 | pub struct Packet { |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | pub data: Vec<u8>, |
| 200 | |
| 201 | pub key: bool, |
| 202 | |
| 203 | |
| 204 | pub order: u64, |
| 205 | } |
| 206 | |
| 207 | |
| 208 | |
| 209 | #[derive(Debug)] |
| 210 | pub struct Av1Encoder { |
| 211 | config: EncoderConfig, |
| 212 | color_config: ColorConfig, |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | reference: Option<Picture>, |
| 218 | next_index: u64, |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | rate_loop: Option<RateLoop>, |
| 224 | } |
| 225 | |
| 226 | impl Av1Encoder { |
| 227 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | pub fn new(config: EncoderConfig) -> Result<Self> { |
| 233 | if config.gop == 0 { |
| 234 | return Err(Error::unsupported("AV1 encode", "gop must be at least 1")); |
| 235 | } |
| 236 | |
| 237 | |
| 238 | |
| 239 | Picture::grey(config.width, config.height).check_even()?; |
| 240 | Ok(Self { |
| 241 | color_config: config.colour.color_config(), |
| 242 | config, |
| 243 | reference: None, |
| 244 | next_index: 0, |
| 245 | rate_loop: None, |
| 246 | }) |
| 247 | } |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> { |
| 256 | let rate_loop = match rate { |
| 257 | RateTarget::QIndex(q) => { |
| 258 | config.base_q_idx = q; |
| 259 | None |
| 260 | } |
| 261 | RateTarget::Quality(quality) => { |
| 262 | config.base_q_idx = quality_to_q_idx(quality); |
| 263 | None |
| 264 | } |
| 265 | RateTarget::BytesPerFrame(target_bytes) => { |
| 266 | Some(RateLoop::new(target_bytes, f64::from(config.base_q_idx))) |
| 267 | } |
| 268 | }; |
| 269 | let mut encoder = Self::new(config)?; |
| 270 | encoder.rate_loop = rate_loop; |
| 271 | Ok(encoder) |
| 272 | } |
| 273 | |
| 274 | |
| 275 | |
| 276 | #[must_use] |
| 277 | pub fn coded_size(&self) -> (usize, usize) { |
| 278 | ( |
| 279 | self.config.width.next_multiple_of(SUPERBLOCK), |
| 280 | self.config.height.next_multiple_of(SUPERBLOCK), |
| 281 | ) |
| 282 | } |
| 283 | |
| 284 | |
| 285 | |
| 286 | #[must_use] |
| 287 | pub fn display_size(&self) -> (usize, usize) { |
| 288 | (self.config.width, self.config.height) |
| 289 | } |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | pub fn encode(&mut self, picture: &Picture) -> Result<Packet> { |
| 301 | if (picture.width, picture.height) != (self.config.width, self.config.height) { |
| 302 | return Err(Error::unsupported( |
| 303 | "AV1 encode", |
| 304 | format!( |
| 305 | "picture is {}x{}, encoder is {}x{}", |
| 306 | picture.width, picture.height, self.config.width, self.config.height |
| 307 | ), |
| 308 | )); |
| 309 | } |
| 310 | let render = (self.config.width, self.config.height); |
| 311 | let padded = picture.padded_to(SUPERBLOCK); |
| 312 | let is_key = self.next_index % self.config.gop as u64 == 0; |
| 313 | let order = self.next_index; |
| 314 | let base_q_idx = self |
| 315 | .rate_loop |
| 316 | .as_ref() |
| 317 | .map_or(self.config.base_q_idx, RateLoop::q_idx); |
| 318 | |
| 319 | let encoded: Encoded = if is_key { |
| 320 | encode_key_frame_inner( |
| 321 | &padded, |
| 322 | base_q_idx, |
| 323 | DEADZONE, |
| 324 | &KEY_FRAME_MODES, |
| 325 | split_blocks(), |
| 326 | render, |
| 327 | self.color_config, |
| 328 | )? |
| 329 | } else { |
| 330 | let reference = self.reference.as_ref().ok_or_else(|| { |
| 331 | Error::unsupported( |
| 332 | "AV1 encode", |
| 333 | "an inter frame needs a previous reconstruction", |
| 334 | ) |
| 335 | })?; |
| 336 | encode_inter_frame( |
| 337 | &padded, |
| 338 | reference, |
| 339 | base_q_idx, |
| 340 | DEADZONE, |
| 341 | order as u32, |
| 342 | render, |
| 343 | )? |
| 344 | }; |
| 345 | |
| 346 | self.reference = Some(encoded.reconstruction.clone()); |
| 347 | self.next_index += 1; |
| 348 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 349 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 350 | rate_loop.update(cropped.stream.len()); |
| 351 | } |
| 352 | Ok(Packet { |
| 353 | data: cropped.stream, |
| 354 | key: is_key, |
| 355 | order, |
| 356 | }) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | #[cfg(test)] |
| 361 | mod tests { |
| 362 | use super::*; |
| 363 | use std::process::{Command, Stdio}; |
| 364 | |
| 365 | fn have_ffmpeg() -> bool { |
| 366 | Command::new("ffmpeg") |
| 367 | .arg("-version") |
| 368 | .stdout(Stdio::null()) |
| 369 | .stderr(Stdio::null()) |
| 370 | .status() |
| 371 | .is_ok_and(|s| s.success()) |
| 372 | } |
| 373 | |
| 374 | fn test_card(width: usize, height: usize, shift: usize) -> Picture { |
| 375 | let mut picture = Picture::grey(width, height); |
| 376 | for y in 0..height { |
| 377 | for x in 0..width { |
| 378 | let sx = (x + shift) % width; |
| 379 | picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u8; |
| 380 | } |
| 381 | } |
| 382 | for y in 0..height / 2 { |
| 383 | for x in 0..width / 2 { |
| 384 | let i = y * (width / 2) + x; |
| 385 | picture.u[i] = ((100 + shift * 4) % 256) as u8; |
| 386 | picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u8; |
| 387 | } |
| 388 | } |
| 389 | picture |
| 390 | } |
| 391 | |
| 392 | |
| 393 | |
| 394 | fn concat(packets: &[Packet]) -> Vec<u8> { |
| 395 | packets.iter().flat_map(|p| p.data.clone()).collect() |
| 396 | } |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | #[test] |
| 402 | fn one_in_one_out() { |
| 403 | let config = EncoderConfig { |
| 404 | width: 64, |
| 405 | height: 64, |
| 406 | base_q_idx: 100, |
| 407 | gop: 2, |
| 408 | colour: Colour::Bt709Limited, |
| 409 | }; |
| 410 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 411 | for t in 0..5u64 { |
| 412 | let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); |
| 413 | assert!(!packet.data.is_empty(), "picture {t}: empty packet"); |
| 414 | assert_eq!(packet.order, t, "picture {t}: order"); |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | #[test] |
| 422 | fn gop_cadence_is_honored() { |
| 423 | let config = EncoderConfig { |
| 424 | width: 64, |
| 425 | height: 64, |
| 426 | base_q_idx: 100, |
| 427 | gop: 3, |
| 428 | colour: Colour::Unspecified, |
| 429 | }; |
| 430 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 431 | let keys: Vec<bool> = (0..7) |
| 432 | .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key) |
| 433 | .collect(); |
| 434 | assert_eq!(keys, vec![true, false, false, true, false, false, true]); |
| 435 | } |
| 436 | |
| 437 | fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { |
| 438 | let path = std::env::temp_dir().join(format!( |
| 439 | "ec-av1-facade-probe-{}-{}.obu", |
| 440 | std::process::id(), |
| 441 | std::ptr::addr_of!(stream) as usize |
| 442 | )); |
| 443 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 444 | let out = Command::new("ffprobe") |
| 445 | .args([ |
| 446 | "-v", |
| 447 | "error", |
| 448 | "-f", |
| 449 | "obu", |
| 450 | "-select_streams", |
| 451 | "v:0", |
| 452 | "-show_entries", |
| 453 | "frame=key_frame,width,height", |
| 454 | "-of", |
| 455 | "csv=p=0", |
| 456 | ]) |
| 457 | .arg(&path) |
| 458 | .output() |
| 459 | .expect("ffprobe failed to run"); |
| 460 | let _ = std::fs::remove_file(&path); |
| 461 | assert!( |
| 462 | out.status.success(), |
| 463 | "ffprobe refused the stream: {}", |
| 464 | String::from_utf8_lossy(&out.stderr) |
| 465 | ); |
| 466 | String::from_utf8_lossy(&out.stdout) |
| 467 | .lines() |
| 468 | .map(|line| { |
| 469 | let mut f = line.trim().split(','); |
| 470 | let key: u32 = f.next().unwrap().parse().unwrap(); |
| 471 | let width: u32 = f.next().unwrap().parse().unwrap(); |
| 472 | let height: u32 = f.next().unwrap().parse().unwrap(); |
| 473 | (key == 1, width, height) |
| 474 | }) |
| 475 | .collect() |
| 476 | } |
| 477 | |
| 478 | fn ffprobe_colour(stream: &[u8]) -> String { |
| 479 | let path = std::env::temp_dir().join(format!( |
| 480 | "ec-av1-facade-colour-probe-{}-{}.obu", |
| 481 | std::process::id(), |
| 482 | std::ptr::addr_of!(stream) as usize |
| 483 | )); |
| 484 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 485 | let out = Command::new("ffprobe") |
| 486 | .args([ |
| 487 | "-v", |
| 488 | "error", |
| 489 | "-f", |
| 490 | "obu", |
| 491 | "-select_streams", |
| 492 | "v:0", |
| 493 | "-show_entries", |
| 494 | "stream=color_primaries,color_transfer,color_space,color_range", |
| 495 | "-of", |
| 496 | "csv=p=0", |
| 497 | ]) |
| 498 | .arg(&path) |
| 499 | .output() |
| 500 | .expect("ffprobe failed to run"); |
| 501 | let _ = std::fs::remove_file(&path); |
| 502 | assert!( |
| 503 | out.status.success(), |
| 504 | "ffprobe refused the stream: {}", |
| 505 | String::from_utf8_lossy(&out.stderr) |
| 506 | ); |
| 507 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 508 | } |
| 509 | |
| 510 | |
| 511 | |
| 512 | |
| 513 | |
| 514 | #[test] |
| 515 | fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { |
| 516 | if !have_ffmpeg() { |
| 517 | eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg"); |
| 518 | return; |
| 519 | } |
| 520 | let (width, height) = (96usize, 96usize); |
| 521 | let config = EncoderConfig { |
| 522 | width, |
| 523 | height, |
| 524 | base_q_idx: 120, |
| 525 | gop: 15, |
| 526 | colour: Colour::Bt709Limited, |
| 527 | }; |
| 528 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 529 | assert_eq!(enc.display_size(), (width, height)); |
| 530 | let (coded_w, coded_h) = enc.coded_size(); |
| 531 | assert_eq!( |
| 532 | (coded_w, coded_h), |
| 533 | ( |
| 534 | width.next_multiple_of(SUPERBLOCK), |
| 535 | height.next_multiple_of(SUPERBLOCK) |
| 536 | ) |
| 537 | ); |
| 538 | |
| 539 | let packets: Vec<Packet> = (0..30) |
| 540 | .map(|t| enc.encode(&test_card(width, height, t)).unwrap()) |
| 541 | .collect(); |
| 542 | let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect(); |
| 543 | assert_eq!( |
| 544 | packets.iter().map(|p| p.key).collect::<Vec<_>>(), |
| 545 | expect_key, |
| 546 | "facade's own key/inter flags" |
| 547 | ); |
| 548 | |
| 549 | let stream = concat(&packets); |
| 550 | let frames = ffprobe_frames(&stream); |
| 551 | assert_eq!(frames.len(), 30, "ffprobe frame count"); |
| 552 | for (t, (key, w, h)) in frames.iter().enumerate() { |
| 553 | assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); |
| 554 | assert_eq!( |
| 555 | (*w, *h), |
| 556 | (width as u32, height as u32), |
| 557 | "picture {t}: ffprobe reports the true (display) size, not the padded coded one" |
| 558 | ); |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | |
| 563 | |
| 564 | |
| 565 | |
| 566 | |
| 567 | |
| 568 | #[test] |
| 569 | fn bt709_limited_colour_is_reported_by_ffprobe() { |
| 570 | if !have_ffmpeg() { |
| 571 | eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 572 | return; |
| 573 | } |
| 574 | let config = EncoderConfig { |
| 575 | width: 64, |
| 576 | height: 64, |
| 577 | base_q_idx: 100, |
| 578 | gop: 4, |
| 579 | colour: Colour::Bt709Limited, |
| 580 | }; |
| 581 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 582 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 583 | let colour = ffprobe_colour(&packet.data); |
| 584 | assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); |
| 585 | } |
| 586 | |
| 587 | |
| 588 | |
| 589 | |
| 590 | #[test] |
| 591 | fn bt601_limited_colour_is_reported_by_ffprobe() { |
| 592 | if !have_ffmpeg() { |
| 593 | eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 594 | return; |
| 595 | } |
| 596 | let config = EncoderConfig { |
| 597 | width: 64, |
| 598 | height: 64, |
| 599 | base_q_idx: 100, |
| 600 | gop: 4, |
| 601 | colour: Colour::Bt601Limited, |
| 602 | }; |
| 603 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 604 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 605 | let colour = ffprobe_colour(&packet.data); |
| 606 | assert_eq!( |
| 607 | colour, "tv,smpte170m,smpte170m,smpte170m", |
| 608 | "ffprobe colour fields" |
| 609 | ); |
| 610 | } |
| 611 | |
| 612 | |
| 613 | |
| 614 | #[test] |
| 615 | fn geometry_mismatch_is_refused() { |
| 616 | let config = EncoderConfig { |
| 617 | width: 64, |
| 618 | height: 64, |
| 619 | base_q_idx: 100, |
| 620 | gop: 4, |
| 621 | colour: Colour::Bt709Limited, |
| 622 | }; |
| 623 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 624 | let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); |
| 625 | assert!(err.to_string().contains("64x64"), "{err}"); |
| 626 | } |
| 627 | |
| 628 | |
| 629 | #[test] |
| 630 | fn zero_gop_is_refused() { |
| 631 | let config = EncoderConfig { |
| 632 | width: 64, |
| 633 | height: 64, |
| 634 | base_q_idx: 100, |
| 635 | gop: 0, |
| 636 | colour: Colour::Bt709Limited, |
| 637 | }; |
| 638 | let err = Av1Encoder::new(config).unwrap_err(); |
| 639 | assert!(err.to_string().contains("gop"), "{err}"); |
| 640 | } |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | |
| 646 | |
| 647 | fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> { |
| 648 | if !have_ffmpeg() { |
| 649 | return None; |
| 650 | } |
| 651 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 652 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 653 | if !clip.exists() { |
| 654 | return None; |
| 655 | } |
| 656 | let out = Command::new("ffmpeg") |
| 657 | .args(["-v", "error", "-i", clip.to_str().unwrap()]) |
| 658 | .args(["-frames:v", &frames.to_string()]) |
| 659 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 660 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 661 | .output() |
| 662 | .expect("ffmpeg failed to run"); |
| 663 | assert!( |
| 664 | out.status.success(), |
| 665 | "{}", |
| 666 | String::from_utf8_lossy(&out.stderr) |
| 667 | ); |
| 668 | let (luma, chroma) = (width * height, width * height / 4); |
| 669 | let frame_len = luma + 2 * chroma; |
| 670 | assert_eq!( |
| 671 | out.stdout.len(), |
| 672 | frame_len * frames, |
| 673 | "expected {frames} 4:2:0 frames" |
| 674 | ); |
| 675 | Some( |
| 676 | (0..frames) |
| 677 | .map(|i| { |
| 678 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 679 | Picture { |
| 680 | width, |
| 681 | height, |
| 682 | y: bytes[..luma].to_vec(), |
| 683 | u: bytes[luma..luma + chroma].to_vec(), |
| 684 | v: bytes[luma + chroma..].to_vec(), |
| 685 | } |
| 686 | }) |
| 687 | .collect(), |
| 688 | ) |
| 689 | } |
| 690 | |
| 691 | |
| 692 | |
| 693 | |
| 694 | |
| 695 | #[test] |
| 696 | fn bytes_per_frame_target_settles_within_20_percent() { |
| 697 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 698 | eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture"); |
| 699 | return; |
| 700 | }; |
| 701 | let target_bytes = 4_000u32; |
| 702 | let config = EncoderConfig { |
| 703 | width: 640, |
| 704 | height: 384, |
| 705 | base_q_idx: 100, |
| 706 | gop: 24, |
| 707 | colour: Colour::Bt709Limited, |
| 708 | }; |
| 709 | let mut enc = |
| 710 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); |
| 711 | let sizes: Vec<usize> = pictures |
| 712 | .iter() |
| 713 | .map(|p| enc.encode(p).unwrap().data.len()) |
| 714 | .collect(); |
| 715 | |
| 716 | |
| 717 | let settled = &sizes[5..]; |
| 718 | let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64; |
| 719 | let low = f64::from(target_bytes) * 0.8; |
| 720 | let high = f64::from(target_bytes) * 1.2; |
| 721 | assert!( |
| 722 | mean >= low && mean <= high, |
| 723 | "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" |
| 724 | ); |
| 725 | } |
| 726 | |
| 727 | |
| 728 | |
| 729 | |
| 730 | |
| 731 | #[test] |
| 732 | fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { |
| 733 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 734 | eprintln!( |
| 735 | "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture" |
| 736 | ); |
| 737 | return; |
| 738 | }; |
| 739 | let config = EncoderConfig { |
| 740 | width: 640, |
| 741 | height: 384, |
| 742 | base_q_idx: 100, |
| 743 | gop: 24, |
| 744 | colour: Colour::Bt709Limited, |
| 745 | }; |
| 746 | let mut enc = |
| 747 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); |
| 748 | let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(); |
| 749 | for picture in &pictures { |
| 750 | enc.encode(picture).unwrap(); |
| 751 | let q = enc.rate_loop.as_ref().unwrap().q_idx(); |
| 752 | let step = (i32::from(q) - i32::from(prev_q)).abs(); |
| 753 | assert!( |
| 754 | f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, |
| 755 | "q stepped from {prev_q} to {q}, past the {} clamp", |
| 756 | RateLoop::STEP_CLAMP |
| 757 | ); |
| 758 | prev_q = q; |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | fn psnr(a: &[u8], b: &[u8]) -> f64 { |
| 763 | let squared: f64 = a |
| 764 | .iter() |
| 765 | .zip(b) |
| 766 | .map(|(&x, &y)| { |
| 767 | let d = f64::from(x) - f64::from(y); |
| 768 | d * d |
| 769 | }) |
| 770 | .sum(); |
| 771 | if squared == 0.0 { |
| 772 | return f64::INFINITY; |
| 773 | } |
| 774 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 775 | } |
| 776 | |
| 777 | |
| 778 | |
| 779 | |
| 780 | |
| 781 | fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> { |
| 782 | let path = std::env::temp_dir().join(format!( |
| 783 | "ec-av1-facade-rate-decode-{}-{}.obu", |
| 784 | std::process::id(), |
| 785 | std::ptr::addr_of!(stream) as usize |
| 786 | )); |
| 787 | std::fs::write(&path, stream).expect("writing the decode probe stream"); |
| 788 | let out = Command::new("ffmpeg") |
| 789 | .args(["-v", "error", "-f", "obu", "-i"]) |
| 790 | .arg(&path) |
| 791 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 792 | .output() |
| 793 | .expect("ffmpeg failed to run"); |
| 794 | let _ = std::fs::remove_file(&path); |
| 795 | assert!( |
| 796 | out.status.success(), |
| 797 | "{}", |
| 798 | String::from_utf8_lossy(&out.stderr) |
| 799 | ); |
| 800 | let (luma, chroma) = (width * height, width * height / 4); |
| 801 | let frame_len = luma + 2 * chroma; |
| 802 | out.stdout |
| 803 | .chunks_exact(frame_len) |
| 804 | .map(|f| f[..luma].to_vec()) |
| 805 | .collect() |
| 806 | } |
| 807 | |
| 808 | |
| 809 | |
| 810 | |
| 811 | #[test] |
| 812 | fn quality_target_is_monotone_in_bytes_and_psnr() { |
| 813 | if !have_ffmpeg() { |
| 814 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg"); |
| 815 | return; |
| 816 | } |
| 817 | let (width, height) = (640, 384); |
| 818 | let Some(pictures) = h264_clip_frames(width, height, 8) else { |
| 819 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture"); |
| 820 | return; |
| 821 | }; |
| 822 | let mut prev_bytes = 0usize; |
| 823 | let mut prev_psnr = 0.0f64; |
| 824 | for quality in [20u8, 50, 80] { |
| 825 | let config = EncoderConfig { |
| 826 | width, |
| 827 | height, |
| 828 | base_q_idx: 100, |
| 829 | gop: 8, |
| 830 | colour: Colour::Bt709Limited, |
| 831 | }; |
| 832 | let mut enc = |
| 833 | Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); |
| 834 | let mut stream = Vec::new(); |
| 835 | let mut total_bytes = 0usize; |
| 836 | for picture in &pictures { |
| 837 | let packet = enc.encode(picture).unwrap(); |
| 838 | total_bytes += packet.data.len(); |
| 839 | stream.extend_from_slice(&packet.data); |
| 840 | } |
| 841 | let decoded = ffmpeg_decode_luma(&stream, width, height); |
| 842 | assert_eq!( |
| 843 | decoded.len(), |
| 844 | pictures.len(), |
| 845 | "quality {quality}: dav1d frame count" |
| 846 | ); |
| 847 | let mean_psnr: f64 = decoded |
| 848 | .iter() |
| 849 | .zip(&pictures) |
| 850 | .map(|(d, p)| psnr(d, &p.y)) |
| 851 | .sum::<f64>() |
| 852 | / decoded.len() as f64; |
| 853 | assert!( |
| 854 | total_bytes >= prev_bytes, |
| 855 | "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" |
| 856 | ); |
| 857 | assert!( |
| 858 | mean_psnr >= prev_psnr - 0.01, |
| 859 | "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" |
| 860 | ); |
| 861 | prev_bytes = total_bytes; |
| 862 | prev_psnr = mean_psnr; |
| 863 | } |
| 864 | } |
| 865 | } |