| 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 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | fn have_ffmpeg() -> bool { |
| 373 | let present = Command::new("ffmpeg") |
| 374 | .arg("-version") |
| 375 | .stdout(Stdio::null()) |
| 376 | .stderr(Stdio::null()) |
| 377 | .status() |
| 378 | .is_ok_and(|s| s.success()); |
| 379 | assert!( |
| 380 | present |
| 381 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 382 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 383 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 384 | ); |
| 385 | present |
| 386 | } |
| 387 | |
| 388 | fn test_card(width: usize, height: usize, shift: usize) -> Picture { |
| 389 | let mut picture = Picture::grey(width, height); |
| 390 | for y in 0..height { |
| 391 | for x in 0..width { |
| 392 | let sx = (x + shift) % width; |
| 393 | picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16; |
| 394 | } |
| 395 | } |
| 396 | for y in 0..height / 2 { |
| 397 | for x in 0..width / 2 { |
| 398 | let i = y * (width / 2) + x; |
| 399 | picture.u[i] = ((100 + shift * 4) % 256) as u16; |
| 400 | picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16; |
| 401 | } |
| 402 | } |
| 403 | picture |
| 404 | } |
| 405 | |
| 406 | |
| 407 | |
| 408 | fn concat(packets: &[Packet]) -> Vec<u8> { |
| 409 | packets.iter().flat_map(|p| p.data.clone()).collect() |
| 410 | } |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | #[test] |
| 416 | fn one_in_one_out() { |
| 417 | let config = EncoderConfig { |
| 418 | width: 64, |
| 419 | height: 64, |
| 420 | base_q_idx: 100, |
| 421 | gop: 2, |
| 422 | colour: Colour::Bt709Limited, |
| 423 | }; |
| 424 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 425 | for t in 0..5u64 { |
| 426 | let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); |
| 427 | assert!(!packet.data.is_empty(), "picture {t}: empty packet"); |
| 428 | assert_eq!(packet.order, t, "picture {t}: order"); |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | |
| 433 | |
| 434 | |
| 435 | #[test] |
| 436 | fn gop_cadence_is_honored() { |
| 437 | let config = EncoderConfig { |
| 438 | width: 64, |
| 439 | height: 64, |
| 440 | base_q_idx: 100, |
| 441 | gop: 3, |
| 442 | colour: Colour::Unspecified, |
| 443 | }; |
| 444 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 445 | let keys: Vec<bool> = (0..7) |
| 446 | .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key) |
| 447 | .collect(); |
| 448 | assert_eq!(keys, vec![true, false, false, true, false, false, true]); |
| 449 | } |
| 450 | |
| 451 | fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { |
| 452 | let path = std::env::temp_dir().join(format!( |
| 453 | "ec-av1-facade-probe-{}-{}.obu", |
| 454 | std::process::id(), |
| 455 | std::ptr::addr_of!(stream) as usize |
| 456 | )); |
| 457 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 458 | let out = Command::new("ffprobe") |
| 459 | .args([ |
| 460 | "-v", |
| 461 | "error", |
| 462 | "-f", |
| 463 | "obu", |
| 464 | "-select_streams", |
| 465 | "v:0", |
| 466 | "-show_entries", |
| 467 | "frame=key_frame,width,height", |
| 468 | "-of", |
| 469 | "csv=p=0", |
| 470 | ]) |
| 471 | .arg(&path) |
| 472 | .output() |
| 473 | .expect("ffprobe failed to run"); |
| 474 | let _ = std::fs::remove_file(&path); |
| 475 | assert!( |
| 476 | out.status.success(), |
| 477 | "ffprobe refused the stream: {}", |
| 478 | String::from_utf8_lossy(&out.stderr) |
| 479 | ); |
| 480 | String::from_utf8_lossy(&out.stdout) |
| 481 | .lines() |
| 482 | .map(|line| { |
| 483 | let mut f = line.trim().split(','); |
| 484 | let key: u32 = f.next().unwrap().parse().unwrap(); |
| 485 | let width: u32 = f.next().unwrap().parse().unwrap(); |
| 486 | let height: u32 = f.next().unwrap().parse().unwrap(); |
| 487 | (key == 1, width, height) |
| 488 | }) |
| 489 | .collect() |
| 490 | } |
| 491 | |
| 492 | fn ffprobe_colour(stream: &[u8]) -> String { |
| 493 | let path = std::env::temp_dir().join(format!( |
| 494 | "ec-av1-facade-colour-probe-{}-{}.obu", |
| 495 | std::process::id(), |
| 496 | std::ptr::addr_of!(stream) as usize |
| 497 | )); |
| 498 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 499 | let out = Command::new("ffprobe") |
| 500 | .args([ |
| 501 | "-v", |
| 502 | "error", |
| 503 | "-f", |
| 504 | "obu", |
| 505 | "-select_streams", |
| 506 | "v:0", |
| 507 | "-show_entries", |
| 508 | "stream=color_primaries,color_transfer,color_space,color_range", |
| 509 | "-of", |
| 510 | "csv=p=0", |
| 511 | ]) |
| 512 | .arg(&path) |
| 513 | .output() |
| 514 | .expect("ffprobe failed to run"); |
| 515 | let _ = std::fs::remove_file(&path); |
| 516 | assert!( |
| 517 | out.status.success(), |
| 518 | "ffprobe refused the stream: {}", |
| 519 | String::from_utf8_lossy(&out.stderr) |
| 520 | ); |
| 521 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 522 | } |
| 523 | |
| 524 | |
| 525 | |
| 526 | |
| 527 | |
| 528 | #[test] |
| 529 | fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { |
| 530 | if !have_ffmpeg() { |
| 531 | eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg"); |
| 532 | return; |
| 533 | } |
| 534 | let (width, height) = (96usize, 96usize); |
| 535 | let config = EncoderConfig { |
| 536 | width, |
| 537 | height, |
| 538 | base_q_idx: 120, |
| 539 | gop: 15, |
| 540 | colour: Colour::Bt709Limited, |
| 541 | }; |
| 542 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 543 | assert_eq!(enc.display_size(), (width, height)); |
| 544 | let (coded_w, coded_h) = enc.coded_size(); |
| 545 | assert_eq!( |
| 546 | (coded_w, coded_h), |
| 547 | ( |
| 548 | width.next_multiple_of(SUPERBLOCK), |
| 549 | height.next_multiple_of(SUPERBLOCK) |
| 550 | ) |
| 551 | ); |
| 552 | |
| 553 | let packets: Vec<Packet> = (0..30) |
| 554 | .map(|t| enc.encode(&test_card(width, height, t)).unwrap()) |
| 555 | .collect(); |
| 556 | let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect(); |
| 557 | assert_eq!( |
| 558 | packets.iter().map(|p| p.key).collect::<Vec<_>>(), |
| 559 | expect_key, |
| 560 | "facade's own key/inter flags" |
| 561 | ); |
| 562 | |
| 563 | let stream = concat(&packets); |
| 564 | let frames = ffprobe_frames(&stream); |
| 565 | assert_eq!(frames.len(), 30, "ffprobe frame count"); |
| 566 | for (t, (key, w, h)) in frames.iter().enumerate() { |
| 567 | assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); |
| 568 | assert_eq!( |
| 569 | (*w, *h), |
| 570 | (width as u32, height as u32), |
| 571 | "picture {t}: ffprobe reports the true (display) size, not the padded coded one" |
| 572 | ); |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | |
| 577 | |
| 578 | |
| 579 | |
| 580 | |
| 581 | |
| 582 | #[test] |
| 583 | fn bt709_limited_colour_is_reported_by_ffprobe() { |
| 584 | if !have_ffmpeg() { |
| 585 | eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 586 | return; |
| 587 | } |
| 588 | let config = EncoderConfig { |
| 589 | width: 64, |
| 590 | height: 64, |
| 591 | base_q_idx: 100, |
| 592 | gop: 4, |
| 593 | colour: Colour::Bt709Limited, |
| 594 | }; |
| 595 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 596 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 597 | let colour = ffprobe_colour(&packet.data); |
| 598 | assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); |
| 599 | } |
| 600 | |
| 601 | |
| 602 | |
| 603 | |
| 604 | #[test] |
| 605 | fn bt601_limited_colour_is_reported_by_ffprobe() { |
| 606 | if !have_ffmpeg() { |
| 607 | eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 608 | return; |
| 609 | } |
| 610 | let config = EncoderConfig { |
| 611 | width: 64, |
| 612 | height: 64, |
| 613 | base_q_idx: 100, |
| 614 | gop: 4, |
| 615 | colour: Colour::Bt601Limited, |
| 616 | }; |
| 617 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 618 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 619 | let colour = ffprobe_colour(&packet.data); |
| 620 | assert_eq!( |
| 621 | colour, "tv,smpte170m,smpte170m,smpte170m", |
| 622 | "ffprobe colour fields" |
| 623 | ); |
| 624 | } |
| 625 | |
| 626 | |
| 627 | |
| 628 | #[test] |
| 629 | fn geometry_mismatch_is_refused() { |
| 630 | let config = EncoderConfig { |
| 631 | width: 64, |
| 632 | height: 64, |
| 633 | base_q_idx: 100, |
| 634 | gop: 4, |
| 635 | colour: Colour::Bt709Limited, |
| 636 | }; |
| 637 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 638 | let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); |
| 639 | assert!(err.to_string().contains("64x64"), "{err}"); |
| 640 | } |
| 641 | |
| 642 | |
| 643 | #[test] |
| 644 | fn zero_gop_is_refused() { |
| 645 | let config = EncoderConfig { |
| 646 | width: 64, |
| 647 | height: 64, |
| 648 | base_q_idx: 100, |
| 649 | gop: 0, |
| 650 | colour: Colour::Bt709Limited, |
| 651 | }; |
| 652 | let err = Av1Encoder::new(config).unwrap_err(); |
| 653 | assert!(err.to_string().contains("gop"), "{err}"); |
| 654 | } |
| 655 | |
| 656 | |
| 657 | |
| 658 | |
| 659 | |
| 660 | |
| 661 | fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> { |
| 662 | if !have_ffmpeg() { |
| 663 | return None; |
| 664 | } |
| 665 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 666 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 667 | if !clip.exists() { |
| 668 | return None; |
| 669 | } |
| 670 | let out = Command::new("ffmpeg") |
| 671 | .args(["-v", "error", "-i", clip.to_str().unwrap()]) |
| 672 | .args(["-frames:v", &frames.to_string()]) |
| 673 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 674 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 675 | .output() |
| 676 | .expect("ffmpeg failed to run"); |
| 677 | assert!( |
| 678 | out.status.success(), |
| 679 | "{}", |
| 680 | String::from_utf8_lossy(&out.stderr) |
| 681 | ); |
| 682 | let (luma, chroma) = (width * height, width * height / 4); |
| 683 | let frame_len = luma + 2 * chroma; |
| 684 | assert_eq!( |
| 685 | out.stdout.len(), |
| 686 | frame_len * frames, |
| 687 | "expected {frames} 4:2:0 frames" |
| 688 | ); |
| 689 | Some( |
| 690 | (0..frames) |
| 691 | .map(|i| { |
| 692 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 693 | Picture { |
| 694 | width, |
| 695 | height, |
| 696 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 697 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 698 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 699 | } |
| 700 | }) |
| 701 | .collect(), |
| 702 | ) |
| 703 | } |
| 704 | |
| 705 | |
| 706 | |
| 707 | |
| 708 | |
| 709 | #[test] |
| 710 | fn bytes_per_frame_target_settles_within_20_percent() { |
| 711 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 712 | eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture"); |
| 713 | return; |
| 714 | }; |
| 715 | let target_bytes = 4_000u32; |
| 716 | let config = EncoderConfig { |
| 717 | width: 640, |
| 718 | height: 384, |
| 719 | base_q_idx: 100, |
| 720 | gop: 24, |
| 721 | colour: Colour::Bt709Limited, |
| 722 | }; |
| 723 | let mut enc = |
| 724 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); |
| 725 | let sizes: Vec<usize> = pictures |
| 726 | .iter() |
| 727 | .map(|p| enc.encode(p).unwrap().data.len()) |
| 728 | .collect(); |
| 729 | |
| 730 | |
| 731 | let settled = &sizes[5..]; |
| 732 | let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64; |
| 733 | let low = f64::from(target_bytes) * 0.8; |
| 734 | let high = f64::from(target_bytes) * 1.2; |
| 735 | assert!( |
| 736 | mean >= low && mean <= high, |
| 737 | "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" |
| 738 | ); |
| 739 | } |
| 740 | |
| 741 | |
| 742 | |
| 743 | |
| 744 | |
| 745 | #[test] |
| 746 | fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { |
| 747 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 748 | eprintln!( |
| 749 | "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture" |
| 750 | ); |
| 751 | return; |
| 752 | }; |
| 753 | let config = EncoderConfig { |
| 754 | width: 640, |
| 755 | height: 384, |
| 756 | base_q_idx: 100, |
| 757 | gop: 24, |
| 758 | colour: Colour::Bt709Limited, |
| 759 | }; |
| 760 | let mut enc = |
| 761 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); |
| 762 | let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(); |
| 763 | for picture in &pictures { |
| 764 | enc.encode(picture).unwrap(); |
| 765 | let q = enc.rate_loop.as_ref().unwrap().q_idx(); |
| 766 | let step = (i32::from(q) - i32::from(prev_q)).abs(); |
| 767 | assert!( |
| 768 | f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, |
| 769 | "q stepped from {prev_q} to {q}, past the {} clamp", |
| 770 | RateLoop::STEP_CLAMP |
| 771 | ); |
| 772 | prev_q = q; |
| 773 | } |
| 774 | } |
| 775 | |
| 776 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 777 | let squared: f64 = a |
| 778 | .iter() |
| 779 | .zip(b) |
| 780 | .map(|(&x, &y)| { |
| 781 | let d = f64::from(x) - f64::from(y); |
| 782 | d * d |
| 783 | }) |
| 784 | .sum(); |
| 785 | if squared == 0.0 { |
| 786 | return f64::INFINITY; |
| 787 | } |
| 788 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 789 | } |
| 790 | |
| 791 | |
| 792 | |
| 793 | |
| 794 | |
| 795 | fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> { |
| 796 | let path = std::env::temp_dir().join(format!( |
| 797 | "ec-av1-facade-rate-decode-{}-{}.obu", |
| 798 | std::process::id(), |
| 799 | std::ptr::addr_of!(stream) as usize |
| 800 | )); |
| 801 | std::fs::write(&path, stream).expect("writing the decode probe stream"); |
| 802 | let out = Command::new("ffmpeg") |
| 803 | .args(["-v", "error", "-f", "obu", "-i"]) |
| 804 | .arg(&path) |
| 805 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 806 | .output() |
| 807 | .expect("ffmpeg failed to run"); |
| 808 | let _ = std::fs::remove_file(&path); |
| 809 | assert!( |
| 810 | out.status.success(), |
| 811 | "{}", |
| 812 | String::from_utf8_lossy(&out.stderr) |
| 813 | ); |
| 814 | let (luma, chroma) = (width * height, width * height / 4); |
| 815 | let frame_len = luma + 2 * chroma; |
| 816 | out.stdout |
| 817 | .chunks_exact(frame_len) |
| 818 | .map(|f| f[..luma].to_vec()) |
| 819 | .collect() |
| 820 | } |
| 821 | |
| 822 | |
| 823 | |
| 824 | |
| 825 | #[test] |
| 826 | fn quality_target_is_monotone_in_bytes_and_psnr() { |
| 827 | if !have_ffmpeg() { |
| 828 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg"); |
| 829 | return; |
| 830 | } |
| 831 | let (width, height) = (640, 384); |
| 832 | let Some(pictures) = h264_clip_frames(width, height, 8) else { |
| 833 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture"); |
| 834 | return; |
| 835 | }; |
| 836 | let mut prev_bytes = 0usize; |
| 837 | let mut prev_psnr = 0.0f64; |
| 838 | for quality in [20u8, 50, 80] { |
| 839 | let config = EncoderConfig { |
| 840 | width, |
| 841 | height, |
| 842 | base_q_idx: 100, |
| 843 | gop: 8, |
| 844 | colour: Colour::Bt709Limited, |
| 845 | }; |
| 846 | let mut enc = |
| 847 | Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); |
| 848 | let mut stream = Vec::new(); |
| 849 | let mut total_bytes = 0usize; |
| 850 | for picture in &pictures { |
| 851 | let packet = enc.encode(picture).unwrap(); |
| 852 | total_bytes += packet.data.len(); |
| 853 | stream.extend_from_slice(&packet.data); |
| 854 | } |
| 855 | let decoded = ffmpeg_decode_luma(&stream, width, height); |
| 856 | assert_eq!( |
| 857 | decoded.len(), |
| 858 | pictures.len(), |
| 859 | "quality {quality}: dav1d frame count" |
| 860 | ); |
| 861 | let mean_psnr: f64 = decoded |
| 862 | .iter() |
| 863 | .zip(&pictures) |
| 864 | .map(|(d, p)| { |
| 865 | let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect(); |
| 866 | psnr(&d16, &p.y) |
| 867 | }) |
| 868 | .sum::<f64>() |
| 869 | / decoded.len() as f64; |
| 870 | assert!( |
| 871 | total_bytes >= prev_bytes, |
| 872 | "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" |
| 873 | ); |
| 874 | assert!( |
| 875 | mean_psnr >= prev_psnr - 0.01, |
| 876 | "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" |
| 877 | ); |
| 878 | prev_bytes = total_bytes; |
| 879 | prev_psnr = mean_psnr; |
| 880 | } |
| 881 | } |
| 882 | } |