Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ Based on the information above, there are several optimizations and changes made

#### Issue

* vaapi: only tested on intel with `va-driver-all`, and hevc_vaapi encoding not supported on my pc
* remove hevc_vaapi because of possible poor quality
* VAAPI H.264 and HEVC discovery tries CBR first, then CQP if initialization or the test frame fails. Only an encoder that produces a keyframe within the probe timeout is reported.
* `CodecInfo.rc` records the tested mode as `["CBR"]` or `["CQP"]`. The field is omitted for other backends; older records without it still deserialize.
* VAAPI HEVC support and CBR image quality depend on the driver and hardware; verify desktop text and detail on a supported device before relying on it.
* amf: not tested, https://github.com/GPUOpen-LibrariesAndSDKs/AMF/issues/378

### MacOS
Expand Down
16 changes: 15 additions & 1 deletion cpp/common/util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
{"mediacodec",
"bitrate_mode",
{{RC_CBR, "cbr"}, {RC_VBR, "vbr"}, {RC_CQ, "cq"}}},
{"vaapi", "rc_mode", {{RC_CBR, "CBR"}, {RC_CQ, "CQP"}}},
// {"videotoolbox", "constant_bit_rate", {{RC_CBR, "1"}}},
};

Expand All @@ -235,6 +236,19 @@ bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
}
}
}
if (name.find("vaapi") != std::string::npos && rc == RC_CQ) {
constexpr int default_qp = 23;
// FFmpeg treats qp = 0 as unspecified, not as an explicit QP.
// Negative values are also unspecified in EncodeContext. Positive
// values are validated by the codec-specific FFmpeg option.
const int qp = q > 0 ? q : default_qp;
ret = av_opt_set_int(c->priv_data, "qp", qp, 0);
if (ret < 0) {
LOG_ERROR(std::string("vaapi set opt qp failed, ret = ") +
av_err2str(ret));
return false;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
}
break;
}
Expand Down Expand Up @@ -330,4 +344,4 @@ bool has_flag_could_not_find_ref_with_poc() {

extern "C" void hwcodec_set_flag_could_not_find_ref_with_poc() {
util_decode::g_flag_could_not_find_ref_with_poc = true;
}
}
7 changes: 5 additions & 2 deletions cpp/ffmpeg_ram/ffmpeg_ram_encode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,10 @@ class FFmpegRamEncoder {
return false;
}
// util_encode::set_quality(c_->priv_data, name_, quality_);
util_encode::set_rate_control(c_, name_, rc_, q_);
if (!util_encode::set_rate_control(c_, name_, rc_, q_) &&
name_.find("vaapi") != std::string::npos) {
return false;
}
util_encode::set_gpu(c_->priv_data, name_, gpu_);
util_encode::force_hw(c_->priv_data, name_);
util_encode::set_others(c_->priv_data, name_);
Expand Down Expand Up @@ -463,4 +466,4 @@ extern "C" int ffmpeg_ram_set_bitrate(FFmpegRamEncoder *encoder, int kbs) {
LOG_ERROR(std::string("ffmpeg_ram_set_bitrate failed, ") + std::string(e.what()));
}
return -1;
}
}
27 changes: 27 additions & 0 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,33 @@
use serde_derive::{Deserialize, Serialize};
include!(concat!(env!("OUT_DIR"), "/common_ffi.rs"));

impl serde::Serialize for RateControl {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(match self {
Self::RC_DEFAULT => "DEFAULT",
Self::RC_CBR => "CBR",
Self::RC_VBR => "VBR",
Self::RC_CQ => "CQP",
})
}
}

impl<'de> serde::Deserialize<'de> for RateControl {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = <String as serde::Deserialize>::deserialize(deserializer)?;
match value.as_str() {
"DEFAULT" | "RC_DEFAULT" => Ok(Self::RC_DEFAULT),
"CBR" | "RC_CBR" => Ok(Self::RC_CBR),
"VBR" | "RC_VBR" => Ok(Self::RC_VBR),
"CQP" | "RC_CQ" => Ok(Self::RC_CQ),
_ => Err(serde::de::Error::unknown_variant(
&value,
&["DEFAULT", "CBR", "VBR", "CQP"],
)),
}
}
}

pub(crate) const DATA_H264_720P: &[u8] = include_bytes!("res/720p.h264");
pub(crate) const DATA_H265_720P: &[u8] = include_bytes!("res/720p.h265");

Expand Down
92 changes: 83 additions & 9 deletions src/ffmpeg_ram/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,13 +254,12 @@ impl Encoder {
priority: Priority::Good as _,
..Default::default()
});
// remove because poor quality on one of my computer
// codecs.push(CodecInfo {
// name: "hevc_vaapi".to_owned(),
// format: H265,
// priority: Priority::Good as _,
// ..Default::default()
// });
codecs.push(CodecInfo {
name: "hevc_vaapi".to_owned(),
format: H265,
priority: Priority::Good as _,
..Default::default()
});
}
}

Expand Down Expand Up @@ -315,13 +314,23 @@ impl Encoder {
..ctx
};

if codec.name.contains("vaapi") {
if let Some(rc) = Self::probe_vaapi(&c, &yuv) {
let mut codec = codec;
codec.rc.push(rc);
res.push(codec);
}
continue;
}

