| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | #![allow(dead_code)] |
| 38 | |
| 39 | use std::collections::VecDeque; |
| 40 | use std::rc::Rc; |
| 41 | |
| 42 | use ec_va::caps::{Entrypoint, Profile}; |
| 43 | use ec_va::va::SurfaceMemoryDescriptor; |
| 44 | use ec_va::va::{ |
| 45 | BufferType, EncMiscParameter, EncMiscParameterBufferQualityLevel, EncMiscParameterFrameRate, |
| 46 | EncMiscParameterHRD, EncMiscParameterRateControl, EncPackedHeaderParameter, EncPackedHeaderType, |
| 47 | RcFlags, |
| 48 | VA_ENC_PACKED_HEADER_PICTURE, VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE, |
| 49 | VA_FOURCC_NV12, VA_FOURCC_P010, VA_RT_FORMAT_YUV420, VA_RT_FORMAT_YUV420_10, |
| 50 | VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER, VAConfigAttribType, VAImage, |
| 51 | }; |
| 52 | use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, Vpp}; |
| 53 | |
| 54 | use crate::error::{Error, Result}; |
| 55 | use crate::frame::{Frame, I420, I420_16}; |
| 56 | use crate::pool::{PooledSurface, SurfacePool}; |
| 57 | use crate::rate::{RATE_WINDOW_MS, RateFeedback, hrd_buffer_ms}; |
| 58 | |
| 59 | pub use crate::types::{ |
| 60 | CodedFrame, Colour, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, Tunings, |
| 61 | }; |
| 62 | |
| 63 | mod av1; |
| 64 | mod h264; |
| 65 | mod headers; |
| 66 | mod hevc; |
| 67 | |
| 68 | |
| 69 | |
| 70 | const VA_RC_QVBR: u32 = 0x0000_0400; |
| 71 | |
| 72 | impl H264Profile { |
| 73 | |
| 74 | fn va_profile(self) -> Profile { |
| 75 | match self { |
| 76 | H264Profile::ConstrainedBaseline => Profile::H264ConstrainedBaseline, |
| 77 | H264Profile::Main => Profile::H264Main, |
| 78 | H264Profile::High => Profile::H264High, |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | |
| 84 | const DEPTH: usize = 3; |
| 85 | |
| 86 | impl RateControlMode { |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | fn va_mode(self) -> u32 { |
| 93 | match self { |
| 94 | RateControlMode::ConstantQp { .. } => ec_va::va::VA_RC_CQP, |
| 95 | RateControlMode::ConstantBitrate => ec_va::va::VA_RC_CBR, |
| 96 | RateControlMode::VariableBitrate => ec_va::va::VA_RC_VBR, |
| 97 | RateControlMode::Qvbr { .. } => VA_RC_QVBR, |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | |
| 103 | struct InFlight<D: SurfaceMemoryDescriptor> { |
| 104 | picture: ec_va::picture::Picture<ec_va::picture::PictureEnd, Rc<ec_va::va::Surface<D>>>, |
| 105 | coded: ec_va::picture::EncCodedBuffer, |
| 106 | source: Rc<ec_va::va::Surface<D>>, |
| 107 | leases: Vec<Rc<PooledSurface>>, |
| 108 | timestamp: i64, |
| 109 | keyframe: bool, |
| 110 | } |
| 111 | |
| 112 | |
| 113 | |
| 114 | pub struct Encoder { |
| 115 | |
| 116 | born_epoch: u64, |
| 117 | config: EncoderConfig, |
| 118 | context: Rc<Context>, |
| 119 | pool: SurfacePool, |
| 120 | coded_size: (u32, u32), |
| 121 | |
| 122 | reference: Option<Rc<PooledSurface>>, |
| 123 | |
| 124 | gop_position: u32, |
| 125 | |
| 126 | |
| 127 | idr_count: u32, |
| 128 | tunings: Tunings, |
| 129 | |
| 130 | tunings_dirty: bool, |
| 131 | rc: RateFeedback, |
| 132 | profile: Profile, |
| 133 | |
| 134 | |
| 135 | |
| 136 | vpp: Option<Vpp>, |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | vpp_surfaces: Vec<Rc<Surface>>, |
| 142 | vpp_next: usize, |
| 143 | |
| 144 | pending: VecDeque<InFlight<()>>, |
| 145 | } |
| 146 | |
| 147 | impl Encoder { |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | pub fn new(display: &Rc<Display>, config: EncoderConfig) -> Result<Encoder> { |
| 153 | let born_epoch = crate::reset::gpu_reset_epoch(); |
| 154 | if crate::reset::gpu_recently_reset() { |
| 155 | return Err(Error::hw_reset( |
| 156 | "the GPU was reset moments ago; new hardware sessions wait out the grace period", |
| 157 | )); |
| 158 | } |
| 159 | if config.bit_depth != 8 && config.bit_depth != 10 { |
| 160 | return Err(Error::config(format!( |
| 161 | "encoder bit depth {} : this crate encodes 8-bit, or 10-bit H.265/AV1", |
| 162 | config.bit_depth |
| 163 | ))); |
| 164 | } |
| 165 | if config.bit_depth == 10 && config.codec == EncCodec::H264 { |
| 166 | return Err(Error::config( |
| 167 | "10-bit encode is H.265 and AV1 only here: the H.264 profiles this crate \ |
| 168 | configures are 8-bit", |
| 169 | )); |
| 170 | } |
| 171 | let (profile, block) = match config.codec { |
| 172 | EncCodec::H264 => (config.h264_profile.va_profile(), 16), |
| 173 | EncCodec::H265 if config.bit_depth == 10 => (Profile::HEVCMain10, 32), |
| 174 | EncCodec::H265 => (Profile::HEVCMain, 32), |
| 175 | EncCodec::Av1 => (Profile::AV1Profile0, 64), |
| 176 | }; |
| 177 | let coded_size = ( |
| 178 | config.width.next_multiple_of(block), |
| 179 | config.height.next_multiple_of(block), |
| 180 | ); |
| 181 | |
| 182 | let caps = CapReport::probe(display)?; |
| 183 | let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| { |
| 184 | Error::unsupported( |
| 185 | format!("{profile:?} encode"), |
| 186 | "the driver advertises no EncSlice entrypoint for this profile", |
| 187 | ) |
| 188 | })?; |
| 189 | if let Some(surfaces) = &entry.surfaces |
| 190 | && !surfaces.allows(coded_size.0, coded_size.1) |
| 191 | { |
| 192 | |
| 193 | |
| 194 | return Err(Error::unsupported( |
| 195 | format!("{}x{} {profile:?} encode", coded_size.0, coded_size.1), |
| 196 | format!( |
| 197 | "the driver accepts {:?}..{:?} x {:?}..{:?}", |
| 198 | surfaces.min_width, |
| 199 | surfaces.max_width, |
| 200 | surfaces.min_height, |
| 201 | surfaces.max_height |
| 202 | ), |
| 203 | )); |
| 204 | } |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | let packed = entry.packed_headers |
| 212 | & (VA_ENC_PACKED_HEADER_SEQUENCE |
| 213 | | VA_ENC_PACKED_HEADER_PICTURE |
| 214 | | VA_ENC_PACKED_HEADER_SLICE); |
| 215 | let config_id = Config::new( |
| 216 | display, |
| 217 | profile, |
| 218 | Entrypoint::EncSlice, |
| 219 | &[ |
| 220 | ConfigAttrib::rt_format(if config.bit_depth == 10 { |
| 221 | VA_RT_FORMAT_YUV420_10 |
| 222 | } else { |
| 223 | VA_RT_FORMAT_YUV420 |
| 224 | }), |
| 225 | ConfigAttrib { |
| 226 | type_: VAConfigAttribType::VAConfigAttribRateControl, |
| 227 | value: config.rate_control.va_mode(), |
| 228 | }, |
| 229 | ConfigAttrib { |
| 230 | type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders, |
| 231 | value: packed, |
| 232 | }, |
| 233 | ], |
| 234 | )?; |
| 235 | let spec = surface_spec(config.bit_depth, coded_size); |
| 236 | |
| 237 | |
| 238 | let surfaces = ec_va::create_pool(display, &spec, 12)?; |
| 239 | for s in &surfaces { |
| 240 | fill_zero(display, s, coded_size, config.bit_depth)?; |
| 241 | } |
| 242 | let context = ec_va::picture::create_context( |
| 243 | display, |
| 244 | &config_id, |
| 245 | coded_size.0, |
| 246 | coded_size.1, |
| 247 | Some(&surfaces), |
| 248 | true, |
| 249 | )?; |
| 250 | let pool = SurfacePool::from_surfaces(surfaces, &spec); |
| 251 | |
| 252 | Ok(Encoder { |
| 253 | born_epoch, |
| 254 | tunings: Tunings { |
| 255 | bitrate: config.bitrate, |
| 256 | framerate: config.framerate, |
| 257 | }, |
| 258 | config, |
| 259 | context, |
| 260 | pool, |
| 261 | coded_size, |
| 262 | reference: None, |
| 263 | gop_position: 0, |
| 264 | idr_count: 0, |
| 265 | tunings_dirty: true, |
| 266 | rc: RateFeedback::default(), |
| 267 | profile, |
| 268 | vpp: None, |
| 269 | vpp_surfaces: Vec::new(), |
| 270 | vpp_next: 0, |
| 271 | pending: VecDeque::new(), |
| 272 | }) |
| 273 | } |
| 274 | |
| 275 | |
| 276 | pub fn coded_size(&self) -> (u32, u32) { |
| 277 | self.coded_size |
| 278 | } |
| 279 | |
| 280 | |
| 281 | pub fn tune(&mut self, tunings: Tunings) { |
| 282 | self.tunings = tunings; |
| 283 | self.tunings_dirty = true; |
| 284 | self.rc = RateFeedback::default(); |
| 285 | } |
| 286 | |
| 287 | |
| 288 | pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { |
| 289 | if !self.pending.is_empty() { |
| 290 | return Err(Error::config( |
| 291 | "encode: pipelined frames pending; call flush first", |
| 292 | )); |
| 293 | } |
| 294 | if self.config.bit_depth != 8 { |
| 295 | return Err(Error::config(format!( |
| 296 | "encode: this encoder is configured for {} bits; call encode_16", |
| 297 | self.config.bit_depth |
| 298 | ))); |
| 299 | } |
| 300 | self.check_size(frame.width, frame.height)?; |
| 301 | let input = self |
| 302 | .pool |
| 303 | .acquire() |
| 304 | .ok_or_else(|| Error::config("encode: every surface is still in use"))?; |
| 305 | upload(&self.context, frame, input.surface(), self.coded_size)?; |
| 306 | self.encode_settled(Rc::clone(input.surface()), meta) |
| 307 | } |
| 308 | |
| 309 | |
| 310 | |
| 311 | pub fn submit(&mut self, frame: &I420, meta: FrameMetadata) -> Result<Option<CodedFrame>> { |
| 312 | if self.config.bit_depth != 8 { |
| 313 | return Err(Error::config(format!( |
| 314 | "submit: this encoder is configured for {} bits; call submit_16", |
| 315 | self.config.bit_depth |
| 316 | ))); |
| 317 | } |
| 318 | self.check_size(frame.width, frame.height)?; |
| 319 | let input = self |
| 320 | .pool |
| 321 | .acquire() |
| 322 | .ok_or_else(|| Error::config("submit: every surface is still in use"))?; |
| 323 | upload(&self.context, frame, input.surface(), self.coded_size)?; |
| 324 | self.push_pipelined(input, meta) |
| 325 | } |
| 326 | |
| 327 | |
| 328 | pub fn submit_16( |
| 329 | &mut self, |
| 330 | frame: &I420_16, |
| 331 | meta: FrameMetadata, |
| 332 | ) -> Result<Option<CodedFrame>> { |
| 333 | if self.config.bit_depth != 10 { |
| 334 | return Err(Error::config(format!( |
| 335 | "submit_16: this encoder is configured for {} bits; call submit", |
| 336 | self.config.bit_depth |
| 337 | ))); |
| 338 | } |
| 339 | self.check_size(frame.width, frame.height)?; |
| 340 | let input = self |
| 341 | .pool |
| 342 | .acquire() |
| 343 | .ok_or_else(|| Error::config("submit_16: every surface is still in use"))?; |
| 344 | upload_16(&self.context, frame, input.surface(), self.coded_size)?; |
| 345 | self.push_pipelined(input, meta) |
| 346 | } |
| 347 | |
| 348 | |
| 349 | pub fn flush(&mut self) -> Result<Vec<CodedFrame>> { |
| 350 | let mut out = Vec::with_capacity(self.pending.len()); |
| 351 | while let Some(f) = self.pending.pop_front() { |
| 352 | out.push(self.finish(f)?); |
| 353 | } |
| 354 | Ok(out) |
| 355 | } |
| 356 | |
| 357 | fn push_pipelined( |
| 358 | &mut self, |
| 359 | input: Rc<PooledSurface>, |
| 360 | meta: FrameMetadata, |
| 361 | ) -> Result<Option<CodedFrame>> { |
| 362 | let source = Rc::clone(input.surface()); |
| 363 | let in_flight = self.submit_settled(source, meta, vec![input])?; |
| 364 | self.pending.push_back(in_flight); |
| 365 | if self.pending.len() > DEPTH { |
| 366 | self.retire_oldest() |
| 367 | } else { |
| 368 | Ok(None) |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | pub fn submit_prime( |
| 377 | &mut self, |
| 378 | surface: Rc<ec_va::va::Surface<ec_va::surface::PrimeImport>>, |
| 379 | meta: FrameMetadata, |
| 380 | ) -> Result<Option<CodedFrame>> { |
| 381 | let input = self |
| 382 | .pool |
| 383 | .acquire() |
| 384 | .ok_or_else(|| Error::config("submit_prime: every surface is still in use"))?; |
| 385 | let dest = if surface.size() == self.coded_size { |
| 386 | (0, 0, 0, 0) |
| 387 | } else { |
| 388 | (0, 0, self.config.width, self.config.height) |
| 389 | }; |
| 390 | self.vpp()? |
| 391 | .convert_region(&surface, (0, 0, 0, 0), Rc::clone(input.surface()), dest)?; |
| 392 | zero_padding( |
| 393 | self.context.display(), |
| 394 | input.surface(), |
| 395 | self.config.bit_depth, |
| 396 | (self.config.width, self.config.height), |
| 397 | self.coded_size, |
| 398 | )?; |
| 399 | self.push_pipelined(input, meta) |
| 400 | } |
| 401 | |
| 402 | fn retire_oldest(&mut self) -> Result<Option<CodedFrame>> { |
| 403 | match self.pending.pop_front() { |
| 404 | Some(f) => self.finish(f).map(Some), |
| 405 | None => Ok(None), |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> { |
| 414 | if !self.pending.is_empty() { |
| 415 | return Err(Error::config( |
| 416 | "encode_16: pipelined frames pending; call flush first", |
| 417 | )); |
| 418 | } |
| 419 | if self.config.bit_depth != 10 { |
| 420 | return Err(Error::config(format!( |
| 421 | "encode_16: this encoder is configured for {} bits; call encode", |
| 422 | self.config.bit_depth |
| 423 | ))); |
| 424 | } |
| 425 | self.check_size(frame.width, frame.height)?; |
| 426 | let input = self |
| 427 | .pool |
| 428 | .acquire() |
| 429 | .ok_or_else(|| Error::config("encode: every surface is still in use"))?; |
| 430 | upload_16(&self.context, frame, input.surface(), self.coded_size)?; |
| 431 | self.encode_settled(Rc::clone(input.surface()), meta) |
| 432 | } |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | |
| 440 | |
| 441 | |
| 442 | |
| 443 | |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | pub fn encode_frame(&mut self, frame: &Frame, meta: FrameMetadata) -> Result<CodedFrame> { |
| 449 | if !self.pending.is_empty() { |
| 450 | return Err(Error::config( |
| 451 | "encode_frame: pipelined frames pending; call flush first", |
| 452 | )); |
| 453 | } |
| 454 | if frame.bit_depth != 8 && frame.bit_depth != 10 { |
| 455 | return Err(Error::unsupported( |
| 456 | format!("encode_frame of a {}-bit source", frame.bit_depth), |
| 457 | "the VPP conversion this crate builds reads 8-bit NV12 and 10-bit P010 only", |
| 458 | )); |
| 459 | } |
| 460 | if !Rc::ptr_eq(frame.display(), self.context.display()) { |
| 461 | return Err(Error::config( |
| 462 | "encode_frame: the frame was decoded on a different Display than this encoder", |
| 463 | )); |
| 464 | } |
| 465 | let source = |
| 466 | if frame.bit_depth != self.config.bit_depth || frame.coded_size != self.coded_size { |
| 467 | self.vpp_into_pool(frame.surface(), frame.display_size)? |
| 468 | } else { |
| 469 | Rc::clone(frame.surface()) |
| 470 | }; |
| 471 | self.encode_settled(source, meta) |
| 472 | } |
| 473 | |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | pub fn encode_surface<D: SurfaceMemoryDescriptor>( |
| 482 | &mut self, |
| 483 | surface: &Rc<ec_va::va::Surface<D>>, |
| 484 | display_size: (u32, u32), |
| 485 | meta: FrameMetadata, |
| 486 | ) -> Result<CodedFrame> { |
| 487 | if !self.pending.is_empty() { |
| 488 | return Err(Error::config( |
| 489 | "encode_surface: pipelined frames pending; call flush first", |
| 490 | )); |
| 491 | } |
| 492 | if surface.size() != self.coded_size { |
| 493 | let converted = self.vpp_into_pool(surface, display_size)?; |
| 494 | self.encode_settled(converted, meta) |
| 495 | } else { |
| 496 | self.encode_settled(Rc::clone(surface), meta) |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | fn check_size(&self, width: u32, height: u32) -> Result<()> { |
| 501 | if width != self.config.width || height != self.config.height { |
| 502 | return Err(Error::config(format!( |
| 503 | "encoder configured for {}x{} was given a {}x{} frame", |
| 504 | self.config.width, self.config.height, width, height |
| 505 | ))); |
| 506 | } |
| 507 | Ok(()) |
| 508 | } |
| 509 | |
| 510 | |
| 511 | |
| 512 | |
| 513 | |
| 514 | |
| 515 | |
| 516 | fn vpp(&mut self) -> Result<&Vpp> { |
| 517 | if self.vpp.is_none() { |
| 518 | let spec = surface_spec(self.config.bit_depth, self.coded_size); |
| 519 | let display = Rc::clone(self.context.display()); |
| 520 | let surfaces = ec_va::create_pool(&display, &spec, 2)?; |
| 521 | for s in &surfaces { |
| 522 | fill_black(&display, s, self.coded_size, self.config.bit_depth)?; |
| 523 | } |
| 524 | let vpp = Vpp::new( |
| 525 | &display, |
| 526 | VA_RT_FORMAT_YUV420 | VA_RT_FORMAT_YUV420_10, |
| 527 | self.coded_size.0, |
| 528 | self.coded_size.1, |
| 529 | )?; |
| 530 | self.vpp_surfaces = surfaces.into_iter().map(Rc::new).collect(); |
| 531 | self.vpp = Some(vpp); |
| 532 | } |
| 533 | Ok(self.vpp.as_ref().expect("just built above if it was None")) |
| 534 | } |
| 535 | |
| 536 | fn vpp_into_pool<D: SurfaceMemoryDescriptor>( |
| 537 | &mut self, |
| 538 | source: &ec_va::va::Surface<D>, |
| 539 | display_size: (u32, u32), |
| 540 | ) -> Result<Rc<Surface>> { |
| 541 | self.vpp()?; |
| 542 | let dest = Rc::clone(&self.vpp_surfaces[self.vpp_next]); |
| 543 | self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len(); |
| 544 | let whole = display_size == self.coded_size; |
| 545 | let vpp = self.vpp()?; |
| 546 | if whole { |
| 547 | Ok(vpp.convert(source, dest)?) |
| 548 | } else { |
| 549 | let rect = (0, 0, display_size.0, display_size.1); |
| 550 | Ok(vpp.convert_region(source, rect, dest, rect)?) |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | |
| 555 | |
| 556 | fn encode_settled<D: SurfaceMemoryDescriptor>( |
| 557 | &mut self, |
| 558 | source: Rc<ec_va::va::Surface<D>>, |
| 559 | meta: FrameMetadata, |
| 560 | ) -> Result<CodedFrame> { |
| 561 | let in_flight = self.submit_settled(source, meta, Vec::new())?; |
| 562 | self.finish(in_flight) |
| 563 | } |
| 564 | |
| 565 | fn submit_settled<D: SurfaceMemoryDescriptor>( |
| 566 | &mut self, |
| 567 | source: Rc<ec_va::va::Surface<D>>, |
| 568 | meta: FrameMetadata, |
| 569 | mut leases: Vec<Rc<PooledSurface>>, |
| 570 | ) -> Result<InFlight<D>> { |
| 571 | if crate::reset::gpu_reset_epoch() != self.born_epoch { |
| 572 | return Err(Error::hw_reset( |
| 573 | "the GPU was reset after this encoder was created; its context is lost", |
| 574 | )); |
| 575 | } |
| 576 | let keyframe = meta.force_keyframe |
| 577 | || self.reference.is_none() |
| 578 | || self.gop_position >= self.config.gop_size.max(1); |
| 579 | |
| 580 | let recon = self |
| 581 | .pool |
| 582 | .acquire() |
| 583 | .ok_or_else(|| Error::config("encode: no surface for the reconstruction"))?; |
| 584 | |
| 585 | |
| 586 | |
| 587 | let coded_bytes_len = (self.coded_size.0 * self.coded_size.1 * 3 / 4).max(1 << 20); |
| 588 | let coded = ec_va::error::va_ok( |
| 589 | "vaCreateBuffer", |
| 590 | self.context.create_enc_coded(coded_bytes_len as usize), |
| 591 | )?; |
| 592 | |
| 593 | let mut params = Vec::new(); |
| 594 | match self.config.codec { |
| 595 | EncCodec::H264 => h264::parameters(self, &recon, coded.id(), keyframe, &mut params)?, |
| 596 | EncCodec::H265 => hevc::parameters(self, &recon, coded.id(), keyframe, &mut params)?, |
| 597 | EncCodec::Av1 => av1::parameters(self, &recon, coded.id(), keyframe, &mut params)?, |
| 598 | } |
| 599 | params.extend(self.rate_control_buffers()?); |
| 600 | let mut buffers = Vec::with_capacity(params.len()); |
| 601 | for ty in params { |
| 602 | buffers.push(ec_va::picture::buffer(&self.context, ty)?); |
| 603 | } |
| 604 | |
| 605 | let picture = ec_va::picture::submit(&self.context, Rc::clone(&source), buffers)?; |
| 606 | if let Some(previous) = self.reference.replace(recon) { |
| 607 | leases.push(previous); |
| 608 | } |
| 609 | if keyframe { |
| 610 | self.idr_count = self.idr_count.wrapping_add(1); |
| 611 | } |
| 612 | self.gop_position = if keyframe { 1 } else { self.gop_position + 1 }; |
| 613 | Ok(InFlight { |
| 614 | picture, |
| 615 | coded, |
| 616 | source, |
| 617 | leases, |
| 618 | timestamp: meta.timestamp, |
| 619 | keyframe, |
| 620 | }) |
| 621 | } |
| 622 | |
| 623 | fn finish<D: SurfaceMemoryDescriptor>(&mut self, f: InFlight<D>) -> Result<CodedFrame> { |
| 624 | crate::reset::sync_watched(&f.source)?; |
| 625 | let InFlight { |
| 626 | picture, |
| 627 | coded, |
| 628 | leases, |
| 629 | timestamp, |
| 630 | keyframe, |
| 631 | .. |
| 632 | } = f; |
| 633 | drop(picture); |
| 634 | |
| 635 | let mut data = { |
| 636 | let mapped = ec_va::error::va_ok( |
| 637 | "vaMapBuffer", |
| 638 | ec_va::picture::MappedCodedBuffer::new(&coded), |
| 639 | )?; |
| 640 | let mut out = Vec::new(); |
| 641 | for segment in mapped.segments() { |
| 642 | out.extend_from_slice(segment.buf); |
| 643 | } |
| 644 | out |
| 645 | }; |
| 646 | if data.is_empty() { |
| 647 | return Err(Error::config("the encoder produced an empty coded buffer")); |
| 648 | } |
| 649 | self.track_rate(data.len()); |
| 650 | if self.config.codec == EncCodec::Av1 { |
| 651 | |
| 652 | |
| 653 | |
| 654 | |
| 655 | |
| 656 | data.splice(0..0, [0x12u8, 0x00]); |
| 657 | } |
| 658 | drop(coded); |
| 659 | drop(leases); |
| 660 | Ok(CodedFrame { |
| 661 | data, |
| 662 | timestamp, |
| 663 | is_keyframe: keyframe, |
| 664 | recovery: false, |
| 665 | }) |
| 666 | } |
| 667 | |
| 668 | fn steered_bitrate(&self) -> u32 { |
| 669 | self.rc.steered_bitrate(self.tunings.bitrate) |
| 670 | } |
| 671 | |
| 672 | fn track_rate(&mut self, bytes: usize) { |
| 673 | if self.rc.track(bytes, self.config.rate_control, self.tunings) { |
| 674 | self.tunings_dirty = true; |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | |
| 679 | fn rate_control_buffers(&mut self) -> Result<Vec<BufferType>> { |
| 680 | if !self.tunings_dirty { |
| 681 | return Ok(Vec::new()); |
| 682 | } |
| 683 | self.tunings_dirty = false; |
| 684 | |
| 685 | |
| 686 | |
| 687 | let (initial_qp, min_qp, max_qp, bits, target, quality) = match self.config.rate_control { |
| 688 | RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0, 100, 0), |
| 689 | RateControlMode::ConstantBitrate => (0, 0, 0, self.steered_bitrate(), 100, 0), |
| 690 | RateControlMode::VariableBitrate => { |
| 691 | (0, 0, 0, self.steered_bitrate().saturating_mul(3) / 2, 66, 0) |
| 692 | } |
| 693 | RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality), |
| 694 | }; |
| 695 | let rc_flags = RcFlags::new(0, 0, 0, 0, 0, 0, 0, 0, 0); |
| 696 | let mut out = vec![BufferType::EncMiscParameter(EncMiscParameter::RateControl( |
| 697 | EncMiscParameterRateControl::new( |
| 698 | bits, |
| 699 | target, |
| 700 | RATE_WINDOW_MS, |
| 701 | initial_qp, |
| 702 | min_qp, |
| 703 | 0, |
| 704 | rc_flags, |
| 705 | 0, |
| 706 | max_qp, |
| 707 | quality, |
| 708 | 0, |
| 709 | ), |
| 710 | ))]; |
| 711 | |
| 712 | |
| 713 | let num = self.tunings.framerate.0.max(1); |
| 714 | let den = self.tunings.framerate.1.max(1); |
| 715 | let packed = if den <= 1 { |
| 716 | num |
| 717 | } else { |
| 718 | (den << 16) | (num & 0xffff) |
| 719 | }; |
| 720 | out.push(BufferType::EncMiscParameter(EncMiscParameter::FrameRate( |
| 721 | EncMiscParameterFrameRate::new(packed, 0), |
| 722 | ))); |
| 723 | if self.config.quality > 0 { |
| 724 | out.push(BufferType::EncMiscParameter(EncMiscParameter::QualityLevel( |
| 725 | EncMiscParameterBufferQualityLevel::new(self.config.quality), |
| 726 | ))); |
| 727 | } |
| 728 | if bits > 0 && !self.rc.take_steered() { |
| 729 | |
| 730 | |
| 731 | |
| 732 | |
| 733 | let buffer_ms = u64::from(hrd_buffer_ms(&self.config)); |
| 734 | let hrd_bits = (u64::from(bits) * buffer_ms / 1000) as u32; |
| 735 | out.push(BufferType::EncMiscParameter(EncMiscParameter::HRD( |
| 736 | EncMiscParameterHRD::new(hrd_bits, hrd_bits), |
| 737 | ))); |
| 738 | } |
| 739 | Ok(out) |
| 740 | } |
| 741 | |
| 742 | |
| 743 | |
| 744 | |
| 745 | |
| 746 | pub(crate) fn push_packed( |
| 747 | &self, |
| 748 | packed: &headers::Packed, |
| 749 | out: &mut Vec<BufferType>, |
| 750 | ) -> Result<()> { |
| 751 | let kind = match packed.kind { |
| 752 | headers::PACKED_HEADER_SEQUENCE => EncPackedHeaderType::Sequence, |
| 753 | headers::PACKED_HEADER_PICTURE => EncPackedHeaderType::Picture, |
| 754 | headers::PACKED_HEADER_SLICE => EncPackedHeaderType::Slice, |
| 755 | other => { |
| 756 | return Err(Error::config(format!("unknown packed header kind {other}"))); |
| 757 | } |
| 758 | }; |
| 759 | out.push(BufferType::EncPackedHeaderParameter( |
| 760 | EncPackedHeaderParameter::new(kind, packed.bits, true), |
| 761 | )); |
| 762 | out.push(BufferType::EncPackedHeaderData(packed.bytes.clone())); |
| 763 | Ok(()) |
| 764 | } |
| 765 | |
| 766 | pub(crate) fn context(&self) -> &Rc<Context> { |
| 767 | &self.context |
| 768 | } |
| 769 | |
| 770 | pub(crate) fn config(&self) -> &EncoderConfig { |
| 771 | &self.config |
| 772 | } |
| 773 | |
| 774 | pub(crate) fn reference(&self) -> Option<&Rc<PooledSurface>> { |
| 775 | self.reference.as_ref() |
| 776 | } |
| 777 | |
| 778 | pub(crate) fn gop_position(&self) -> u32 { |
| 779 | self.gop_position |
| 780 | } |
| 781 | |
| 782 | |
| 783 | |
| 784 | pub(crate) fn idr_count(&self) -> u32 { |
| 785 | self.idr_count |
| 786 | } |
| 787 | |
| 788 | |
| 789 | pub fn profile(&self) -> Profile { |
| 790 | self.profile |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | |
| 795 | fn surface_spec(bit_depth: u8, size: (u32, u32)) -> SurfaceSpec { |
| 796 | let spec = if bit_depth == 10 { |
| 797 | SurfaceSpec::p010(size.0, size.1) |
| 798 | } else { |
| 799 | SurfaceSpec::nv12(size.0, size.1) |
| 800 | }; |
| 801 | spec.with_usage_hint(VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER) |
| 802 | } |
| 803 | |
| 804 | |
| 805 | fn fourcc(bit_depth: u8) -> u32 { |
| 806 | if bit_depth == 10 { |
| 807 | VA_FOURCC_P010 |
| 808 | } else { |
| 809 | VA_FOURCC_NV12 |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | |
| 814 | |
| 815 | |
| 816 | |
| 817 | |
| 818 | fn write_surface<D: SurfaceMemoryDescriptor>( |
| 819 | display: &Display, |
| 820 | surface: &ec_va::va::Surface<D>, |
| 821 | fourcc: u32, |
| 822 | size: (u32, u32), |
| 823 | fill: impl FnOnce(&VAImage, &mut [u8]), |
| 824 | ) -> Result<()> { |
| 825 | if let Ok(mut image) = ec_va::va::Image::derive_from(surface, size) |
| 826 | && image.image().format.fourcc == fourcc |
| 827 | { |
| 828 | let layout = *image.image(); |
| 829 | fill(&layout, AsMut::<[u8]>::as_mut(&mut image)); |
| 830 | return Ok(()); |
| 831 | } |
| 832 | let format = ec_va::surface::image_format(display, fourcc)?; |
| 833 | let mut image = ec_va::surface::create_image(surface, format, size, size)?; |
| 834 | let layout = *image.image(); |
| 835 | fill(&layout, AsMut::<[u8]>::as_mut(&mut image)); |
| 836 | Ok(()) |
| 837 | } |
| 838 | |
| 839 | |
| 840 | fn upload(context: &Rc<Context>, frame: &I420, surface: &Surface, coded: (u32, u32)) -> Result<()> { |
| 841 | let display: &Display = context.display(); |
| 842 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 843 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 844 | write_surface(display, surface, VA_FOURCC_NV12, coded, |layout, data| { |
| 845 | let y_pitch = layout.pitches[0] as usize; |
| 846 | let uv_pitch = layout.pitches[1] as usize; |
| 847 | let y_base = layout.offsets[0] as usize; |
| 848 | let uv_base = layout.offsets[1] as usize; |
| 849 | |
| 850 | |
| 851 | for row in 0..h { |
| 852 | let d = y_base + row * y_pitch; |
| 853 | if let Some(dst) = data.get_mut(d..d + w) { |
| 854 | dst.copy_from_slice(&frame.y[row * w..row * w + w]); |
| 855 | } else { |
| 856 | break; |
| 857 | } |
| 858 | } |
| 859 | for row in 0..ch { |
| 860 | let d = uv_base + row * uv_pitch; |
| 861 | let Some(dst) = data.get_mut(d..d + cw * 2) else { |
| 862 | break; |
| 863 | }; |
| 864 | for col in 0..cw { |
| 865 | dst[col * 2] = frame.u[row * cw + col]; |
| 866 | dst[col * 2 + 1] = frame.v[row * cw + col]; |
| 867 | } |
| 868 | } |
| 869 | }) |
| 870 | } |
| 871 | |
| 872 | |
| 873 | |
| 874 | |
| 875 | |
| 876 | fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> { |
| 877 | write_surface(display, surface, fourcc(bit_depth), size, |layout, data| { |
| 878 | |
| 879 | |
| 880 | let samples = |eight: u8| -> Vec<u8> { |
| 881 | if bit_depth == 8 { |
| 882 | vec![eight] |
| 883 | } else { |
| 884 | (u16::from(eight) << 6).to_le_bytes().to_vec() |
| 885 | } |
| 886 | }; |
| 887 | for (plane, value, rows) in [ |
| 888 | (0usize, 16u8, size.1 as usize), |
| 889 | (1, 128, size.1 as usize / 2), |
| 890 | ] { |
| 891 | let pitch = layout.pitches[plane] as usize; |
| 892 | let base = layout.offsets[plane] as usize; |
| 893 | let unit = samples(value); |
| 894 | let width = size.0 as usize * unit.len(); |
| 895 | for row in 0..rows { |
| 896 | let start = base + row * pitch; |
| 897 | if let Some(line) = data.get_mut(start..start + width) { |
| 898 | for px in line.chunks_exact_mut(unit.len()) { |
| 899 | px.copy_from_slice(&unit); |
| 900 | } |
| 901 | } |
| 902 | } |
| 903 | } |
| 904 | }) |
| 905 | } |
| 906 | |
| 907 | fn fill_zero(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> { |
| 908 | write_surface(display, surface, fourcc(bit_depth), size, |_, data| { |
| 909 | data.fill(0) |
| 910 | }) |
| 911 | } |
| 912 | |
| 913 | fn zero_padding<D: SurfaceMemoryDescriptor>( |
| 914 | display: &Display, |
| 915 | surface: &ec_va::va::Surface<D>, |
| 916 | bit_depth: u8, |
| 917 | (w, h): (u32, u32), |
| 918 | coded: (u32, u32), |
| 919 | ) -> Result<()> { |
| 920 | if (w, h) == coded { |
| 921 | return Ok(()); |
| 922 | } |
| 923 | let (fourcc, px) = if bit_depth > 8 { |
| 924 | (VA_FOURCC_P010, 2) |
| 925 | } else { |
| 926 | (VA_FOURCC_NV12, 1) |
| 927 | }; |
| 928 | let (w, h, cw, ch) = ( |
| 929 | w as usize * px, |
| 930 | h as usize, |
| 931 | coded.0 as usize * px, |
| 932 | coded.1 as usize, |
| 933 | ); |
| 934 | write_surface(display, surface, fourcc, coded, |layout, data| { |
| 935 | for (plane, rows, last, start) in [ |
| 936 | (0, h, ch, w), |
| 937 | (1, h.div_ceil(2), ch / 2, w.next_multiple_of(2 * px)), |
| 938 | ] { |
| 939 | let pitch = layout.pitches[plane] as usize; |
| 940 | let base = layout.offsets[plane] as usize; |
| 941 | for row in 0..last { |
| 942 | let from = if row < rows { start } else { 0 }; |
| 943 | if let Some(dst) = data.get_mut(base + row * pitch + from..base + row * pitch + cw) |
| 944 | { |
| 945 | dst.fill(0); |
| 946 | } |
| 947 | } |
| 948 | } |
| 949 | }) |
| 950 | } |
| 951 | |
| 952 | |
| 953 | |
| 954 | fn upload_16( |
| 955 | context: &Rc<Context>, |
| 956 | frame: &I420_16, |
| 957 | surface: &Surface, |
| 958 | coded: (u32, u32), |
| 959 | ) -> Result<()> { |
| 960 | let display: &Display = context.display(); |
| 961 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 962 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 963 | write_surface(display, surface, VA_FOURCC_P010, coded, |layout, data| { |
| 964 | let y_pitch = layout.pitches[0] as usize; |
| 965 | let uv_pitch = layout.pitches[1] as usize; |
| 966 | let y_base = layout.offsets[0] as usize; |
| 967 | let uv_base = layout.offsets[1] as usize; |
| 968 | for row in 0..h { |
| 969 | let d = y_base + row * y_pitch; |
| 970 | let Some(dst) = data.get_mut(d..d + w * 2) else { |
| 971 | break; |
| 972 | }; |
| 973 | for col in 0..w { |
| 974 | let v = (frame.y[row * w + col] & 0x3ff) << 6; |
| 975 | dst[col * 2..col * 2 + 2].copy_from_slice(&v.to_le_bytes()); |
| 976 | } |
| 977 | } |
| 978 | for row in 0..ch { |
| 979 | let d = uv_base + row * uv_pitch; |
| 980 | let Some(dst) = data.get_mut(d..d + cw * 4) else { |
| 981 | break; |
| 982 | }; |
| 983 | for col in 0..cw { |
| 984 | let u = (frame.u[row * cw + col] & 0x3ff) << 6; |
| 985 | let v = (frame.v[row * cw + col] & 0x3ff) << 6; |
| 986 | dst[col * 4..col * 4 + 2].copy_from_slice(&u.to_le_bytes()); |
| 987 | dst[col * 4 + 2..col * 4 + 4].copy_from_slice(&v.to_le_bytes()); |
| 988 | } |
| 989 | } |
| 990 | }) |
| 991 | } |
| 992 | |
| 993 | #[cfg(test)] |
| 994 | mod tests { |
| 995 | use super::*; |
| 996 | |
| 997 | #[test] |
| 998 | fn default_profile_is_high() { |
| 999 | assert_eq!(H264Profile::default(), H264Profile::High); |
| 1000 | } |
| 1001 | } |