| 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 | #[derive(Debug, Clone, Copy)] |
| 85 | pub struct EncoderConfig { |
| 86 | |
| 87 | pub width: usize, |
| 88 | |
| 89 | pub height: usize, |
| 90 | |
| 91 | pub base_q_idx: u8, |
| 92 | |
| 93 | |
| 94 | |
| 95 | pub gop: usize, |
| 96 | |
| 97 | pub colour: Colour, |
| 98 | } |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | #[derive(Debug, Clone)] |
| 104 | pub struct Packet { |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | pub data: Vec<u8>, |
| 112 | |
| 113 | pub key: bool, |
| 114 | |
| 115 | |
| 116 | pub order: u64, |
| 117 | } |
| 118 | |
| 119 | |
| 120 | |
| 121 | #[derive(Debug)] |
| 122 | pub struct Av1Encoder { |
| 123 | config: EncoderConfig, |
| 124 | color_config: ColorConfig, |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | reference: Option<Picture>, |
| 130 | next_index: u64, |
| 131 | } |
| 132 | |
| 133 | impl Av1Encoder { |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | pub fn new(config: EncoderConfig) -> Result<Self> { |
| 140 | if config.gop == 0 { |
| 141 | return Err(Error::unsupported("AV1 encode", "gop must be at least 1")); |
| 142 | } |
| 143 | |
| 144 | |
| 145 | |
| 146 | Picture::grey(config.width, config.height).check_even()?; |
| 147 | Ok(Self { |
| 148 | color_config: config.colour.color_config(), |
| 149 | config, |
| 150 | reference: None, |
| 151 | next_index: 0, |
| 152 | }) |
| 153 | } |
| 154 | |
| 155 | |
| 156 | |
| 157 | #[must_use] |
| 158 | pub fn coded_size(&self) -> (usize, usize) { |
| 159 | ( |
| 160 | self.config.width.next_multiple_of(SUPERBLOCK), |
| 161 | self.config.height.next_multiple_of(SUPERBLOCK), |
| 162 | ) |
| 163 | } |
| 164 | |
| 165 | |
| 166 | |
| 167 | #[must_use] |
| 168 | pub fn display_size(&self) -> (usize, usize) { |
| 169 | (self.config.width, self.config.height) |
| 170 | } |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | pub fn encode(&mut self, picture: &Picture) -> Result<Packet> { |
| 182 | if (picture.width, picture.height) != (self.config.width, self.config.height) { |
| 183 | return Err(Error::unsupported( |
| 184 | "AV1 encode", |
| 185 | format!( |
| 186 | "picture is {}x{}, encoder is {}x{}", |
| 187 | picture.width, picture.height, self.config.width, self.config.height |
| 188 | ), |
| 189 | )); |
| 190 | } |
| 191 | let render = (self.config.width, self.config.height); |
| 192 | let padded = picture.padded_to(SUPERBLOCK); |
| 193 | let is_key = self.next_index % self.config.gop as u64 == 0; |
| 194 | let order = self.next_index; |
| 195 | |
| 196 | let encoded: Encoded = if is_key { |
| 197 | encode_key_frame_inner( |
| 198 | &padded, |
| 199 | self.config.base_q_idx, |
| 200 | DEADZONE, |
| 201 | &KEY_FRAME_MODES, |
| 202 | split_blocks(), |
| 203 | render, |
| 204 | self.color_config, |
| 205 | )? |
| 206 | } else { |
| 207 | let reference = self.reference.as_ref().ok_or_else(|| { |
| 208 | Error::unsupported( |
| 209 | "AV1 encode", |
| 210 | "an inter frame needs a previous reconstruction", |
| 211 | ) |
| 212 | })?; |
| 213 | encode_inter_frame( |
| 214 | &padded, |
| 215 | reference, |
| 216 | self.config.base_q_idx, |
| 217 | DEADZONE, |
| 218 | order as u32, |
| 219 | render, |
| 220 | )? |
| 221 | }; |
| 222 | |
| 223 | self.reference = Some(encoded.reconstruction.clone()); |
| 224 | self.next_index += 1; |
| 225 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 226 | Ok(Packet { |
| 227 | data: cropped.stream, |
| 228 | key: is_key, |
| 229 | order, |
| 230 | }) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | #[cfg(test)] |
| 235 | mod tests { |
| 236 | use super::*; |
| 237 | use std::process::{Command, Stdio}; |
| 238 | |
| 239 | fn have_ffmpeg() -> bool { |
| 240 | Command::new("ffmpeg") |
| 241 | .arg("-version") |
| 242 | .stdout(Stdio::null()) |
| 243 | .stderr(Stdio::null()) |
| 244 | .status() |
| 245 | .is_ok_and(|s| s.success()) |
| 246 | } |
| 247 | |
| 248 | fn test_card(width: usize, height: usize, shift: usize) -> Picture { |
| 249 | let mut picture = Picture::grey(width, height); |
| 250 | for y in 0..height { |
| 251 | for x in 0..width { |
| 252 | let sx = (x + shift) % width; |
| 253 | picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u8; |
| 254 | } |
| 255 | } |
| 256 | for y in 0..height / 2 { |
| 257 | for x in 0..width / 2 { |
| 258 | let i = y * (width / 2) + x; |
| 259 | picture.u[i] = ((100 + shift * 4) % 256) as u8; |
| 260 | picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u8; |
| 261 | } |
| 262 | } |
| 263 | picture |
| 264 | } |
| 265 | |
| 266 | |
| 267 | |
| 268 | fn concat(packets: &[Packet]) -> Vec<u8> { |
| 269 | packets.iter().flat_map(|p| p.data.clone()).collect() |
| 270 | } |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | #[test] |
| 276 | fn one_in_one_out() { |
| 277 | let config = EncoderConfig { |
| 278 | width: 64, |
| 279 | height: 64, |
| 280 | base_q_idx: 100, |
| 281 | gop: 2, |
| 282 | colour: Colour::Bt709Limited, |
| 283 | }; |
| 284 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 285 | for t in 0..5u64 { |
| 286 | let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); |
| 287 | assert!(!packet.data.is_empty(), "picture {t}: empty packet"); |
| 288 | assert_eq!(packet.order, t, "picture {t}: order"); |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | #[test] |
| 296 | fn gop_cadence_is_honored() { |
| 297 | let config = EncoderConfig { |
| 298 | width: 64, |
| 299 | height: 64, |
| 300 | base_q_idx: 100, |
| 301 | gop: 3, |
| 302 | colour: Colour::Unspecified, |
| 303 | }; |
| 304 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 305 | let keys: Vec<bool> = (0..7) |
| 306 | .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key) |
| 307 | .collect(); |
| 308 | assert_eq!(keys, vec![true, false, false, true, false, false, true]); |
| 309 | } |
| 310 | |
| 311 | fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { |
| 312 | let path = std::env::temp_dir().join(format!( |
| 313 | "ec-av1-facade-probe-{}-{}.obu", |
| 314 | std::process::id(), |
| 315 | std::ptr::addr_of!(stream) as usize |
| 316 | )); |
| 317 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 318 | let out = Command::new("ffprobe") |
| 319 | .args([ |
| 320 | "-v", |
| 321 | "error", |
| 322 | "-f", |
| 323 | "obu", |
| 324 | "-select_streams", |
| 325 | "v:0", |
| 326 | "-show_entries", |
| 327 | "frame=key_frame,width,height", |
| 328 | "-of", |
| 329 | "csv=p=0", |
| 330 | ]) |
| 331 | .arg(&path) |
| 332 | .output() |
| 333 | .expect("ffprobe failed to run"); |
| 334 | let _ = std::fs::remove_file(&path); |
| 335 | assert!( |
| 336 | out.status.success(), |
| 337 | "ffprobe refused the stream: {}", |
| 338 | String::from_utf8_lossy(&out.stderr) |
| 339 | ); |
| 340 | String::from_utf8_lossy(&out.stdout) |
| 341 | .lines() |
| 342 | .map(|line| { |
| 343 | let mut f = line.trim().split(','); |
| 344 | let key: u32 = f.next().unwrap().parse().unwrap(); |
| 345 | let width: u32 = f.next().unwrap().parse().unwrap(); |
| 346 | let height: u32 = f.next().unwrap().parse().unwrap(); |
| 347 | (key == 1, width, height) |
| 348 | }) |
| 349 | .collect() |
| 350 | } |
| 351 | |
| 352 | fn ffprobe_colour(stream: &[u8]) -> String { |
| 353 | let path = std::env::temp_dir().join(format!( |
| 354 | "ec-av1-facade-colour-probe-{}-{}.obu", |
| 355 | std::process::id(), |
| 356 | std::ptr::addr_of!(stream) as usize |
| 357 | )); |
| 358 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 359 | let out = Command::new("ffprobe") |
| 360 | .args([ |
| 361 | "-v", |
| 362 | "error", |
| 363 | "-f", |
| 364 | "obu", |
| 365 | "-select_streams", |
| 366 | "v:0", |
| 367 | "-show_entries", |
| 368 | "stream=color_primaries,color_transfer,color_space,color_range", |
| 369 | "-of", |
| 370 | "csv=p=0", |
| 371 | ]) |
| 372 | .arg(&path) |
| 373 | .output() |
| 374 | .expect("ffprobe failed to run"); |
| 375 | let _ = std::fs::remove_file(&path); |
| 376 | assert!( |
| 377 | out.status.success(), |
| 378 | "ffprobe refused the stream: {}", |
| 379 | String::from_utf8_lossy(&out.stderr) |
| 380 | ); |
| 381 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 382 | } |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | #[test] |
| 389 | fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { |
| 390 | if !have_ffmpeg() { |
| 391 | eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg"); |
| 392 | return; |
| 393 | } |
| 394 | let (width, height) = (96usize, 96usize); |
| 395 | let config = EncoderConfig { |
| 396 | width, |
| 397 | height, |
| 398 | base_q_idx: 120, |
| 399 | gop: 15, |
| 400 | colour: Colour::Bt709Limited, |
| 401 | }; |
| 402 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 403 | assert_eq!(enc.display_size(), (width, height)); |
| 404 | let (coded_w, coded_h) = enc.coded_size(); |
| 405 | assert_eq!( |
| 406 | (coded_w, coded_h), |
| 407 | ( |
| 408 | width.next_multiple_of(SUPERBLOCK), |
| 409 | height.next_multiple_of(SUPERBLOCK) |
| 410 | ) |
| 411 | ); |
| 412 | |
| 413 | let packets: Vec<Packet> = (0..30) |
| 414 | .map(|t| enc.encode(&test_card(width, height, t)).unwrap()) |
| 415 | .collect(); |
| 416 | let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect(); |
| 417 | assert_eq!( |
| 418 | packets.iter().map(|p| p.key).collect::<Vec<_>>(), |
| 419 | expect_key, |
| 420 | "facade's own key/inter flags" |
| 421 | ); |
| 422 | |
| 423 | let stream = concat(&packets); |
| 424 | let frames = ffprobe_frames(&stream); |
| 425 | assert_eq!(frames.len(), 30, "ffprobe frame count"); |
| 426 | for (t, (key, w, h)) in frames.iter().enumerate() { |
| 427 | assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); |
| 428 | assert_eq!( |
| 429 | (*w, *h), |
| 430 | (width as u32, height as u32), |
| 431 | "picture {t}: ffprobe reports the true (display) size, not the padded coded one" |
| 432 | ); |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | |
| 440 | |
| 441 | |
| 442 | #[test] |
| 443 | fn bt709_limited_colour_is_reported_by_ffprobe() { |
| 444 | if !have_ffmpeg() { |
| 445 | eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 446 | return; |
| 447 | } |
| 448 | let config = EncoderConfig { |
| 449 | width: 64, |
| 450 | height: 64, |
| 451 | base_q_idx: 100, |
| 452 | gop: 4, |
| 453 | colour: Colour::Bt709Limited, |
| 454 | }; |
| 455 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 456 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 457 | let colour = ffprobe_colour(&packet.data); |
| 458 | assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); |
| 459 | } |
| 460 | |
| 461 | |
| 462 | |
| 463 | |
| 464 | #[test] |
| 465 | fn bt601_limited_colour_is_reported_by_ffprobe() { |
| 466 | if !have_ffmpeg() { |
| 467 | eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 468 | return; |
| 469 | } |
| 470 | let config = EncoderConfig { |
| 471 | width: 64, |
| 472 | height: 64, |
| 473 | base_q_idx: 100, |
| 474 | gop: 4, |
| 475 | colour: Colour::Bt601Limited, |
| 476 | }; |
| 477 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 478 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 479 | let colour = ffprobe_colour(&packet.data); |
| 480 | assert_eq!( |
| 481 | colour, "tv,smpte170m,smpte170m,smpte170m", |
| 482 | "ffprobe colour fields" |
| 483 | ); |
| 484 | } |
| 485 | |
| 486 | |
| 487 | |
| 488 | #[test] |
| 489 | fn geometry_mismatch_is_refused() { |
| 490 | let config = EncoderConfig { |
| 491 | width: 64, |
| 492 | height: 64, |
| 493 | base_q_idx: 100, |
| 494 | gop: 4, |
| 495 | colour: Colour::Bt709Limited, |
| 496 | }; |
| 497 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 498 | let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); |
| 499 | assert!(err.to_string().contains("64x64"), "{err}"); |
| 500 | } |
| 501 | |
| 502 | |
| 503 | #[test] |
| 504 | fn zero_gop_is_refused() { |
| 505 | let config = EncoderConfig { |
| 506 | width: 64, |
| 507 | height: 64, |
| 508 | base_q_idx: 100, |
| 509 | gop: 0, |
| 510 | colour: Colour::Bt709Limited, |
| 511 | }; |
| 512 | let err = Av1Encoder::new(config).unwrap_err(); |
| 513 | assert!(err.to_string().contains("gop"), "{err}"); |
| 514 | } |
| 515 | } |