blob: 040188c48521dbd0144863ceec9fc650732fbc83 [file]
/*
* Copyright (c) 2026 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/video_coding/rate_control/buffer_level_rate_controller.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <utility>
#include <variant>
#include <vector>
#include "absl/container/inlined_vector.h"
#include "api/media_stream_interface.h"
#include "api/scoped_refptr.h"
#include "api/units/data_rate.h"
#include "api/units/data_size.h"
#include "api/units/time_delta.h"
#include "api/units/timestamp.h"
#include "api/video/i420_buffer.h"
#include "api/video/resolution.h"
#include "api/video/video_frame_buffer.h"
#include "api/video_codecs/buffer_level_rate_controller_config.h"
#include "api/video_codecs/buffer_level_rate_controller_factory.h"
#include "api/video_codecs/video_encoder_interface.h"
#include "api/video_codecs/video_rate_controller.h"
#include "rtc_base/checks.h"
#include "test/gmock.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
using ::testing::AllOf;
using ::testing::DoubleNear;
using ::testing::Ge;
using ::testing::Gt;
using ::testing::Le;
using ::testing::Lt;
using ::testing::SizeIs;
using ContentHint = VideoTrackInterface::ContentHint;
using DropFrame = VideoRateController::DropFrame;
using EncodeFrame = VideoRateController::EncodeFrame;
using EncodedFrameStats = VideoRateController::EncodedFrameStats;
using FrameEncodeSettings = VideoEncoderInterface::FrameEncodeSettings;
using FramePlan = VideoRateController::FramePlan;
using FrameType = VideoEncoderInterface::FrameType;
using TemporalUnitSettings = VideoEncoderInterface::TemporalUnitSettings;
using Verdict = VideoRateController::Verdict;
using LayerBitrates =
absl::InlinedVector<DataRate,
BufferLevelRateController::kMaxTemporalLayers>;
constexpr Resolution kResolution = {.width = 640, .height = 360};
LayerBitrates SingleLayer(DataRate bitrate) {
return {bitrate};
}
// Non-cumulative per-layer bitrates for L1T3 where each layer stream has twice
// the rate per frame of the one below it: the base layer gets half of the
// bitrate, each enhancement layer a quarter.
LayerBitrates ThreeLayers(DataRate bitrate) {
return {bitrate * 0.5, bitrate * 0.25, bitrate * 0.25};
}
int TemporalIdOf(int frame_index, int num_temporal_layers) {
if (num_temporal_layers == 1) {
return 0;
}
return frame_index % 4 == 0 ? 0 : (frame_index % 2 == 0 ? 1 : 2);
}
FrameEncodeSettings MakeFrameSettings(
FrameType frame_type = FrameType::kDeltaFrame,
int temporal_id = 0,
Resolution resolution = kResolution) {
FrameEncodeSettings settings;
settings.set_frame_type(frame_type);
settings.set_temporal_id(temporal_id);
settings.set_resolution(resolution);
return settings;
}
const EncodeFrame& AsEncode(const FramePlan& plan) {
RTC_CHECK(std::holds_alternative<EncodeFrame>(plan.decision));
return std::get<EncodeFrame>(plan.decision);
}
bool IsDrop(const FramePlan& plan) {
return std::holds_alternative<DropFrame>(plan.decision);
}
// Produces reusable solid-luma I420 frames so tests can drive `SceneAnalyzer`
// with exact per-pixel luma steps (`mean_abs_diff`) and scene jumps.
class SyntheticFrameSource {
public:
VideoFrameBuffer* FrameWithLuma(Resolution res, uint8_t luma) {
Key key = {.width = res.width, .height = res.height, .luma = luma};
auto it = cache_.find(key);
if (it != cache_.end()) {
return it->second.get();
}
scoped_refptr<I420Buffer> buf = I420Buffer::Create(res.width, res.height);
std::memset(buf->MutableDataY(), luma,
static_cast<size_t>(buf->StrideY()) * res.height);
std::memset(buf->MutableDataU(), 128,
static_cast<size_t>(buf->StrideU()) * ((res.height + 1) / 2));
std::memset(buf->MutableDataV(), 128,
static_cast<size_t>(buf->StrideV()) * ((res.height + 1) / 2));
VideoFrameBuffer* ptr = buf.get();
cache_.emplace(key, std::move(buf));
return ptr;
}
private:
struct Key {
int width;
int height;
uint8_t luma;
bool operator<(const Key& other) const {
if (width != other.width)
return width < other.width;
if (height != other.height)
return height < other.height;
return luma < other.luma;
}
};
std::map<Key, scoped_refptr<I420Buffer>> cache_;
};
// Frame sizes that follow the shape of a bits per macroblock model,
// complexity * macroblocks / quantizer step, with a quantizer step that is
// linear in the QP up to 100 and exponential above, a smooth approximation
// rather than the curve the controller uses.
class SyntheticEncoder {
public:
void set_complexity(double complexity) { complexity_ = complexity; }
DataSize Encode(int qp,
Resolution resolution,
FrameType frame_type,
int temporal_id) const {
const double num_mbs = std::ceil(resolution.width / 16.0) *
std::ceil(resolution.height / 16.0);
const double qstep =
qp < 100 ? (4.0 + qp) / 4
: 26 * std::exp((qp - 100) * std::log(1828.0 / 104) / 155);
double bits = complexity_ * 2000 * num_mbs / qstep;
if (frame_type != FrameType::kDeltaFrame) {
bits *= 3;
} else if (temporal_id == 0) {
bits *= 1.5;
} else if (temporal_id == 1) {
bits *= 1.2;
}
return DataSize::Bytes(std::llround(bits / 8));
}
private:
double complexity_ = 1.0;
};
struct FrameResult {
FramePlan plan;
FrameType frame_type = FrameType::kDeltaFrame;
int temporal_id = 0;
TimeDelta duration = TimeDelta::Zero();
DataSize encoded_size = DataSize::Zero();
int qp() const { return AsEncode(plan).qp; }
DataSize target_size() const { return AsEncode(plan).target_size; }
bool dropped() const { return IsDrop(plan); }
};
// Drives a controller with frames from a `SyntheticEncoder`.
class Harness {
public:
explicit Harness(const BufferLevelRateControllerConfig& config = {})
: controller_(
BufferLevelRateControllerFactory(config).CreateRateController()) {}
VideoRateController& controller() { return *controller_; }
SyntheticEncoder& encoder() { return encoder_; }
void SetStream(const LayerBitrates& layer_bitrates,
double fps,
ContentHint content_hint = ContentHint::kNone,
Resolution resolution = kResolution) {
layer_bitrates_ = layer_bitrates;
duration_ = TimeDelta::Seconds(1) / fps;
content_hint_ = content_hint;
resolution_ = resolution;
}
// Configures synthetic input frames with a per-frame luma step (`delta`), or
// disables input frames when `std::nullopt`.
void SetMotionStep(std::optional<uint8_t> step) { luma_step_ = step; }
// Triggers a single large luma jump on the next frame, then continues from
// the new luma level.
void TriggerSceneJump(uint8_t jump = 120) {
current_luma_ = static_cast<uint8_t>((current_luma_ + jump) % 256);
if (std::abs(static_cast<int>(current_luma_) - last_fed_luma_) < 80) {
current_luma_ = static_cast<uint8_t>(current_luma_ ^ 0x80);
}
pending_jump_ = true;
}
void AdvanceTime(TimeDelta delta) { current_timestamp_ += delta; }
int NextTemporalId() const {
return TemporalIdOf(frame_index_, static_cast<int>(layer_bitrates_.size()));
}
FramePlan StartNextFrame(
FrameType frame_type = FrameType::kDeltaFrame,
std::optional<Resolution> resolution_override = std::nullopt) {
if (frame_index_ == 0 && frame_type == FrameType::kDeltaFrame) {
frame_type = FrameType::kKeyframe;
}
const int tid = NextTemporalId();
const Resolution res = resolution_override.value_or(resolution_);
VideoFrameBuffer* frame_buf = NextFrameBuffer(res);
last_frame_type_ = frame_type;
last_tid_ = tid;
last_resolution_ = res;
const TemporalUnitSettings tu_settings(content_hint_, current_timestamp_);
const FrameEncodeSettings frame_settings =
MakeFrameSettings(frame_type, tid, res);
const FramePlan plan =
controller_->PlanFrame({.target_bitrate = layer_bitrates_[tid],
.duration = duration_,
.tu_settings = tu_settings,
.frame_settings = frame_settings,
.frame_buffer = frame_buf});
return plan;
}
FrameResult FinishEncode(const FramePlan& plan) {
const EncodeFrame& encode = AsEncode(plan);
const DataSize size = encoder_.Encode(encode.qp, last_resolution_,
last_frame_type_, last_tid_);
controller_->OnFrameEncoded(plan.id,
{.encoded_size = size, .qp = encode.qp});
++frame_index_;
current_timestamp_ += duration_;
return {.plan = plan,
.frame_type = last_frame_type_,
.temporal_id = last_tid_,
.duration = duration_,
.encoded_size = size};
}
FrameResult EncodeNextFrame(FrameType frame_type = FrameType::kDeltaFrame) {
const FramePlan plan = StartNextFrame(frame_type);
return FinishEncode(plan);
}
void DropNextFrame() {
const FramePlan plan = StartNextFrame();
controller_->OnFrameDropped(plan.id, std::nullopt);
++frame_index_;
current_timestamp_ += duration_;
}
// Follows the advice of `PlanFrame`, returning a zero size for dropped
// frames.
FrameResult EncodeOrDropNextFrame() {
const FramePlan plan = StartNextFrame();
if (IsDrop(plan)) {
controller_->OnFrameDropped(plan.id, std::nullopt);
++frame_index_;
current_timestamp_ += duration_;
return {.plan = plan,
.frame_type = last_frame_type_,
.temporal_id = last_tid_,
.duration = duration_,
.encoded_size = DataSize::Zero()};
}
return FinishEncode(plan);
}
// Reports that the encode of `plan` with `size` was discarded.
void DiscardEncode(const FramePlan& plan, DataSize size) {
const EncodeFrame& encode = AsEncode(plan);
controller_->OnFrameDropped(
plan.id, EncodedFrameStats{.encoded_size = size, .qp = encode.qp});
++frame_index_;
current_timestamp_ += duration_;
}
std::vector<FrameResult> EncodeFor(TimeDelta total_duration) {
std::vector<FrameResult> results;
const int64_t num_frames = std::llround(total_duration / duration_);
for (int64_t i = 0; i < num_frames; ++i) {
results.push_back(EncodeNextFrame());
}
return results;
}
TimeDelta duration() const { return duration_; }
Timestamp current_timestamp() const { return current_timestamp_; }
SyntheticFrameSource& frame_source() { return frame_source_; }
private:
VideoFrameBuffer* NextFrameBuffer(Resolution res) {
if (!luma_step_.has_value() && !pending_jump_) {
return nullptr;
}
if (pending_jump_) {
pending_jump_ = false;
} else if (luma_step_.has_value() && *luma_step_ > 0) {
// Alternate +/- `luma_step_` so luma stays bounded while producing an
// exact `mean_abs_diff == *luma_step_` on every frame.
step_up_ = !step_up_;
current_luma_ = step_up_
? static_cast<uint8_t>(current_luma_ + *luma_step_)
: static_cast<uint8_t>(current_luma_ - *luma_step_);
}
last_fed_luma_ = current_luma_;
return frame_source_.FrameWithLuma(res, current_luma_);
}
std::unique_ptr<VideoRateController> controller_;
SyntheticEncoder encoder_;
SyntheticFrameSource frame_source_;
LayerBitrates layer_bitrates_;
TimeDelta duration_ = TimeDelta::Seconds(1) / 30;
ContentHint content_hint_ = ContentHint::kNone;
Resolution resolution_ = kResolution;
Timestamp current_timestamp_ = Timestamp::Zero();
int frame_index_ = 0;
FrameType last_frame_type_ = FrameType::kDeltaFrame;
int last_tid_ = 0;
Resolution last_resolution_ = kResolution;
std::optional<uint8_t> luma_step_;
uint8_t current_luma_ = 64;
int last_fed_luma_ = 64;
bool step_up_ = false;
bool pending_jump_ = false;
};
DataSize TotalSize(const std::vector<FrameResult>& results,
size_t begin = 0,
size_t end = SIZE_MAX) {
DataSize total = DataSize::Zero();
for (size_t i = begin; i < std::min(end, results.size()); ++i) {
total += results[i].encoded_size;
}
return total;
}
// The ratio of the size of the frames to what the bitrate allows for the time
// they span.
double RateRatio(const std::vector<FrameResult>& results,
DataRate bitrate,
size_t begin = 0,
size_t end = SIZE_MAX) {
end = std::min(end, results.size());
TimeDelta total_duration = TimeDelta::Zero();
for (size_t i = begin; i < end; ++i) {
total_duration += results[i].duration;
}
return TotalSize(results, begin, end) / (bitrate * total_duration);
}
int MaxQpStep(const std::vector<FrameResult>& results) {
int max_step = 0;
for (size_t i = 1; i < results.size(); ++i) {
if (results[i].frame_type == FrameType::kDeltaFrame &&
!results[i].dropped() && !results[i - 1].dropped()) {
max_step =
std::max(max_step, std::abs(results[i].qp() - results[i - 1].qp()));
}
}
return max_step;
}
TEST(BufferLevelRateControllerTest, ConvergesToTargetBitrate) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
Harness harness;
harness.SetStream(SingleLayer(kBitrate), 30);
const std::vector<FrameResult> results =
harness.EncodeFor(TimeDelta::Seconds(5));
ASSERT_THAT(results, SizeIs(150));
EXPECT_THAT(RateRatio(results, kBitrate), DoubleNear(1.0, 0.05));
// The last two seconds are on target too, not just the average.
EXPECT_THAT(RateRatio(results, kBitrate, 90), DoubleNear(1.0, 0.05));
}
TEST(BufferLevelRateControllerTest, AdaptsToComplexityChange) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
Harness harness;
harness.SetStream(SingleLayer(kBitrate), 30);
harness.EncodeFor(TimeDelta::Seconds(3));
harness.encoder().set_complexity(3.0);
const std::vector<FrameResult> results =
harness.EncodeFor(TimeDelta::Seconds(4));
EXPECT_THAT(RateRatio(results, kBitrate), DoubleNear(1.0, 0.1));
EXPECT_THAT(RateRatio(results, kBitrate, 60), DoubleNear(1.0, 0.05));
}
TEST(BufferLevelRateControllerTest,
BufferCreditCapLimitsSpendingAfterUndershoot) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
std::vector<double> ratios;
for (std::optional<int> credit_pct :
{std::optional<int>(), std::optional(0)}) {
Harness harness({.max_buffer_credit_pct = credit_pct});
harness.SetStream(SingleLayer(kBitrate), 30);
// Content too simple to reach the target fills the buffer.
harness.encoder().set_complexity(0.001);
harness.EncodeFor(TimeDelta::Seconds(3));
harness.encoder().set_complexity(0.1);
// The first frames on the harder content.
ratios.push_back(
RateRatio(harness.EncodeFor(TimeDelta::Seconds(1)), kBitrate, 0, 10));
}
// Without the cap the banked undershoot is spent on the harder content
// (2.3x the rate vs 1.5x).
EXPECT_GT(ratios[0], 2.0);
EXPECT_LT(ratios[1], 1.6);
}
TEST(BufferLevelRateControllerTest,
IdleGapDrainsBufferWithoutInflatingFrameTarget) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
const DataSize kNominalFrameBudget = kBitrate * kDuration;
const BufferLevelRateControllerConfig kConfig = {.max_buffer_credit_pct = 0};
Harness paused(kConfig);
Harness immediate(kConfig);
paused.SetStream(SingleLayer(kBitrate), 30, ContentHint::kText);
immediate.SetStream(SingleLayer(kBitrate), 30, ContentHint::kText);
paused.EncodeFor(TimeDelta::Seconds(2));
immediate.EncodeFor(TimeDelta::Seconds(2));
// Deplete both buffers with an oversized slide frame.
const FramePlan p0 = paused.StartNextFrame();
const FramePlan i0 = immediate.StartNextFrame();
paused.controller().OnFrameEncoded(
p0.id, {.encoded_size = DataSize::Bytes(60'000), .qp = AsEncode(p0).qp});
immediate.controller().OnFrameEncoded(
i0.id, {.encoded_size = DataSize::Bytes(60'000), .qp = AsEncode(i0).qp});
// `paused` has no frames for 1 second (1 Hz static screencast), while
// `immediate` encodes 33 ms later. Both keep `duration = 33 ms`.
paused.AdvanceTime(TimeDelta::Seconds(1));
immediate.AdvanceTime(kDuration);
const EncodeFrame after_pause = AsEncode(paused.StartNextFrame());
const EncodeFrame after_33ms = AsEncode(immediate.StartNextFrame());
// The 1-second gap drained the queue back to the target level, so
// `after_pause` gets a higher budget and lower QP than `after_33ms`, while
// still sizing the frame for a 33 ms duration rather than a 1-second burst.
EXPECT_GT(after_pause.target_size, after_33ms.target_size);
EXPECT_LT(after_pause.qp, after_33ms.qp);
EXPECT_THAT(after_pause.target_size.bytes<double>(),
DoubleNear(kNominalFrameBudget.bytes<double>(),
kNominalFrameBudget.bytes<double>() * 0.05));
}
TEST(BufferLevelRateControllerTest, FramerateChangeKeepsRateAndQp) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
Harness harness;
harness.SetStream(SingleLayer(kBitrate), 30);
harness.EncodeFor(TimeDelta::Seconds(3));
std::vector<FrameResult> results;
for (double fps : {10.0, 30.0}) {
// One frame at the old rate before the change, for the QP step.
const FrameResult before = harness.EncodeNextFrame();
harness.SetStream(SingleLayer(kBitrate), fps);
std::vector<FrameResult> segment = harness.EncodeFor(TimeDelta::Seconds(3));
EXPECT_THAT(RateRatio(segment, kBitrate), DoubleNear(1.0, 0.1)) << fps;
segment.insert(segment.begin(), before);
// The QP adapts to the new frame size gradually, nothing is reset.
EXPECT_THAT(MaxQpStep(segment), Le(20)) << fps;
results.insert(results.end(), segment.begin(), segment.end());
}
EXPECT_THAT(RateRatio(results, kBitrate), DoubleNear(1.0, 0.05));
}
TEST(BufferLevelRateControllerTest, FollowsBitrateSteps) {
const DataRate kHigh = DataRate::KilobitsPerSec(2000);
const DataRate kLow = kHigh / 5;
Harness harness;
harness.SetStream(SingleLayer(kHigh), 30);
harness.EncodeFor(TimeDelta::Seconds(3));
for (DataRate bitrate : {kLow, kHigh}) {
harness.SetStream(SingleLayer(bitrate), 30);
const std::vector<FrameResult> results =
harness.EncodeFor(TimeDelta::Seconds(4));
// The buffer is not reset, only clipped to the new size, so the first
// second spends what is above the target level after a step down, and
// refills the buffer after a step up.
EXPECT_THAT(RateRatio(results, bitrate, 0, 30), DoubleNear(1.0, 0.6))
<< bitrate;
EXPECT_THAT(RateRatio(results, bitrate, 30), DoubleNear(1.0, 0.1))
<< bitrate;
EXPECT_THAT(RateRatio(results, bitrate, 60), DoubleNear(1.0, 0.05))
<< bitrate;
}
}
TEST(BufferLevelRateControllerTest, CheckEncodedFrameHasNoSideEffects) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
Harness reference({.postencode_drop = true, .reencode_overshoot = true});
Harness probed({.postencode_drop = true, .reencode_overshoot = true});
reference.SetStream(SingleLayer(kBitrate), 30);
probed.SetStream(SingleLayer(kBitrate), 30);
for (int i = 0; i < 100; ++i) {
const FramePlan ref_plan = reference.StartNextFrame();
const FramePlan probed_plan = probed.StartNextFrame();
ASSERT_EQ(AsEncode(ref_plan).qp, AsEncode(probed_plan).qp) << i;
ASSERT_EQ(AsEncode(ref_plan).target_size, AsEncode(probed_plan).target_size)
<< i;
// Probing `CheckEncodedFrame` with arbitrary sizes leaves no trace.
EXPECT_NE(probed.controller().CheckEncodedFrame(
probed_plan.id, {.encoded_size = DataSize::Bytes(200'000),
.qp = AsEncode(probed_plan).qp}),
Verdict::kDrop);
EXPECT_EQ(probed.controller().CheckEncodedFrame(
probed_plan.id, {.encoded_size = DataSize::Bytes(10),
.qp = AsEncode(probed_plan).qp}),
Verdict::kAccept);
reference.FinishEncode(ref_plan);
probed.FinishEncode(probed_plan);
}
}
// Like an upper spatial layer of L2T3 whose first frame is inter-layer
// predicted from the keyframe below it, so the layer never sees a keyframe.
TEST(BufferLevelRateControllerTest, StreamStartingWithDeltaFrame) {
BufferLevelRateController controller;
const LayerBitrates kBitrates = ThreeLayers(DataRate::KilobitsPerSec(500));
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
Timestamp timestamp = Timestamp::Zero();
std::optional<int> first_qp;
for (int tid : {0, 2, 1, 2, 0, 2, 1, 2}) {
const TemporalUnitSettings tu_settings(timestamp);
const FrameEncodeSettings frame_settings =
MakeFrameSettings(FrameType::kDeltaFrame, tid);
const FramePlan plan =
controller.PlanFrame({.target_bitrate = kBitrates[tid],
.duration = kDuration,
.tu_settings = tu_settings,
.frame_settings = frame_settings});
const EncodeFrame& encode = AsEncode(plan);
if (!first_qp.has_value()) {
first_qp = encode.qp;
} else {
// Without a keyframe Q to weigh against, the Q dropped to 0 here.
EXPECT_THAT(encode.qp, Gt(*first_qp / 2)) << "tid " << tid;
}
// Omitting `qp` falls back to the planned QP.
controller.OnFrameEncoded(plan.id, {.encoded_size = encode.target_size});
timestamp += kDuration;
}
}
TEST(BufferLevelRateControllerTest, DroppedFrameLowersQp) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
Harness dropping;
Harness encoding;
dropping.SetStream(SingleLayer(kBitrate), 30);
encoding.SetStream(SingleLayer(kBitrate), 30);
dropping.EncodeFor(TimeDelta::Seconds(2));
encoding.EncodeFor(TimeDelta::Seconds(2));
// The dropped frame's budget is left in the buffer.
dropping.DropNextFrame();
dropping.DropNextFrame();
encoding.EncodeNextFrame();
encoding.EncodeNextFrame();
const EncodeFrame after_drop = AsEncode(dropping.StartNextFrame());
const EncodeFrame after_encode = AsEncode(encoding.StartNextFrame());
EXPECT_THAT(after_drop.qp, Le(after_encode.qp));
EXPECT_THAT(after_drop.target_size, Gt(after_encode.target_size));
}
TEST(BufferLevelRateControllerTest, ReencodesRaiseQp) {
Harness harness;
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30);
harness.EncodeFor(TimeDelta::Seconds(2));
// A scene change makes the frame overshoot.
harness.encoder().set_complexity(5);
const FramePlan original_plan = harness.StartNextFrame();
const EncodeFrame& original = AsEncode(original_plan);
DataSize size =
harness.encoder().Encode(original.qp, kResolution, FrameType::kDeltaFrame,
/*temporal_id=*/0);
ASSERT_THAT(size, Gt(original.target_size * 3));
int last_qp = original.qp;
for (int attempt = 0; attempt < 3; ++attempt) {
const FramePlan retry_plan = harness.controller().ReplanFrame(
original_plan.id, {.encoded_size = size, .qp = last_qp});
EXPECT_EQ(retry_plan.id, original_plan.id);
const EncodeFrame& retry = AsEncode(retry_plan);
EXPECT_THAT(retry.qp, Gt(last_qp)) << attempt;
EXPECT_EQ(retry.target_size, original.target_size);
size = harness.encoder().Encode(retry.qp, kResolution,
FrameType::kDeltaFrame, /*temporal_id=*/0);
last_qp = retry.qp;
// The overshoot is corrected for in one go.
EXPECT_THAT(size, Lt(original.target_size * 1.5)) << attempt;
}
}
TEST(BufferLevelRateControllerTest, ReencodeAfterUndershootRaisesQp) {
Harness harness;
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30);
harness.EncodeFor(TimeDelta::Seconds(2));
const FramePlan original_plan = harness.StartNextFrame();
const EncodeFrame& original = AsEncode(original_plan);
const EncodeFrame retry = AsEncode(harness.controller().ReplanFrame(
original_plan.id,
{.encoded_size = original.target_size / 2, .qp = original.qp}));
EXPECT_EQ(retry.qp, original.qp + 1);
}
TEST(BufferLevelRateControllerTest, ReencodeAtMaxQpStaysAtMaxQp) {
Harness harness;
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30);
harness.EncodeFor(TimeDelta::Seconds(1));
const FramePlan plan = harness.StartNextFrame();
const EncodeFrame retry = AsEncode(harness.controller().ReplanFrame(
plan.id, {.encoded_size = DataSize::Bytes(100000), .qp = 255}));
EXPECT_EQ(retry.qp, 255);
}
TEST(BufferLevelRateControllerTest, TemporalLayersFollowLayerBudgets) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const LayerBitrates layer_bitrates = ThreeLayers(kBitrate);
Harness harness;
harness.SetStream(layer_bitrates, 30);
harness.EncodeFor(TimeDelta::Seconds(5));
const std::vector<FrameResult> results =
harness.EncodeFor(TimeDelta::Seconds(5));
EXPECT_THAT(RateRatio(results, kBitrate), DoubleNear(1.0, 0.05));
std::vector<DataSize> layer_size(3, DataSize::Zero());
for (const FrameResult& result : results) {
layer_size[result.temporal_id] += result.encoded_size;
}
const TimeDelta kDuration = TimeDelta::Seconds(5);
for (int tid = 0; tid < 3; ++tid) {
EXPECT_THAT(layer_size[tid] / (layer_bitrates[tid] * kDuration),
DoubleNear(1.0, 0.2))
<< tid;
}
}
TEST(BufferLevelRateControllerTest, ChangingNumberOfTemporalLayers) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
Harness harness;
harness.SetStream(SingleLayer(kBitrate), 30);
harness.EncodeFor(TimeDelta::Seconds(2));
for (const LayerBitrates& layer_bitrates :
{ThreeLayers(kBitrate), SingleLayer(kBitrate)}) {
harness.SetStream(layer_bitrates, 30);
const std::vector<FrameResult> results =
harness.EncodeFor(TimeDelta::Seconds(4));
EXPECT_THAT(RateRatio(results, kBitrate), DoubleNear(1.0, 0.1));
EXPECT_THAT(RateRatio(results, kBitrate, 60), DoubleNear(1.0, 0.05));
}
}
TEST(BufferLevelRateControllerTest, IntraTargetRespectsMaxIntraBitrate) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const DataSize kMaxIntraTarget = kBitrate * TimeDelta::Seconds(1) * 1.5 / 30;
Harness harness({.max_intra_bitrate_factor = 1.5});
harness.SetStream(SingleLayer(kBitrate), 30);
const FrameResult first = harness.EncodeNextFrame(FrameType::kKeyframe);
EXPECT_THAT(first.target_size(), Le(kMaxIntraTarget));
harness.EncodeFor(TimeDelta::Seconds(2));
for (FrameType type : {FrameType::kKeyframe, FrameType::kStartFrame}) {
const FramePlan intra = harness.StartNextFrame(type);
EXPECT_THAT(AsEncode(intra).target_size, Le(kMaxIntraTarget));
harness.FinishEncode(intra);
}
}
TEST(BufferLevelRateControllerTest, KeyframeMidStreamUsesKeyframePath) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const DataSize kFrameBudget = kBitrate * TimeDelta::Seconds(1) / 30;
Harness delta_probe;
Harness start_probe;
Harness harness;
for (Harness* h : {&delta_probe, &start_probe, &harness}) {
h->SetStream(SingleLayer(kBitrate), 30);
h->EncodeFor(TimeDelta::Seconds(2));
}
const EncodeFrame delta = AsEncode(delta_probe.StartNextFrame());
const EncodeFrame start =
AsEncode(start_probe.StartNextFrame(FrameType::kStartFrame));
const FramePlan key_plan = harness.StartNextFrame(FrameType::kKeyframe);
const EncodeFrame& key = AsEncode(key_plan);
EXPECT_THAT(delta.target_size, Lt(kFrameBudget * 1.5));
// The boost is capped by `max_intra_bitrate_factor`.
EXPECT_THAT(key.target_size.bytes<double>(),
DoubleNear(kFrameBudget.bytes<double>() * 3, 2));
EXPECT_THAT(key.qp, Lt(delta.qp));
EXPECT_EQ(start.qp, key.qp);
EXPECT_EQ(start.target_size, key.target_size);
// The keyframe is accounted as such: the stream stays on target and the
// delta frames return to their QP.
harness.FinishEncode(key_plan);
const std::vector<FrameResult> results =
harness.EncodeFor(TimeDelta::Seconds(3));
EXPECT_THAT(RateRatio(results, kBitrate, 30), DoubleNear(1.0, 0.1));
EXPECT_THAT(results.back().qp(), AllOf(Ge(delta.qp - 10), Le(delta.qp + 10)));
}
TEST(BufferLevelRateControllerTest, KeyframeBoostDependsOnFramerate) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
for (double fps : {10.0, 30.0}) {
Harness harness({.max_intra_bitrate_factor = 10});
harness.SetStream(SingleLayer(kBitrate), fps);
harness.EncodeFor(TimeDelta::Seconds(2));
const EncodeFrame key =
AsEncode(harness.StartNextFrame(FrameType::kKeyframe));
// `(16 + max(32, 2 * fps - 16)) / 16` times the frame budget.
const double boost = (16 + std::max(32.0, 2 * fps - 16)) / 16;
EXPECT_THAT(key.target_size.bytes<double>(),
DoubleNear(kBitrate.bytes_per_sec<double>() / fps * boost, 2))
<< fps;
}
}
// Steady state at 1000 kbps, then a frame far over its budget.
struct OvershootSetup {
explicit OvershootSetup(const BufferLevelRateControllerConfig& config)
: harness(config) {
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30);
harness.EncodeFor(TimeDelta::Seconds(3));
plan = harness.StartNextFrame();
}
Harness harness;
FramePlan plan;
const DataSize kHugeSize = DataSize::Bytes(100'000);
};
TEST(BufferLevelRateControllerTest, DefaultSettingsNeverDrop) {
OvershootSetup setup({});
ASSERT_FALSE(IsDrop(setup.plan));
EXPECT_EQ(setup.harness.controller().CheckEncodedFrame(
setup.plan.id, {.encoded_size = setup.kHugeSize,
.qp = AsEncode(setup.plan).qp}),
Verdict::kAccept);
setup.harness.FinishEncode(setup.plan);
setup.harness.encoder().set_complexity(100);
for (int i = 0; i < 60; ++i) {
EXPECT_FALSE(setup.harness.EncodeOrDropNextFrame().dropped());
}
}
TEST(BufferLevelRateControllerTest, PreEncodeDropLimitsConsecutiveDrops) {
Harness harness({.drop_frames_water_mark_pct = 30});
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30);
harness.EncodeFor(TimeDelta::Seconds(2));
// Even the max QP overshoots the budget by an order of magnitude.
harness.encoder().set_complexity(100);
int num_drops = 0;
int consecutive = 0;
int max_consecutive = 0;
for (int i = 0; i < 90; ++i) {
if (harness.EncodeOrDropNextFrame().dropped()) {
++num_drops;
max_consecutive = std::max(max_consecutive, ++consecutive);
} else {
consecutive = 0;
}
}
EXPECT_GT(num_drops, 0);
// `max_consecutive_drop` of 250 ms at 30 fps.
EXPECT_EQ(max_consecutive, 8);
}
TEST(BufferLevelRateControllerTest, PostEncodeDropForcesMaxQp) {
OvershootSetup setup({.postencode_drop = true});
const EncodeFrame& initial = AsEncode(setup.plan);
ASSERT_LT(initial.qp, 191);
EXPECT_EQ(
setup.harness.controller().CheckEncodedFrame(
setup.plan.id, {.encoded_size = setup.kHugeSize, .qp = initial.qp}),
Verdict::kDrop);
// A frame within budget is kept.
EXPECT_EQ(setup.harness.controller().CheckEncodedFrame(
setup.plan.id,
{.encoded_size = initial.target_size, .qp = initial.qp}),
Verdict::kAccept);
setup.harness.DiscardEncode(setup.plan, setup.kHugeSize);
EXPECT_EQ(setup.harness.EncodeNextFrame().qp(), 255);
}
// With temporal layers, the frame after a post-encode drop is usually of
// another layer. Every layer restarts from the max QP, like libaom's layer
// contexts, or the dropped layer is planned at the same low QP again.
TEST(BufferLevelRateControllerTest, PostEncodeDropForcesMaxQpOnEveryLayer) {
for (bool drop_upper : {false, true}) {
Harness harness({.postencode_drop = true,
.drop_upper_layers_after_base_drop = drop_upper});
harness.SetStream(ThreeLayers(DataRate::KilobitsPerSec(1000)), 30);
harness.EncodeFor(TimeDelta::Seconds(3));
while (harness.NextTemporalId() != 0) {
harness.EncodeNextFrame();
}
const FramePlan plan = harness.StartNextFrame();
harness.DiscardEncode(plan, DataSize::Bytes(500'000));
// tid 2, 1, 2, then 0.
for (int i = 0; i < 4; ++i) {
const int tid = harness.NextTemporalId();
const FrameResult result = harness.EncodeOrDropNextFrame();
if (tid == 0) {
EXPECT_FALSE(result.dropped());
EXPECT_EQ(result.qp(), 255);
} else if (drop_upper) {
EXPECT_TRUE(result.dropped()) << "tid " << tid;
} else if (i < 2) {
// The first frame of each upper layer.
EXPECT_EQ(result.qp(), 255) << "tid " << tid;
}
}
// Upper layers are coded again after the base layer.
EXPECT_FALSE(harness.EncodeOrDropNextFrame().dropped());
}
}
TEST(BufferLevelRateControllerTest, ReencodeOvershootAsksForReencode) {
OvershootSetup setup({.postencode_drop = true, .reencode_overshoot = true});
const EncodeFrame& initial = AsEncode(setup.plan);
EXPECT_EQ(
setup.harness.controller().CheckEncodedFrame(
setup.plan.id, {.encoded_size = setup.kHugeSize, .qp = initial.qp}),
Verdict::kReencode);
const EncodeFrame retry = AsEncode(setup.harness.controller().ReplanFrame(
setup.plan.id, {.encoded_size = setup.kHugeSize, .qp = initial.qp}));
EXPECT_GT(retry.qp, initial.qp);
}
TEST(BufferLevelRateControllerTest, ReencodeTargetFactorLowersRetryQp) {
std::array<EncodeFrame, 2> retries;
for (int i = 0; i < 2; ++i) {
OvershootSetup setup(
{.reencode_overshoot = true, .reencode_target_factor = i * 4.0});
const EncodeFrame& initial = AsEncode(setup.plan);
// Over 8 times the budget, but not so much that both retries end up at
// the max QP.
retries[i] = AsEncode(setup.harness.controller().ReplanFrame(
setup.plan.id,
{.encoded_size = DataSize::Bytes(40'000), .qp = initial.qp}));
}
EXPECT_GT(retries[1].target_size, retries[0].target_size * 3);
EXPECT_LT(retries[1].qp, retries[0].qp);
EXPECT_GT(retries[1].qp, 0);
}
TEST(BufferLevelRateControllerTest, SeedAfterReencodeKeepsNextQpNearRetry) {
std::array<int, 2> next_qp = {};
int retry_qp = 0;
for (int seed = 0; seed < 2; ++seed) {
OvershootSetup setup(
{.reencode_overshoot = true, .seed_after_reencode = seed == 1});
const EncodeFrame& initial = AsEncode(setup.plan);
const EncodeFrame retry = AsEncode(setup.harness.controller().ReplanFrame(
setup.plan.id, {.encoded_size = setup.kHugeSize, .qp = initial.qp}));
retry_qp = retry.qp;
setup.harness.controller().OnFrameEncoded(
setup.plan.id, {.encoded_size = retry.target_size, .qp = retry.qp});
setup.harness.AdvanceTime(setup.harness.duration());
next_qp[seed] = AsEncode(setup.harness.StartNextFrame()).qp;
}
EXPECT_LT(next_qp[0], retry_qp - 30);
EXPECT_GE(next_qp[1], retry_qp - 30);
}
TEST(BufferLevelRateControllerTest, ScreenSceneChangeUsesMaxQp) {
for (bool scene_change_high_qp : {false, true}) {
Harness harness({.scene_change_high_qp = scene_change_high_qp});
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30,
ContentHint::kDetailed);
harness.SetMotionStep(0);
harness.EncodeFor(TimeDelta::Seconds(2));
harness.TriggerSceneJump();
const int qp = AsEncode(harness.StartNextFrame()).qp;
if (scene_change_high_qp) {
EXPECT_EQ(qp, 255);
} else {
EXPECT_LT(qp, 255);
}
}
}
TEST(BufferLevelRateControllerTest,
SoftScreenSceneChangeTriggersReencodeOnOvershoot) {
const BufferLevelRateControllerConfig kConfig = {
.reencode_overshoot = true,
.scene_change_high_qp = true,
.soft_screen_scene_change = true};
Harness regular_harness(kConfig);
Harness screen_harness(kConfig);
for (Harness* h : {&regular_harness, &screen_harness}) {
h->SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30,
ContentHint::kDetailed);
h->SetMotionStep(0);
h->EncodeFor(TimeDelta::Seconds(2));
}
const int regular_qp = AsEncode(regular_harness.StartNextFrame()).qp;
ASSERT_GE(regular_qp, 123);
screen_harness.TriggerSceneJump();
const FramePlan scene_plan = screen_harness.StartNextFrame();
const EncodeFrame& scene_encode = AsEncode(scene_plan);
EXPECT_EQ(scene_encode.qp, (regular_qp + 255) >> 1);
ASSERT_GE(scene_encode.qp, 189);
ASSERT_LT(scene_encode.qp, 255);
EXPECT_EQ(screen_harness.controller().CheckEncodedFrame(
scene_plan.id, {.encoded_size = DataSize::Bytes(100'000),
.qp = scene_encode.qp}),
Verdict::kReencode);
// Camera content (`kFluid`) ignores `soft_screen_scene_change` and keeps
// high-QP scene changes as-is even at >= 720p where `SceneChangeQIndex` uses
// `(qindex + worst_quality_qindex_) >> 1`.
const Resolution kHd = {.width = 1280, .height = 720};
Harness motion_harness(kConfig);
motion_harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(2000)), 30,
ContentHint::kFluid, kHd);
motion_harness.SetMotionStep(0);
motion_harness.EncodeFor(TimeDelta::Millis(500));
motion_harness.TriggerSceneJump();
const FramePlan motion_scene_plan = motion_harness.StartNextFrame();
const EncodeFrame& motion_scene = AsEncode(motion_scene_plan);
EXPECT_LT(motion_scene.qp, 255);
EXPECT_EQ(motion_harness.controller().CheckEncodedFrame(
motion_scene_plan.id, {.encoded_size = DataSize::Bytes(200'000),
.qp = motion_scene.qp}),
Verdict::kAccept);
}
TEST(BufferLevelRateControllerTest,
AdaptsUpwardFromOverheadFloorAfterStaticScreen) {
// Use `min_qp = 120` so static screen frames plan at qp = 120, where
// `EstimateSizeAtQIndex` at `kMinRateCorrectionFactor` (0.005) clamps to
// `kFrameOverhead` (25 bytes).
const BufferLevelRateControllerConfig kConfig = {.min_qp = 120,
.postencode_drop = true,
.seed_after_reencode = true,
.fast_recovery = true,
.max_buffer_credit_pct = 0};
Harness static_screen(kConfig);
Harness fresh_screen(kConfig);
Harness static_adapt(kConfig);
for (Harness* h : {&static_screen, &fresh_screen, &static_adapt}) {
h->SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30,
ContentHint::kText);
h->encoder().set_complexity(0.0001);
}
static_screen.EncodeFor(TimeDelta::Seconds(3));
static_adapt.EncodeFor(TimeDelta::Seconds(3));
fresh_screen.EncodeNextFrame(FrameType::kKeyframe);
// `PickReencodeQIndex` must invert `BitsPerMacroblock` directly rather than
// dividing by the 25-byte-clamped `EstimateSizeAtQIndex`.
const FramePlan static_plan = static_screen.StartNextFrame();
const FramePlan fresh_plan = fresh_screen.StartNextFrame();
ASSERT_EQ(AsEncode(static_plan).qp, 120);
const EncodeFrame static_retry =
AsEncode(static_screen.controller().ReplanFrame(
static_plan.id,
{.encoded_size = DataSize::Bytes(20'000), .qp = 150}));
const EncodeFrame fresh_retry =
AsEncode(fresh_screen.controller().ReplanFrame(
fresh_plan.id, {.encoded_size = DataSize::Bytes(20'000), .qp = 150}));
EXPECT_EQ(static_retry.qp, fresh_retry.qp);
static_screen.controller().OnFrameDropped(static_plan.id, std::nullopt);
fresh_screen.controller().OnFrameDropped(fresh_plan.id, std::nullopt);
// `UpdateRateCorrectionFactors` must still raise `rate_correction_factor`
// when a frame at `qp = 120` (where projected size at factor 0.005 clamps to
// the 25-byte overhead floor) overshoots, so the next frame raises QP above
// 120 rather than staying pinned at `min_qp`.
const FramePlan overshoot_plan = static_adapt.StartNextFrame();
ASSERT_EQ(AsEncode(overshoot_plan).qp, 120);
static_adapt.controller().OnFrameEncoded(
overshoot_plan.id, {.encoded_size = DataSize::Bytes(15'000), .qp = 120});
static_adapt.AdvanceTime(static_adapt.duration());
EXPECT_GT(AsEncode(static_adapt.StartNextFrame()).qp, 120);
}
TEST(BufferLevelRateControllerTest,
DroppedFramesPreserveResolutionTransitionAndInitialEnhancementQpFloor) {
// 1. First enhancement-layer frames after a keyframe must not falsely trigger
// `ChangedTargetBitsPerMb` and skip the `last_qindex_tl0 - 4` floor.
BufferLevelRateController layered({.max_intra_bitrate_factor = 1.0});
const LayerBitrates kLayeredRates =
ThreeLayers(DataRate::KilobitsPerSec(1500));
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
Timestamp timestamp = Timestamp::Zero();
const TemporalUnitSettings kf_tu(timestamp);
const FrameEncodeSettings kf_settings =
MakeFrameSettings(FrameType::kKeyframe, /*temporal_id=*/0);
const FramePlan kf_plan =
layered.PlanFrame({.target_bitrate = kLayeredRates[0],
.duration = kDuration,
.tu_settings = kf_tu,
.frame_settings = kf_settings});
const EncodeFrame& kf = AsEncode(kf_plan);
ASSERT_GT(kf.qp, 100);
ASSERT_LT(kf.qp, 200);
layered.OnFrameEncoded(kf_plan.id,
{.encoded_size = DataSize::Bytes(100), .qp = kf.qp});
// Cover the entire first L1T3 GOP (T2a, T1, T2b) before any TL0 delta frame
// has been coded: all enhancement frames keep `kf.qp - 4` as the floor rather
// than reading the uninitialized TL0 inter `last_qindex` (255).
for (int tid : {2, 1, 2}) {
timestamp += kDuration;
const TemporalUnitSettings tu(timestamp);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame, tid);
const FramePlan enh_plan =
layered.PlanFrame({.target_bitrate = kLayeredRates[tid],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
const EncodeFrame& enh = AsEncode(enh_plan);
EXPECT_GE(enh.qp, kf.qp - 4) << "tid " << tid;
EXPECT_LT(enh.qp, 240) << "tid " << tid;
layered.OnFrameEncoded(
enh_plan.id, {.encoded_size = DataSize::Bytes(100), .qp = enh.qp});
}
// 2. Dropping an initial keyframe must not mark `seen_keyframe_`.
const LayerBitrates kLayers = ThreeLayers(DataRate::KilobitsPerSec(500));
BufferLevelRateController dropped_kf;
timestamp = Timestamp::Zero();
VideoRateController::PlanId kf_drop_id = 0;
{
const TemporalUnitSettings tu(timestamp);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kKeyframe, /*temporal_id=*/0);
kf_drop_id = dropped_kf
.PlanFrame({.target_bitrate = kLayers[0],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings})
.id;
}
dropped_kf.OnFrameDropped(kf_drop_id, std::nullopt);
timestamp += kDuration;
const TemporalUnitSettings delta0_tu(timestamp);
const FrameEncodeSettings delta0_settings =
MakeFrameSettings(FrameType::kDeltaFrame, /*temporal_id=*/0);
const FramePlan delta0_plan =
dropped_kf.PlanFrame({.target_bitrate = kLayers[0],
.duration = kDuration,
.tu_settings = delta0_tu,
.frame_settings = delta0_settings});
const EncodeFrame& delta0 = AsEncode(delta0_plan);
dropped_kf.OnFrameEncoded(
delta0_plan.id, {.encoded_size = delta0.target_size, .qp = delta0.qp});
timestamp += kDuration;
const TemporalUnitSettings delta_enh_tu(timestamp);
const FrameEncodeSettings delta_enh_settings =
MakeFrameSettings(FrameType::kDeltaFrame, /*temporal_id=*/2);
const EncodeFrame delta_enh =
AsEncode(dropped_kf.PlanFrame({.target_bitrate = kLayers[2],
.duration = kDuration,
.tu_settings = delta_enh_tu,
.frame_settings = delta_enh_settings}));
EXPECT_GT(delta_enh.qp, delta0.qp / 2);
// 3. Dropping the first frame after a resolution increase must not overwrite
// `prev_coded_resolution_` and mask the resolution transition on the next
// coded frame.
Harness res_drop;
res_drop.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30);
res_drop.encoder().set_complexity(0.2);
res_drop.EncodeFor(TimeDelta::Seconds(2));
const FramePlan drain_plan = res_drop.StartNextFrame();
res_drop.controller().OnFrameEncoded(
drain_plan.id,
{.encoded_size = DataSize::Bytes(55'000), .qp = AsEncode(drain_plan).qp});
res_drop.AdvanceTime(res_drop.duration());
Harness probe_low;
probe_low.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30);
probe_low.encoder().set_complexity(0.2);
probe_low.EncodeFor(TimeDelta::Seconds(2));
const FramePlan drain2_plan = probe_low.StartNextFrame();
probe_low.controller().OnFrameEncoded(
drain2_plan.id, {.encoded_size = DataSize::Bytes(55'000),
.qp = AsEncode(drain2_plan).qp});
probe_low.AdvanceTime(probe_low.duration());
const int low_res_qp = AsEncode(probe_low.StartNextFrame()).qp;
ASSERT_LT(low_res_qp, 100);
const Resolution kHd = {.width = 1280, .height = 720};
const FramePlan hd_drop =
res_drop.StartNextFrame(FrameType::kDeltaFrame, kHd);
res_drop.controller().OnFrameDropped(hd_drop.id, std::nullopt);
res_drop.AdvanceTime(res_drop.duration());
// Next frame is still the first coded frame at 1280x720, so
// `ChangedTargetBitsPerMb` bypasses the +20 QP step limit and
// `AdjustQIndexCbr` shifts Q halfway toward `active_worst_qindex`.
const EncodeFrame after_res_drop =
AsEncode(res_drop.StartNextFrame(FrameType::kDeltaFrame, kHd));
EXPECT_GT(after_res_drop.qp, low_res_qp + 30);
}
TEST(BufferLevelRateControllerTest,
SceneChangeSeedsPreviousFrameQpAcrossAllTemporalLayers) {
Harness harness({.scene_change_high_qp = true});
harness.SetStream(ThreeLayers(DataRate::KilobitsPerSec(1000)), 30);
harness.encoder().set_complexity(0.05);
harness.SetMotionStep(1);
harness.EncodeFor(TimeDelta::Seconds(3));
while (harness.NextTemporalId() != 0) {
harness.EncodeNextFrame();
}
const FrameResult pre_scene = harness.EncodeNextFrame();
ASSERT_LT(pre_scene.qp(), 80);
while (harness.NextTemporalId() != 0) {
harness.EncodeNextFrame();
}
harness.TriggerSceneJump();
const FrameResult scene_t0 = harness.EncodeNextFrame();
ASSERT_EQ(scene_t0.temporal_id, 0);
ASSERT_GE(scene_t0.qp(), 191);
const EncodeFrame next_t2 = AsEncode(harness.StartNextFrame());
ASSERT_EQ(harness.NextTemporalId(), 2);
// Without updating `prev_frame_qindex` across all layers in
// `OnSceneChangeEncoded`, `AdjustQIndexCbr` clamped `tid = 2` to
// `pre_scene_qp + 20` (< 100).
EXPECT_GT(next_t2.qp, 150);
}
TEST(BufferLevelRateControllerTest,
FasterConvergenceStaticLowersQpOnStaticScreen) {
for (uint8_t post_step : {uint8_t{0}, uint8_t{1}}) {
std::array<int, 2> last_qp = {};
for (bool faster : {false, true}) {
Harness harness(
{.scene_change_high_qp = true, .faster_convergence_static = faster});
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30,
ContentHint::kText);
harness.SetMotionStep(1);
harness.EncodeFor(TimeDelta::Seconds(2));
harness.TriggerSceneJump();
harness.EncodeNextFrame();
// Content that is cheap to code after the scene change.
harness.encoder().set_complexity(0.05);
harness.SetMotionStep(post_step);
last_qp[faster] = harness.EncodeFor(TimeDelta::Millis(500)).back().qp();
}
if (post_step == 0) {
EXPECT_LT(last_qp[1], last_qp[0] - 30);
} else {
EXPECT_EQ(last_qp[1], last_qp[0]);
}
}
}
TEST(BufferLevelRateControllerTest, NeverPicksQpZero) {
// QP 0 maps to lossless coding in AV1.
Harness harness;
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30,
ContentHint::kText);
harness.encoder().set_complexity(0.001);
for (const FrameResult& result : harness.EncodeFor(TimeDelta::Seconds(2))) {
EXPECT_GE(result.qp(), 1);
}
}
TEST(BufferLevelRateControllerTest, RecommendedSettingsConvergeToTarget) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
Harness harness(BufferLevelRateControllerConfig::Recommended());
harness.SetStream(SingleLayer(kBitrate), 30);
harness.SetMotionStep(2);
const std::vector<FrameResult> results =
harness.EncodeFor(TimeDelta::Seconds(5));
EXPECT_THAT(RateRatio(results, kBitrate, 90), DoubleNear(1.0, 0.05));
for (const FrameResult& result : results) {
EXPECT_FALSE(result.dropped());
}
}
TEST(BufferLevelRateControllerTest,
PipelinedFramesMapCallbacksByPlanIdAndConvergeToTarget) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
constexpr int kPipelineDepth = 3;
BufferLevelRateController controller({.max_buffer_credit_pct = 0});
SyntheticEncoder encoder;
struct InFlight {
FramePlan plan;
FrameType frame_type;
};
std::vector<InFlight> in_flight;
std::vector<FrameResult> completed;
Timestamp timestamp = Timestamp::Zero();
// Keep up to `kPipelineDepth` frames in flight simultaneously (like an async
// hardware encoder), completing the oldest once the pipeline fills.
for (int i = 0; i < 150; ++i) {
const FrameType type =
i == 0 ? FrameType::kKeyframe : FrameType::kDeltaFrame;
const TemporalUnitSettings tu(timestamp);
const FrameEncodeSettings settings = MakeFrameSettings(type);
const FramePlan plan = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
timestamp += kDuration;
if (!in_flight.empty()) {
EXPECT_GT(plan.id, in_flight.back().plan.id);
}
in_flight.push_back({.plan = plan, .frame_type = type});
if (static_cast<int>(in_flight.size()) >= kPipelineDepth) {
const InFlight done = in_flight.front();
in_flight.erase(in_flight.begin());
const EncodeFrame& encode = AsEncode(done.plan);
const DataSize size = encoder.Encode(encode.qp, kResolution,
done.frame_type, /*temporal_id=*/0);
controller.OnFrameEncoded(done.plan.id,
{.encoded_size = size, .qp = encode.qp});
completed.push_back({.plan = done.plan,
.frame_type = done.frame_type,
.temporal_id = 0,
.duration = kDuration,
.encoded_size = size});
}
}
// Complete the remaining in-flight frames out of order to verify `PlanId`
// lookup binds each completion to its exact request.
while (!in_flight.empty()) {
const InFlight done = in_flight.back();
in_flight.pop_back();
const EncodeFrame& encode = AsEncode(done.plan);
const DataSize size = encoder.Encode(encode.qp, kResolution,
done.frame_type, /*temporal_id=*/0);
controller.OnFrameEncoded(done.plan.id,
{.encoded_size = size, .qp = encode.qp});
completed.push_back({.plan = done.plan,
.frame_type = done.frame_type,
.temporal_id = 0,
.duration = kDuration,
.encoded_size = size});
}
ASSERT_THAT(completed, SizeIs(150));
EXPECT_THAT(RateRatio(completed, kBitrate, 90), DoubleNear(1.0, 0.05));
}
TEST(BufferLevelRateControllerTest, ConstFactoryCreatesIndependentControllers) {
const BufferLevelRateControllerFactory factory(
BufferLevelRateControllerConfig::Recommended());
std::unique_ptr<VideoRateController> first = factory.CreateRateController();
std::unique_ptr<VideoRateController> second = factory.CreateRateController();
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
const TemporalUnitSettings tu0(Timestamp::Zero());
const FrameEncodeSettings kf_settings =
MakeFrameSettings(FrameType::kKeyframe);
const FramePlan p1 = first->PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu0,
.frame_settings = kf_settings});
const FramePlan p2 = second->PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu0,
.frame_settings = kf_settings});
EXPECT_EQ(AsEncode(p1).qp, AsEncode(p2).qp);
EXPECT_EQ(AsEncode(p1).target_size, AsEncode(p2).target_size);
// Overshooting on `first` must not affect `second`.
first->OnFrameEncoded(p1.id, {.encoded_size = DataSize::Bytes(100'000)});
second->OnFrameEncoded(p2.id, {.encoded_size = DataSize::Bytes(500)});
const TemporalUnitSettings tu1(Timestamp::Zero() + kDuration);
const FrameEncodeSettings delta_settings =
MakeFrameSettings(FrameType::kDeltaFrame);
const EncodeFrame next1 =
AsEncode(first->PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu1,
.frame_settings = delta_settings}));
const EncodeFrame next2 =
AsEncode(second->PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu1,
.frame_settings = delta_settings}));
EXPECT_GT(next1.qp, next2.qp);
}
TEST(BufferLevelRateControllerTest, RespectsConfiguredQpBounds) {
constexpr int kMinQp = 40;
constexpr int kMaxQp = 180;
Harness harness({.min_qp = kMinQp,
.max_qp = kMaxQp,
.reencode_overshoot = true,
.scene_change_high_qp = true});
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30,
ContentHint::kDetailed);
harness.SetMotionStep(0);
// Easy content stays at or above `min_qp`.
harness.encoder().set_complexity(0.001);
for (const FrameResult& result : harness.EncodeFor(TimeDelta::Seconds(2))) {
EXPECT_THAT(result.qp(), AllOf(Ge(kMinQp), Le(kMaxQp)));
}
// Scene change and re-encode stay at or below `max_qp`.
harness.TriggerSceneJump();
const FramePlan scene_plan = harness.StartNextFrame();
EXPECT_EQ(AsEncode(scene_plan).qp, kMaxQp);
const EncodeFrame retry = AsEncode(harness.controller().ReplanFrame(
scene_plan.id, {.encoded_size = DataSize::Bytes(100'000), .qp = 150}));
EXPECT_THAT(retry.qp, AllOf(Ge(kMinQp), Le(kMaxQp)));
}
TEST(BufferLevelRateControllerTest,
UsesInRangeEncoderReportedQpAndIgnoresOutOfRange) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
Harness reference;
Harness negative_qp;
Harness too_high_qp;
Harness clamped_qp;
for (Harness* h : {&reference, &negative_qp, &too_high_qp, &clamped_qp}) {
h->SetStream(SingleLayer(kBitrate), 30);
h->EncodeFor(TimeDelta::Seconds(2));
}
const FramePlan ref_plan = reference.StartNextFrame();
const FramePlan neg_plan = negative_qp.StartNextFrame();
const FramePlan high_plan = too_high_qp.StartNextFrame();
const FramePlan clamped_plan = clamped_qp.StartNextFrame();
const EncodeFrame& planned = AsEncode(ref_plan);
ASSERT_EQ(AsEncode(neg_plan).qp, planned.qp);
ASSERT_EQ(AsEncode(high_plan).qp, planned.qp);
ASSERT_EQ(AsEncode(clamped_plan).qp, planned.qp);
const DataSize kOvershoot = planned.target_size * 3;
// Out-of-range sentinels (-1, 256) fall back to `planned.qp`; an in-range QP
// diverging widely from `planned.qp` (e.g. from caller-side clamping) is
// honored.
const int widely_shifted_qp =
planned.qp + 80 < 256 ? planned.qp + 80 : planned.qp - 80;
reference.controller().OnFrameEncoded(
ref_plan.id, {.encoded_size = kOvershoot, .qp = planned.qp});
negative_qp.controller().OnFrameEncoded(
neg_plan.id, {.encoded_size = kOvershoot, .qp = -1});
too_high_qp.controller().OnFrameEncoded(
high_plan.id, {.encoded_size = kOvershoot, .qp = 256});
clamped_qp.controller().OnFrameEncoded(
clamped_plan.id, {.encoded_size = kOvershoot, .qp = widely_shifted_qp});
for (Harness* h : {&reference, &negative_qp, &too_high_qp, &clamped_qp}) {
h->AdvanceTime(h->duration());
}
const int next_ref = AsEncode(reference.StartNextFrame()).qp;
EXPECT_EQ(AsEncode(negative_qp.StartNextFrame()).qp, next_ref);
EXPECT_EQ(AsEncode(too_high_qp.StartNextFrame()).qp, next_ref);
if (widely_shifted_qp > planned.qp) {
EXPECT_GT(AsEncode(clamped_qp.StartNextFrame()).qp, next_ref);
} else {
EXPECT_LT(AsEncode(clamped_qp.StartNextFrame()).qp, next_ref);
}
}
TEST(BufferLevelRateControllerTest, ReplanFollowedByDropForcesMaxQp) {
OvershootSetup setup({.reencode_overshoot = true});
const EncodeFrame& initial = AsEncode(setup.plan);
const FramePlan retry = setup.harness.controller().ReplanFrame(
setup.plan.id, {.encoded_size = setup.kHugeSize, .qp = initial.qp});
EXPECT_EQ(retry.id, setup.plan.id);
EXPECT_GT(AsEncode(retry).qp, initial.qp);
// Giving up after a `ReplanFrame` passes `std::nullopt` to `OnFrameDropped`,
// which still treats the frame as a post-encode drop and forces max QP next.
setup.harness.controller().OnFrameDropped(setup.plan.id, std::nullopt);
setup.harness.AdvanceTime(setup.harness.duration());
EXPECT_EQ(AsEncode(setup.harness.StartNextFrame()).qp, 255);
}
TEST(BufferLevelRateControllerTest,
FastRecoverySpeedsQpConvergenceAfterOvershoot) {
std::array<int, 2> recovered_qp = {};
for (bool fast_recovery : {false, true}) {
Harness harness(
{.scene_change_high_qp = true, .fast_recovery = fast_recovery});
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30,
ContentHint::kFluid);
harness.SetMotionStep(2);
harness.EncodeFor(TimeDelta::Seconds(2));
harness.TriggerSceneJump();
harness.EncodeNextFrame();
// Easy content right after the scene change should pull QP down faster when
// `fast_recovery` is enabled.
harness.encoder().set_complexity(0.05);
recovered_qp[fast_recovery] =
harness.EncodeFor(TimeDelta::Millis(400)).back().qp();
}
EXPECT_LT(recovered_qp[1], recovered_qp[0]);
}
TEST(BufferLevelRateControllerTest, BaseLayerQpPushLowersSingleLayerQp) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
BufferLevelRateController baseline({.base_layer_qp_push = 0});
BufferLevelRateController pushed({.base_layer_qp_push = 10});
const TemporalUnitSettings tu0(Timestamp::Zero());
const FrameEncodeSettings kf_settings =
MakeFrameSettings(FrameType::kKeyframe);
const FramePlan kf_base = baseline.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu0,
.frame_settings = kf_settings});
const FramePlan kf_push = pushed.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu0,
.frame_settings = kf_settings});
baseline.OnFrameEncoded(kf_base.id,
{.encoded_size = AsEncode(kf_base).target_size});
pushed.OnFrameEncoded(kf_push.id,
{.encoded_size = AsEncode(kf_push).target_size});
const TemporalUnitSettings tu1(Timestamp::Zero() + kDuration);
const FrameEncodeSettings delta_settings =
MakeFrameSettings(FrameType::kDeltaFrame);
const EncodeFrame delta_base =
AsEncode(baseline.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu1,
.frame_settings = delta_settings}));
const EncodeFrame delta_push =
AsEncode(pushed.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu1,
.frame_settings = delta_settings}));
EXPECT_LT(delta_push.qp, delta_base.qp);
}
TEST(BufferLevelRateControllerTest, KeyframeRecoveryLowersPostKeyframeQp) {
const DataRate kBitrate = DataRate::KilobitsPerSec(500);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
BufferLevelRateController without_recovery({.keyframe_recovery = false});
BufferLevelRateController with_recovery({.keyframe_recovery = true});
const TemporalUnitSettings tu0(Timestamp::Zero());
const FrameEncodeSettings kf_settings =
MakeFrameSettings(FrameType::kKeyframe);
const FramePlan kf_without =
without_recovery.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu0,
.frame_settings = kf_settings});
const FramePlan kf_with =
with_recovery.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu0,
.frame_settings = kf_settings});
const EncodeFrame& kf = AsEncode(kf_without);
ASSERT_EQ(AsEncode(kf_with).qp, kf.qp);
without_recovery.OnFrameEncoded(
kf_without.id, {.encoded_size = kf.target_size, .qp = kf.qp});
with_recovery.OnFrameEncoded(kf_with.id,
{.encoded_size = kf.target_size, .qp = kf.qp});
// Immediately after the keyframe, `keyframe_recovery` weighs in the keyframe
// QP itself rather than only its slowly moving average, keeping the first
// delta frame at a strictly lower QP.
const TemporalUnitSettings tu1(Timestamp::Zero() + kDuration);
const FrameEncodeSettings delta_settings =
MakeFrameSettings(FrameType::kDeltaFrame);
const EncodeFrame delta_without =
AsEncode(without_recovery.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu1,
.frame_settings = delta_settings}));
const EncodeFrame delta_with =
AsEncode(with_recovery.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu1,
.frame_settings = delta_settings}));
EXPECT_LT(delta_with.qp, delta_without.qp);
}
TEST(BufferLevelRateControllerTest,
RepeatFramesPreserveLayerBudgetsAndResumeCleanly) {
// Mirrors `drop_repeat_frames_on_enhancement_layers_` on an L1T3 screencast:
// active L1T3 -> quality-convergence repeat frames (only TL0 every 4 slots)
// -> keep-alive repeat frames (TL0 every 1 s with `allow_drop = false`) ->
// sudden user activity resuming on T1 then T2.
const DataRate kTotalBitrate = DataRate::KilobitsPerSec(1000);
const LayerBitrates kRates = ThreeLayers(kTotalBitrate);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
const DataSize kTl0Budget = kRates[0] * (4 * kDuration);
const DataSize kTl1Budget = kRates[1] * (4 * kDuration);
const DataSize kTl2Budget = kRates[2] * (2 * kDuration);
BufferLevelRateController controller(
{.drop_frames_water_mark_pct = 30, .max_buffer_credit_pct = 0});
SyntheticEncoder encoder;
Timestamp timestamp = Timestamp::Zero();
// 1. Active L1T3 steady state (2 seconds).
for (int i = 0; i < 60; ++i) {
const int tid = TemporalIdOf(i, /*num_temporal_layers=*/3);
const FrameType type =
i == 0 ? FrameType::kKeyframe : FrameType::kDeltaFrame;
const TemporalUnitSettings tu(ContentHint::kText, timestamp);
const FrameEncodeSettings settings = MakeFrameSettings(type, tid);
const FramePlan plan = controller.PlanFrame({.target_bitrate = kRates[tid],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
const EncodeFrame& enc = AsEncode(plan);
const DataSize size = encoder.Encode(enc.qp, kResolution, type, tid);
controller.OnFrameEncoded(plan.id, {.encoded_size = size, .qp = enc.qp});
timestamp += kDuration;
}
// 2. Quality-convergence repeat frames: enhancement frames are dropped
// upstream, so only TL0 arrives every 4 slots (133 ms) while keeping its
// non-cumulative bitrate and nominal 33 ms duration. TL0 must keep its full
// 4-slot budget rather than collapsing to a 1-slot single-layer budget.
for (int i = 0; i < 8; ++i) {
const TemporalUnitSettings tu(ContentHint::kText, timestamp);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame, /*temporal_id=*/0);
const FramePlan plan = controller.PlanFrame({.target_bitrate = kRates[0],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
const EncodeFrame& enc = AsEncode(plan);
// Allow normal +/-25% P-frame buffer adjustment on the first convergence
// frame; once the buffer refills from static frames, target stays right on
// `kTl0Budget` (~8333 B, not collapsed 4x to ~2083 B).
const double tolerance = i == 0 ? 0.26 : 0.10;
EXPECT_THAT(enc.target_size.bytes<double>(),
DoubleNear(kTl0Budget.bytes<double>(),
kTl0Budget.bytes<double>() * tolerance))
<< "convergence frame " << i;
controller.OnFrameEncoded(
plan.id, {.encoded_size = DataSize::Bytes(80), .qp = enc.qp});
timestamp += 4 * kDuration;
}
// 3. Keep-alive repeat frames (1 Hz, `allow_drop = false`): TL0 keeps its
// budget and never drops.
for (int i = 0; i < 3; ++i) {
timestamp += TimeDelta::Seconds(1);
const TemporalUnitSettings tu(ContentHint::kText, timestamp);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame, /*temporal_id=*/0);
const FramePlan plan = controller.PlanFrame({.target_bitrate = kRates[0],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings,
.allow_drop = false});
ASSERT_FALSE(IsDrop(plan));
const EncodeFrame& enc = AsEncode(plan);
EXPECT_THAT(enc.target_size.bytes<double>(),
DoubleNear(kTl0Budget.bytes<double>(),
kTl0Budget.bytes<double>() * 0.15))
<< "keep-alive frame " << i;
controller.OnFrameEncoded(
plan.id, {.encoded_size = DataSize::Bytes(80), .qp = enc.qp});
}
// 4. User activity resumes on T1 first (2 slots after TL0), then T2 (1 slot
// later): both layers immediately use their own budgets and keep their
// pre-idle QP models rather than starting at min_qp or 2x budget.
timestamp += 2 * kDuration;
{
const TemporalUnitSettings tu(ContentHint::kText, timestamp);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame, /*temporal_id=*/1);
const FramePlan t1_plan =
controller.PlanFrame({.target_bitrate = kRates[1],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
const EncodeFrame& t1 = AsEncode(t1_plan);
EXPECT_THAT(t1.target_size.bytes<double>(),
DoubleNear(kTl1Budget.bytes<double>(),
kTl1Budget.bytes<double>() * 0.15));
EXPECT_GT(t1.qp, 30);
const DataSize size =
encoder.Encode(t1.qp, kResolution, FrameType::kDeltaFrame, 1);
controller.OnFrameEncoded(t1_plan.id, {.encoded_size = size, .qp = t1.qp});
}
timestamp += kDuration;
{
const TemporalUnitSettings tu(ContentHint::kText, timestamp);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame, /*temporal_id=*/2);
const FramePlan t2_plan =
controller.PlanFrame({.target_bitrate = kRates[2],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
const EncodeFrame& t2 = AsEncode(t2_plan);
EXPECT_THAT(t2.target_size.bytes<double>(),
DoubleNear(kTl2Budget.bytes<double>(),
kTl2Budget.bytes<double>() * 0.15));
EXPECT_GT(t2.qp, 30);
const DataSize size =
encoder.Encode(t2.qp, kResolution, FrameType::kDeltaFrame, 2);
controller.OnFrameEncoded(t2_plan.id, {.encoded_size = size, .qp = t2.qp});
}
// Resumed active L1T3 converges back to target bitrate.
std::vector<FrameResult> resumed;
for (int i = 0; i < 120; ++i) {
timestamp += kDuration;
const int tid = TemporalIdOf(i, /*num_temporal_layers=*/3);
const TemporalUnitSettings tu(ContentHint::kText, timestamp);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame, tid);
const FramePlan plan = controller.PlanFrame({.target_bitrate = kRates[tid],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
if (IsDrop(plan)) {
controller.OnFrameDropped(plan.id, std::nullopt);
resumed.push_back({.plan = plan,
.frame_type = FrameType::kDeltaFrame,
.temporal_id = tid,
.duration = kDuration,
.encoded_size = DataSize::Zero()});
continue;
}
const EncodeFrame& enc = AsEncode(plan);
const DataSize size =
encoder.Encode(enc.qp, kResolution, FrameType::kDeltaFrame, tid);
controller.OnFrameEncoded(plan.id, {.encoded_size = size, .qp = enc.qp});
resumed.push_back({.plan = plan,
.frame_type = FrameType::kDeltaFrame,
.temporal_id = tid,
.duration = kDuration,
.encoded_size = size});
}
EXPECT_THAT(RateRatio(resumed, kTotalBitrate, 60), DoubleNear(1.0, 0.1));
}
TEST(BufferLevelRateControllerTest, AllowDropFalsePreventsPreEncodeDrop) {
BufferLevelRateController controller(
{.drop_frames_water_mark_pct = 30, .max_buffer_credit_pct = 0});
const DataRate kBitrate = DataRate::KilobitsPerSec(500);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
Timestamp timestamp = Timestamp::Zero();
// Keyframe, then an oversized delta frame that drains the buffer below 0.
{
const TemporalUnitSettings tu(timestamp);
const FrameEncodeSettings kf = MakeFrameSettings(FrameType::kKeyframe);
const FramePlan p0 = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu,
.frame_settings = kf});
controller.OnFrameEncoded(p0.id, {.encoded_size = DataSize::Bytes(60'000)});
}
// With `allow_drop = true`, the negative buffer triggers a pre-encode drop.
timestamp += kDuration;
{
const TemporalUnitSettings tu(timestamp);
const FrameEncodeSettings delta = MakeFrameSettings(FrameType::kDeltaFrame);
const FramePlan drop_plan =
controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu,
.frame_settings = delta,
.allow_drop = true});
EXPECT_TRUE(IsDrop(drop_plan));
controller.OnFrameDropped(drop_plan.id, std::nullopt);
}
// With `allow_drop = false` (e.g. a keep-alive frame), `PlanFrame` must
// still return an `EncodeFrame` even while the buffer is negative.
timestamp += kDuration;
{
const TemporalUnitSettings tu(timestamp);
const FrameEncodeSettings delta = MakeFrameSettings(FrameType::kDeltaFrame);
const FramePlan forced_plan =
controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu,
.frame_settings = delta,
.allow_drop = false});
ASSERT_FALSE(IsDrop(forced_plan));
EXPECT_GE(AsEncode(forced_plan).qp, 1);
controller.OnFrameEncoded(forced_plan.id,
{.encoded_size = DataSize::Bytes(100)});
}
}
TEST(BufferLevelRateControllerTest,
ReplanFrameHandlesClampedAndOutOfRangeQpMonotonically) {
Harness harness({.reencode_overshoot = true});
harness.SetStream(SingleLayer(DataRate::KilobitsPerSec(1000)), 30);
harness.EncodeFor(TimeDelta::Seconds(2));
const FramePlan plan = harness.StartNextFrame();
int current_qp = AsEncode(plan).qp;
ASSERT_GT(current_qp, 80);
ASSERT_LT(current_qp, 200);
// Widely clamped low QP, negative sentinel, INT_MAX, and a rounded-down QP
// must all strictly advance `planned_qp` without overflowing or regressing.
for (int reported_qp :
{20, -1, std::numeric_limits<int>::max(), current_qp - 2}) {
const FramePlan retry = harness.controller().ReplanFrame(
plan.id,
{.encoded_size = AsEncode(plan).target_size / 2, .qp = reported_qp});
const int next_qp = AsEncode(retry).qp;
EXPECT_GT(next_qp, current_qp) << "reported_qp=" << reported_qp;
current_qp = next_qp;
}
}
TEST(BufferLevelRateControllerTest,
PipelinedDropStateAndForceMaxQpStayConsistent) {
// 1. Pipelined pre-encode drop state respects `max_consecutive_drop` even
// when multiple plans are issued before earlier frames retire.
{
const DataRate kBitrate = DataRate::KilobitsPerSec(500);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
BufferLevelRateController controller(
{.drop_frames_water_mark_pct = 30,
.max_consecutive_drop = 2 * kDuration});
Timestamp ts = Timestamp::Zero();
// Frame 0: large overshoot depletes the buffer below 0.
const TemporalUnitSettings tu0(ts);
const FrameEncodeSettings kf = MakeFrameSettings(FrameType::kKeyframe);
const FramePlan p0 = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu0,
.frame_settings = kf});
controller.OnFrameEncoded(p0.id, {.encoded_size = DataSize::Bytes(60'000)});
// Plan 3 frames back-to-back before retiring any of them: the first 2 are
// dropped, and the 3rd must encode due to `max_consecutive_drop`.
std::vector<FramePlan> plans;
for (int i = 0; i < 3; ++i) {
ts += kDuration;
const TemporalUnitSettings tu(ts);
const FrameEncodeSettings delta =
MakeFrameSettings(FrameType::kDeltaFrame);
plans.push_back(controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu,
.frame_settings = delta}));
}
EXPECT_TRUE(IsDrop(plans[0]));
EXPECT_TRUE(IsDrop(plans[1]));
EXPECT_FALSE(IsDrop(plans[2]));
}
// 2. An in-flight frame planned before a post-encode drop must not clear
// `force_max_qp` when it finishes encoding; the next planned delta frame
// must still get max QP, while a keyframe is not forced to max QP.
{
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
BufferLevelRateController controller({.postencode_drop = true});
Timestamp ts = Timestamp::Zero();
// Keyframe.
const TemporalUnitSettings tu0(ts);
const FrameEncodeSettings kf = MakeFrameSettings(FrameType::kKeyframe);
const FramePlan p0 = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu0,
.frame_settings = kf});
controller.OnFrameEncoded(p0.id,
{.encoded_size = AsEncode(p0).target_size});
// Plan Frame 1 and Frame 2 while both are in flight.
ts += kDuration;
const TemporalUnitSettings tu1(ts);
const FrameEncodeSettings delta = MakeFrameSettings(FrameType::kDeltaFrame);
const FramePlan p1 = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu1,
.frame_settings = delta});
ts += kDuration;
const TemporalUnitSettings tu2(ts);
const FramePlan p2 = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu2,
.frame_settings = delta});
// Frame 1 triggers a post-encode drop (sets `force_max_qp = true`).
controller.OnFrameDropped(
p1.id, EncodedFrameStats{.encoded_size = DataSize::Bytes(100'000),
.qp = AsEncode(p1).qp});
// Frame 2 (planned earlier, not at forced max QP) completes encoding.
controller.OnFrameEncoded(p2.id, {.encoded_size = AsEncode(p2).target_size,
.qp = AsEncode(p2).qp});
// Frame 3 (keyframe) must NOT be forced to max QP.
ts += kDuration;
const TemporalUnitSettings tu3(ts);
const FramePlan p3_kf = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu3,
.frame_settings = kf});
EXPECT_LT(AsEncode(p3_kf).qp, 255);
controller.OnFrameEncoded(p3_kf.id,
{.encoded_size = AsEncode(p3_kf).target_size});
// Frame 4 (delta) still receives the forced max QP since neither Frame 2
// nor the keyframe consumed it.
ts += kDuration;
const TemporalUnitSettings tu4(ts);
const FramePlan p4 = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu4,
.frame_settings = delta});
EXPECT_EQ(AsEncode(p4).qp, 255);
}
}
TEST(BufferLevelRateControllerTest,
SingleLayerShortPausesDoNotInflateTargetOrEnableMultiLayerPush) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
const DataSize kNominalBudget = kBitrate * kDuration;
BufferLevelRateController controller({.max_buffer_credit_pct = 0});
Timestamp ts = Timestamp::Zero();
// Warm up at steady 30 fps.
for (int i = 0; i < 30; ++i) {
const FrameType type =
i == 0 ? FrameType::kKeyframe : FrameType::kDeltaFrame;
const TemporalUnitSettings tu(ContentHint::kText, ts);
const FrameEncodeSettings settings = MakeFrameSettings(type);
const FramePlan plan = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
controller.OnFrameEncoded(plan.id,
{.encoded_size = AsEncode(plan).target_size});
ts += kDuration;
}
// Short pauses of 2, 6, and 9 slots (67 ms, 200 ms, 300 ms) while keeping
// `duration = 33 ms` must NEVER inflate TL0's frame budget.
for (int gap_slots : {2, 6, 9, 2, 2}) {
ts += gap_slots * kDuration;
const TemporalUnitSettings tu(ContentHint::kText, ts);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame);
const FramePlan plan = controller.PlanFrame({.target_bitrate = kBitrate,
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
const EncodeFrame& enc = AsEncode(plan);
EXPECT_THAT(enc.target_size.bytes<double>(),
DoubleNear(kNominalBudget.bytes<double>(),
kNominalBudget.bytes<double>() * 0.05))
<< "gap_slots=" << gap_slots;
controller.OnFrameEncoded(plan.id, {.encoded_size = enc.target_size});
}
}
TEST(BufferLevelRateControllerTest,
ResumingUpperLayersAfterSingleLayerComplexityJumpInheritsCurrentQp) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
Harness harness({.max_buffer_credit_pct = 0});
// 1. Run L1T3 on easy content so all layers converge to low QP (< 90).
harness.SetStream(ThreeLayers(kBitrate), 30);
harness.encoder().set_complexity(0.1);
const std::vector<FrameResult> easy =
harness.EncodeFor(TimeDelta::Seconds(3));
ASSERT_LT(easy.back().qp(), 90);
// 2. Switch to L1T1 and increase complexity 20x so TL0 adapts to high QP.
harness.SetStream(SingleLayer(kBitrate), 30);
harness.encoder().set_complexity(2.0);
const std::vector<FrameResult> hard =
harness.EncodeFor(TimeDelta::Seconds(3));
const int hard_tl0_qp = hard.back().qp();
ASSERT_GT(hard_tl0_qp, 160);
// 3. Switch back to L1T3: retired upper layers must freshly inherit TL0's
// high QP envelope rather than keeping the stale low QP (< 90) from phase 1.
harness.SetStream(ThreeLayers(kBitrate), 30);
for (int i = 0; i < 4; ++i) {
const FrameResult res = harness.EncodeNextFrame();
EXPECT_GT(res.qp(), 120) << "frame " << i << " tid " << res.temporal_id;
}
// 4. Transition L1T3 -> L1T1 -> L1T2: TL1 must get its 2-slot L1T2 budget
// (~4167 B at 500 kbps), not a frozen 4-slot L1T3 budget (~8333 B).
harness.SetStream(SingleLayer(kBitrate), 30);
harness.EncodeFor(TimeDelta::Seconds(1));
const LayerBitrates two_layers = {kBitrate * 0.5, kBitrate * 0.5};
const DataSize kL1T2LayerBudget = (kBitrate * 0.5) * (2 * harness.duration());
const TimeDelta kDuration = harness.duration();
Timestamp ts = harness.current_timestamp();
// Feed explicit L1T2 cadence (T0, T1, T0, T1).
for (int i = 0; i < 4; ++i) {
const int tid = i % 2;
const TemporalUnitSettings tu(ts);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame, tid);
const FramePlan plan =
harness.controller().PlanFrame({.target_bitrate = two_layers[tid],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
const EncodeFrame& enc = AsEncode(plan);
if (tid == 1) {
EXPECT_THAT(enc.target_size.bytes<double>(),
DoubleNear(kL1T2LayerBudget.bytes<double>(),
kL1T2LayerBudget.bytes<double>() * 0.25))
<< "i=" << i;
}
harness.controller().OnFrameEncoded(
plan.id, {.encoded_size = enc.target_size, .qp = enc.qp});
ts += kDuration;
}
}
TEST(BufferLevelRateControllerTest,
BitrateDropOnL1T3ScalesUnvisitedLayersImmediately) {
const DataRate kHigh = DataRate::KilobitsPerSec(2000);
const DataRate kLow = DataRate::KilobitsPerSec(400);
Harness harness({.reencode_overshoot = true, .max_buffer_credit_pct = 0});
harness.SetStream(ThreeLayers(kHigh), 30);
harness.encoder().set_complexity(0.25);
harness.EncodeFor(TimeDelta::Seconds(2));
// Align to TL0, then drop total bitrate 5x (2000 -> 400 kbps).
while (harness.NextTemporalId() != 0) {
harness.EncodeNextFrame();
}
harness.SetStream(ThreeLayers(kLow), 30);
// Frame 0 at new rate: TL0 (1000 -> 200 kbps).
harness.EncodeNextFrame();
// Frame 1 at new rate: TL2 arrives BEFORE TL1 has been updated. Because
// TL1's estimate scaled proportionally, `CheckEncodedFrame` evaluates
// against 400 kbps (8x budget = 13.3 KB, 25 KB drains 500 ms -> below 25%
// of 600 ms target) rather than stale 800 kbps (8x budget = 26.7 KB, 25 KB
// only drains 250 ms), so a 25 KB overshoot triggers `kReencode`.
ASSERT_EQ(harness.NextTemporalId(), 2);
const FramePlan t2_plan = harness.StartNextFrame();
ASSERT_LT(AsEncode(t2_plan).qp, 191);
EXPECT_EQ(harness.controller().CheckEncodedFrame(
t2_plan.id, {.encoded_size = DataSize::Bytes(25'000),
.qp = AsEncode(t2_plan).qp}),
Verdict::kReencode);
}
TEST(BufferLevelRateControllerTest,
NonProportionalSplitChangeAndRampDoNotOscillateLayerBitrates) {
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
Harness harness({.reencode_overshoot = true, .max_buffer_credit_pct = 0});
// Start in steady-state L1T3 with a 50/25/25 split (1000/500/500 kbps).
harness.SetStream(ThreeLayers(DataRate::KilobitsPerSec(2000)), 30);
harness.encoder().set_complexity(0.25);
harness.EncodeFor(TimeDelta::Seconds(2));
while (harness.NextTemporalId() != 0) {
harness.EncodeNextFrame();
}
// Shift to a non-proportional 60/20/20 split (600/200/200 kbps) for one GOP.
const LayerBitrates kShifted = {DataRate::KilobitsPerSec(600),
DataRate::KilobitsPerSec(200),
DataRate::KilobitsPerSec(200)};
Timestamp ts = harness.current_timestamp();
for (int tid : {0, 2, 1, 2}) {
const TemporalUnitSettings tu(ts);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame, tid);
const FramePlan plan =
harness.controller().PlanFrame({.target_bitrate = kShifted[tid],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
const EncodeFrame& enc = AsEncode(plan);
harness.controller().OnFrameEncoded(
plan.id, {.encoded_size = enc.target_size, .qp = enc.qp});
ts += kDuration;
}
// Ramp slightly (+1%: 606/202/202 kbps = 1010 kbps total). Without tracking
// `bitrate_estimated`, TL2 in the previous GOP clobbered TL0 to 400 kbps,
// causing TL0's ramp here to rescale TL1/TL2 by +51% and TL2 to clobber TL0
// back down to 404 kbps (`CumulativeBitrate(2)` = 808 kbps instead of 1010).
const LayerBitrates kRamped = {DataRate::KilobitsPerSec(606),
DataRate::KilobitsPerSec(202),
DataRate::KilobitsPerSec(202)};
{
const TemporalUnitSettings tu(ts);
const FrameEncodeSettings settings =
MakeFrameSettings(FrameType::kDeltaFrame, /*temporal_id=*/0);
const FramePlan t0_plan =
harness.controller().PlanFrame({.target_bitrate = kRamped[0],
.duration = kDuration,
.tu_settings = tu,
.frame_settings = settings});
// Drain the buffer partway (~277 ms at 1010 kbps) so
// `projected_buffer_level` on the next frame drops below 25% of target if
// an overshoot occurs.
harness.controller().OnFrameEncoded(
t0_plan.id,
{.encoded_size = DataSize::Bytes(35'000), .qp = AsEncode(t0_plan).qp});
ts += kDuration;
}
const TemporalUnitSettings t2_tu(ts);
const FrameEncodeSettings t2_settings =
MakeFrameSettings(FrameType::kDeltaFrame, /*temporal_id=*/2);
const FramePlan t2_plan =
harness.controller().PlanFrame({.target_bitrate = kRamped[2],
.duration = kDuration,
.tu_settings = t2_tu,
.frame_settings = t2_settings});
ASSERT_LT(AsEncode(t2_plan).qp, 191);
// At the true 1010 kbps cumulative rate, 8x `avg_frame_bandwidth` is ~33.7 KB
// so 30 KB is accepted; at the corrupted 808 kbps rate, 8x is ~26.9 KB and
// projected buffer drops below 150 ms, falsely triggering `kReencode`.
EXPECT_EQ(harness.controller().CheckEncodedFrame(
t2_plan.id, {.encoded_size = DataSize::Bytes(30'000),
.qp = AsEncode(t2_plan).qp}),
Verdict::kAccept);
}
TEST(BufferLevelRateControllerTest,
PipelinedLayerCountShrinkWaitsForInFlightUpperLayerFrame) {
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
const TimeDelta kDuration = TimeDelta::Seconds(1) / 30;
Harness harness({.reencode_overshoot = true, .max_buffer_credit_pct = 0});
harness.SetStream(ThreeLayers(kBitrate), 30);
harness.encoder().set_complexity(0.25);
harness.EncodeFor(TimeDelta::Seconds(2));
while (harness.NextTemporalId() != 2) {
harness.EncodeNextFrame();
}
// Keep a TL2 frame in flight while the stream switches immediately to L1T1.
const FramePlan in_flight_t2 = harness.StartNextFrame();
const EncodeFrame& t2_enc = AsEncode(in_flight_t2);
ASSERT_LT(t2_enc.qp, 191);
harness.AdvanceTime(kDuration);
harness.SetStream(SingleLayer(kBitrate), 30);
for (int i = 0; i < 2; ++i) {
const FramePlan t0_plan = harness.StartNextFrame();
const EncodeFrame& t0_enc = AsEncode(t0_plan);
harness.controller().OnFrameEncoded(
t0_plan.id, {.encoded_size = t0_enc.target_size, .qp = t0_enc.qp});
harness.AdvanceTime(kDuration);
}
// `layers_[2]` must remain initialized and retain its buffer state until the
// in-flight TL2 frame completes: a 40 KB encode (~320 ms at 1000 kbps) leaves
// the real ~600 ms buffer well above 150 ms (`kAccept`), whereas a
// prematurely zeroed layer buffer would project negative and falsely trigger
// `kReencode`.
EXPECT_EQ(harness.controller().CheckEncodedFrame(
in_flight_t2.id,
{.encoded_size = DataSize::Bytes(40'000), .qp = t2_enc.qp}),
Verdict::kAccept);
harness.controller().OnFrameEncoded(
in_flight_t2.id, {.encoded_size = t2_enc.target_size, .qp = t2_enc.qp});
// Once the in-flight TL2 frame retires, subsequent L1T1 TL0 frames retire
// the upper layers and use the full 1-slot single-layer budget.
const DataSize kSingleLayerBudget = kBitrate * kDuration;
for (int i = 0; i < 2; ++i) {
const FramePlan t0_plan = harness.StartNextFrame();
const EncodeFrame& t0_enc = AsEncode(t0_plan);
if (i == 1) {
EXPECT_THAT(t0_enc.target_size.bytes<double>(),
DoubleNear(kSingleLayerBudget.bytes<double>(),
kSingleLayerBudget.bytes<double>() * 0.15));
}
harness.controller().OnFrameEncoded(
t0_plan.id, {.encoded_size = t0_enc.target_size, .qp = t0_enc.qp});
harness.AdvanceTime(kDuration);
}
}
TEST(BufferLevelRateControllerTest,
ReplanFrameUpdatesActiveTargetSizeForCheckAndPipelining) {
const BufferLevelRateControllerConfig kConfig = {
.reencode_overshoot = true,
.reencode_target_factor = 12.0,
.max_buffer_credit_pct = 0};
const DataRate kBitrate = DataRate::KilobitsPerSec(1000);
// 1. Pipelined frames planned while a replanned frame is still in flight
// account for its boosted `current_target_size` in `InFlightDuration`.
Harness replanned(kConfig);
Harness baseline(kConfig);
for (Harness* h : {&replanned, &baseline}) {
h->SetStream(SingleLayer(kBitrate), 30);
h->encoder().set_complexity(0.25);
h->EncodeFor(TimeDelta::Seconds(2));
}
const FramePlan p1_replanned = replanned.StartNextFrame();
const FramePlan p1_baseline = baseline.StartNextFrame();
ASSERT_EQ(AsEncode(p1_baseline).target_size,
AsEncode(p1_replanned).target_size);
const EncodeFrame retry = AsEncode(replanned.controller().ReplanFrame(
p1_replanned.id, {.encoded_size = DataSize::Bytes(60'000),
.qp = AsEncode(p1_replanned).qp}));
ASSERT_GT(retry.target_size, AsEncode(p1_replanned).target_size * 8);
replanned.AdvanceTime(replanned.duration());
baseline.AdvanceTime(baseline.duration());
const FramePlan p2_replanned = replanned.StartNextFrame();
const FramePlan p2_baseline = baseline.StartNextFrame();
EXPECT_LT(AsEncode(p2_replanned).target_size,
AsEncode(p2_baseline).target_size);
// 2. `CheckEncodedFrame` compares against `current_target_size` (~50 KB)
// rather than the unboosted initial target (~4 KB). Complete `p2_replanned`
// with a 30 KB encode so `projected_buffer_level` for `p1_replanned` falls
// below 25% of target, making `accept_size_ceiling` the deciding factor.
ASSERT_LT(retry.qp, 191);
replanned.controller().OnFrameEncoded(
p2_replanned.id, {.encoded_size = DataSize::Bytes(30'000),
.qp = AsEncode(p2_replanned).qp});
const DataSize kUnderRetryTarget = retry.target_size - DataSize::Bytes(1000);
const DataSize kOverRetryTarget = retry.target_size + DataSize::Bytes(1000);
ASSERT_GT(kUnderRetryTarget, AsEncode(p1_replanned).target_size * 8);
EXPECT_EQ(
replanned.controller().CheckEncodedFrame(
p1_replanned.id, {.encoded_size = kUnderRetryTarget, .qp = retry.qp}),
Verdict::kAccept);
EXPECT_EQ(
replanned.controller().CheckEncodedFrame(
p1_replanned.id, {.encoded_size = kOverRetryTarget, .qp = retry.qp}),
Verdict::kReencode);
}
} // namespace
} // namespace webrtc