match Encoder::new(c) {
Ok(mut encoder) => {
debug!("Encoder {} created successfully", codec.name);
let mut passed = false;
let mut last_err: Option<i32> = None;

let max_attempts = if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
let max_attempts = if cfg!(all(target_os = "macos", target_arch = "x86_64"))
{
3
} else {
1
Expand All @@ -337,7 +346,8 @@ impl Encoder {
if frames[0].key == 1 && elapsed < TEST_TIMEOUT_MS as _ {
debug!(
"Encoder {} test passed on attempt {}",
codec.name, attempt + 1
codec.name,
attempt + 1
);
res.push(codec.clone());
passed = true;
Expand Down Expand Up @@ -394,6 +404,25 @@ impl Encoder {
res
}

fn probe_vaapi(ctx: &EncodeContext, yuv: &[u8]) -> Option<RateControl> {
probe_vaapi_modes(|rc| {
log::debug!("Testing encoder {} with {:?}", ctx.name, rc);
if let Ok(mut encoder) = Self::new(EncodeContext { rc, ..ctx.clone() }) {
let start = std::time::Instant::now();
if let Ok(frames) = encoder.encode(yuv, 0) {
if frames.len() == 1
&& frames[0].key == 1
&& start.elapsed().as_millis() < TEST_TIMEOUT_MS as _
{
return true;
}
}
}
log::debug!("Encoder {} test failed with {:?}", ctx.name, rc);
false
})
}

fn dummy_yuv(ctx: EncodeContext) -> Result<Vec<u8>, ()> {
let mut yuv = vec![];
if let Ok((_, _, len)) = ffmpeg_linesize_offset_length(
Expand All @@ -420,3 +449,48 @@ impl Drop for Encoder {
}
}
}

// Prefer a working CBR encoder; only probe CQP after the CBR encode test fails.
fn probe_vaapi_modes(mut probe: impl FnMut(RateControl) -> bool) -> Option<RateControl> {
[RateControl::RC_CBR, RateControl::RC_CQ]
.into_iter()
.find(|&rc| probe(rc))
}

#[cfg(test)]
mod vaapi_tests {
use super::*;

#[test]
fn working_cbr_does_not_probe_cqp() {
let mut attempted = Vec::new();
let mode = probe_vaapi_modes(|rc| {
attempted.push(rc);
true
});
assert_eq!(mode, Some(RateControl::RC_CBR));
assert_eq!(attempted, [RateControl::RC_CBR]);
}

#[test]
fn failed_cbr_falls_back_to_cqp() {
let mut attempted = Vec::new();
let mode = probe_vaapi_modes(|rc| {
attempted.push(rc);
rc == RateControl::RC_CQ
});
assert_eq!(mode, Some(RateControl::RC_CQ));
assert_eq!(attempted, [RateControl::RC_CBR, RateControl::RC_CQ]);
}

#[test]
fn unsupported_encoder_is_not_reported() {
let mut attempted = Vec::new();
let mode = probe_vaapi_modes(|rc| {
attempted.push(rc);
false
});
assert_eq!(mode, None);
assert_eq!(attempted, [RateControl::RC_CBR, RateControl::RC_CQ]);
}
}
48 changes: 44 additions & 4 deletions src/ffmpeg_ram/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]

use crate::common::DataFormat::{self, *};
use crate::ffmpeg::{
AVHWDeviceType::{self, *},
AVPixelFormat,
use crate::{
common::{
DataFormat::{self, *},
RateControl,
},
ffmpeg::{
AVHWDeviceType::{self, *},
AVPixelFormat,
},
};
use serde_derive::{Deserialize, Serialize};
use std::ffi::c_int;
Expand All @@ -31,6 +36,8 @@ pub struct CodecInfo {
pub format: DataFormat,
pub priority: i32,
pub hwdevice: AVHWDeviceType,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rc: Vec<RateControl>,
}

impl Default for CodecInfo {
Expand All @@ -41,6 +48,7 @@ impl Default for CodecInfo {
format: DataFormat::H264,
priority: Default::default(),
hwdevice: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
rc: Vec::new(),
}
}
}
Expand Down Expand Up @@ -114,13 +122,15 @@ impl CodecInfo {
format: H264,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
..Default::default()
}),
h265: Some(CodecInfo {
name: "hevc".to_owned(),
mc_name: Default::default(),
format: H265,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
..Default::default()
}),
vp8: None,
vp9: None,
Expand Down Expand Up @@ -183,3 +193,33 @@ pub fn ffmpeg_linesize_offset_length(

Err(())
}

#[cfg(test)]
mod tests {
use super::*;
use crate::common::RateControl::{RC_CBR, RC_CQ};

#[test]
fn codec_info_rate_control_serialization() {
let mut codec = CodecInfo::soft().h264.unwrap();
let legacy = serde_json::to_value(&codec).unwrap();
assert!(legacy.get("rc").is_none());
assert!(serde_json::from_value::<CodecInfo>(legacy)
.unwrap()
.rc
.is_empty());

codec.name = "h264_vaapi".into();
for (rc, name, legacy_name) in [(RC_CBR, "CBR", "RC_CBR"), (RC_CQ, "CQP", "RC_CQ")] {
codec.rc = vec![rc];
let mut value = serde_json::to_value(&codec).unwrap();
assert_eq!(value["rc"], serde_json::json!([name]));
assert_eq!(
serde_json::from_value::<CodecInfo>(value.clone()).unwrap(),
codec
);
value["rc"] = serde_json::json!([legacy_name]);
assert_eq!(serde_json::from_value::<CodecInfo>(value).unwrap(), codec);
}
}
}
Loading