blob: 9fedf794a90d832e5e10d503827d4f989b278288 [file] [log] [blame]
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001/*
2 * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 *
10 */
11
Mirko Bonadei95adedb2018-11-19 09:52:37 +010012#ifdef RTC_ENABLE_VP9
13
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020014#include "modules/video_coding/codecs/vp9/vp9_impl.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000015
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +020016#include <algorithm>
Sergey Silkind45b3452018-05-31 16:00:24 +020017#include <limits>
marpan@webrtc.org5b883172014-11-01 06:10:48 +000018#include <vector>
19
marpan@webrtc.org5b883172014-11-01 06:10:48 +000020#include "vpx/vp8cx.h"
21#include "vpx/vp8dx.h"
Yves Gerey665174f2018-06-19 15:03:05 +020022#include "vpx/vpx_decoder.h"
23#include "vpx/vpx_encoder.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000024
Karl Wiberg918f50c2018-07-05 11:40:33 +020025#include "absl/memory/memory.h"
Emircan Uysaler800787f2018-07-16 10:01:49 -070026#include "api/video/color_space.h"
Emircan Uysaler0823eec2018-07-13 17:10:00 -070027#include "api/video/i010_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "common_video/include/video_frame_buffer.h"
29#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkind902d582018-05-18 17:31:19 +020030#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020031#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/checks.h"
Erik Språng4b4266f2019-01-23 12:48:13 +010033#include "rtc_base/experiments/rate_control_settings.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/keep_ref_until_done.h"
35#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/trace_event.h"
Sergey Silkin390f3582018-10-01 17:13:50 +020038#include "system_wrappers/include/field_trial.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000039
40namespace webrtc {
41
Sergey Silkind902d582018-05-18 17:31:19 +020042namespace {
Sergey Silkin390f3582018-10-01 17:13:50 +020043// Maps from gof_idx to encoder internal reference frame buffer index. These
44// maps work for 1,2 and 3 temporal layers with GOF length of 1,2 and 4 frames.
45uint8_t kRefBufIdx[4] = {0, 0, 0, 1};
46uint8_t kUpdBufIdx[4] = {0, 0, 1, 0};
47
Sergey Silkinb674cd12018-10-09 10:59:06 +020048int kMaxNumTiles4kVideo = 8;
49
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +010050// Maximum allowed PID difference for differnet per-layer frame-rate case.
Ilya Nikolaevskiy3a656d12019-02-14 14:44:22 +010051const int kMaxAllowedPidDIff = 30;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +010052
Erik Språng7a3fe892019-04-15 12:22:55 +020053constexpr double kLowRateFactor = 1.0;
54constexpr double kHighRateFactor = 2.0;
55
56// These settings correspond to the settings in vpx_codec_enc_cfg.
Erik Språngeb180f82019-05-23 13:55:24 +020057struct Vp9RateSettings {
Erik Språng7a3fe892019-04-15 12:22:55 +020058 uint32_t rc_undershoot_pct;
59 uint32_t rc_overshoot_pct;
60 uint32_t rc_buf_sz;
61 uint32_t rc_buf_optimal_sz;
62 uint32_t rc_dropframe_thresh;
63};
64
Marco6e89b252015-07-07 14:40:38 -070065// Only positive speeds, range for real-time coding currently is: 5 - 8.
66// Lower means slower/better quality, higher means fastest/lower quality.
67int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070068#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080069 return 8;
70#else
Marco6e89b252015-07-07 14:40:38 -070071 // For smaller resolutions, use lower speed setting (get some coding gain at
72 // the cost of increased encoding complexity).
73 if (width * height <= 352 * 288)
74 return 5;
75 else
76 return 7;
Marco002f0d02015-12-17 09:49:31 -080077#endif
Marco6e89b252015-07-07 14:40:38 -070078}
Emircan Uysaler715cc232018-07-23 17:50:43 -070079// Helper class for extracting VP9 colorspace.
80ColorSpace ExtractVP9ColorSpace(vpx_color_space_t space_t,
81 vpx_color_range_t range_t,
82 unsigned int bit_depth) {
Johannes Kronb47ccc32018-12-07 11:12:44 +010083 ColorSpace::PrimaryID primaries = ColorSpace::PrimaryID::kUnspecified;
84 ColorSpace::TransferID transfer = ColorSpace::TransferID::kUnspecified;
85 ColorSpace::MatrixID matrix = ColorSpace::MatrixID::kUnspecified;
Emircan Uysaler715cc232018-07-23 17:50:43 -070086 switch (space_t) {
87 case VPX_CS_BT_601:
88 case VPX_CS_SMPTE_170:
89 primaries = ColorSpace::PrimaryID::kSMPTE170M;
90 transfer = ColorSpace::TransferID::kSMPTE170M;
91 matrix = ColorSpace::MatrixID::kSMPTE170M;
92 break;
93 case VPX_CS_SMPTE_240:
94 primaries = ColorSpace::PrimaryID::kSMPTE240M;
95 transfer = ColorSpace::TransferID::kSMPTE240M;
96 matrix = ColorSpace::MatrixID::kSMPTE240M;
97 break;
98 case VPX_CS_BT_709:
99 primaries = ColorSpace::PrimaryID::kBT709;
100 transfer = ColorSpace::TransferID::kBT709;
101 matrix = ColorSpace::MatrixID::kBT709;
102 break;
103 case VPX_CS_BT_2020:
104 primaries = ColorSpace::PrimaryID::kBT2020;
105 switch (bit_depth) {
106 case 8:
107 transfer = ColorSpace::TransferID::kBT709;
108 break;
109 case 10:
110 transfer = ColorSpace::TransferID::kBT2020_10;
111 break;
112 default:
113 RTC_NOTREACHED();
114 break;
115 }
116 matrix = ColorSpace::MatrixID::kBT2020_NCL;
117 break;
118 case VPX_CS_SRGB:
119 primaries = ColorSpace::PrimaryID::kBT709;
120 transfer = ColorSpace::TransferID::kIEC61966_2_1;
121 matrix = ColorSpace::MatrixID::kBT709;
122 break;
123 default:
124 break;
125 }
126
127 ColorSpace::RangeID range = ColorSpace::RangeID::kInvalid;
128 switch (range_t) {
129 case VPX_CR_STUDIO_RANGE:
130 range = ColorSpace::RangeID::kLimited;
131 break;
132 case VPX_CR_FULL_RANGE:
133 range = ColorSpace::RangeID::kFull;
134 break;
135 default:
136 break;
137 }
138 return ColorSpace(primaries, transfer, matrix, range);
139}
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100140
141bool MoreLayersEnabled(const VideoBitrateAllocation& first,
142 const VideoBitrateAllocation& second) {
143 for (size_t sl_idx = 0; sl_idx < kMaxSpatialLayers; ++sl_idx) {
144 if (first.GetSpatialLayerSum(sl_idx) > 0 &&
145 second.GetSpatialLayerSum(sl_idx) == 0) {
146 return true;
147 }
148 }
149 return false;
150}
151
Erik Språng7a3fe892019-04-15 12:22:55 +0200152uint32_t Interpolate(uint32_t low,
153 uint32_t high,
154 double bandwidth_headroom_factor) {
155 RTC_DCHECK_GE(bandwidth_headroom_factor, kLowRateFactor);
156 RTC_DCHECK_LE(bandwidth_headroom_factor, kHighRateFactor);
157
158 // |factor| is between 0.0 and 1.0.
159 const double factor = bandwidth_headroom_factor - kLowRateFactor;
160
161 return static_cast<uint32_t>(((1.0 - factor) * low) + (factor * high) + 0.5);
162}
163
Erik Språngeb180f82019-05-23 13:55:24 +0200164Vp9RateSettings GetRateSettings(double bandwidth_headroom_factor) {
165 static const Vp9RateSettings low_settings{100u, 0u, 100u, 33u, 40u};
166 static const Vp9RateSettings high_settings{50u, 50u, 1000u, 700u, 5u};
Erik Språng7a3fe892019-04-15 12:22:55 +0200167
168 if (bandwidth_headroom_factor <= kLowRateFactor) {
169 return low_settings;
170 } else if (bandwidth_headroom_factor >= kHighRateFactor) {
171 return high_settings;
172 }
173
Erik Språngeb180f82019-05-23 13:55:24 +0200174 Vp9RateSettings settings;
Erik Språng7a3fe892019-04-15 12:22:55 +0200175 settings.rc_undershoot_pct =
176 Interpolate(low_settings.rc_undershoot_pct,
177 high_settings.rc_undershoot_pct, bandwidth_headroom_factor);
178 settings.rc_overshoot_pct =
179 Interpolate(low_settings.rc_overshoot_pct, high_settings.rc_overshoot_pct,
180 bandwidth_headroom_factor);
181 settings.rc_buf_sz =
182 Interpolate(low_settings.rc_buf_sz, high_settings.rc_buf_sz,
183 bandwidth_headroom_factor);
184 settings.rc_buf_optimal_sz =
185 Interpolate(low_settings.rc_buf_optimal_sz,
186 high_settings.rc_buf_optimal_sz, bandwidth_headroom_factor);
187 settings.rc_dropframe_thresh =
188 Interpolate(low_settings.rc_dropframe_thresh,
189 high_settings.rc_dropframe_thresh, bandwidth_headroom_factor);
190 return settings;
191}
192
193void UpdateRateSettings(vpx_codec_enc_cfg_t* config,
Erik Språngeb180f82019-05-23 13:55:24 +0200194 const Vp9RateSettings& new_settings) {
Erik Språng7a3fe892019-04-15 12:22:55 +0200195 config->rc_undershoot_pct = new_settings.rc_undershoot_pct;
196 config->rc_overshoot_pct = new_settings.rc_overshoot_pct;
197 config->rc_buf_sz = new_settings.rc_buf_sz;
198 config->rc_buf_optimal_sz = new_settings.rc_buf_optimal_sz;
199 config->rc_dropframe_thresh = new_settings.rc_dropframe_thresh;
200}
201
Emircan Uysaler715cc232018-07-23 17:50:43 -0700202} // namespace
Marco6e89b252015-07-07 14:40:38 -0700203
asaperssona9455ab2015-07-31 06:10:09 -0700204void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
205 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -0800206 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -0700207 enc->GetEncodedLayerFrame(pkt);
208}
209
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700210VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000211 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -0700212 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700213 profile_(
214 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000215 inited_(false),
216 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000217 cpu_speed_(3),
218 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -0700219 encoder_(nullptr),
220 config_(nullptr),
221 raw_(nullptr),
222 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200223 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200224 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -0700225 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -0800226 num_spatial_layers_(0),
Sergey Silkin390f3582018-10-01 17:13:50 +0200227 num_active_spatial_layers_(0),
Erik Språngd3438aa2018-11-08 16:56:43 +0100228 layer_deactivation_requires_key_frame_(
229 field_trial::IsEnabled("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation")),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200230 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200231 inter_layer_pred_(InterLayerPredMode::kOn),
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100232 external_ref_control_(false), // Set in InitEncode because of tests.
Erik Språng4b4266f2019-01-23 12:48:13 +0100233 trusted_rate_controller_(RateControlSettings::ParseFromFieldTrials()
234 .LibvpxVp9TrustedRateController()),
Erik Språng7a3fe892019-04-15 12:22:55 +0200235 dynamic_rate_settings_(
236 RateControlSettings::ParseFromFieldTrials().Vp9DynamicRateSettings()),
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100237 full_superframe_drop_(true),
238 first_frame_in_picture_(true),
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100239 ss_info_needed_(false),
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100240 is_flexible_mode_(false),
241 variable_framerate_experiment_(ParseVariableFramerateConfig(
242 "WebRTC-VP9VariableFramerateScreenshare")),
243 variable_framerate_controller_(
244 variable_framerate_experiment_.framerate_limit),
245 num_steady_state_frames_(0) {
philipeld1d03592019-03-01 13:53:55 +0100246 codec_ = {};
johannkoenig8225c402017-01-26 13:23:44 -0800247 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000248}
249
250VP9EncoderImpl::~VP9EncoderImpl() {
251 Release();
252}
253
254int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100255 int ret_val = WEBRTC_VIDEO_CODEC_OK;
256
Niels Möllerdd1cc982019-02-07 18:52:50 +0100257 encoded_image_.Allocate(0);
sprang3958ed82017-08-17 08:12:10 -0700258 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100259 if (inited_) {
260 if (vpx_codec_destroy(encoder_)) {
261 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
262 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000263 }
264 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700265 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000266 }
sprang3958ed82017-08-17 08:12:10 -0700267 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000268 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700269 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000270 }
sprang3958ed82017-08-17 08:12:10 -0700271 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000272 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700273 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000274 }
275 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100276 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000277}
278
sprangce4aef12015-11-02 07:23:20 -0800279bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
280 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
281 // (i.e. bitrates) were explicitly configured.
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200282 return codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800283}
284
Erik Språng566124a2018-04-23 12:32:22 +0200285bool VP9EncoderImpl::SetSvcRates(
286 const VideoBitrateAllocation& bitrate_allocation) {
Sergey Silkin86684962018-03-28 19:32:37 +0200287 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200288
sprangce4aef12015-11-02 07:23:20 -0800289 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200290 const bool layer_activation_requires_key_frame =
291 inter_layer_pred_ == InterLayerPredMode::kOff ||
292 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic;
293
Sergey Silkin86684962018-03-28 19:32:37 +0200294 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200295 const bool was_layer_active = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200296 config_->ss_target_bitrate[sl_idx] =
297 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
298
299 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
300 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
301 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
302 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200303
Sergey Silkine7ce8882018-10-03 18:04:57 +0200304 const bool is_active_layer = (config_->ss_target_bitrate[sl_idx] > 0);
305 if (!was_layer_active && is_active_layer &&
306 layer_activation_requires_key_frame) {
307 force_key_frame_ = true;
308 } else if (was_layer_active && !is_active_layer &&
309 layer_deactivation_requires_key_frame_) {
310 force_key_frame_ = true;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200311 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200312
Sergey Silkine7ce8882018-10-03 18:04:57 +0200313 if (!was_layer_active) {
Sergey Silkin96f2c972018-09-05 21:07:17 +0200314 // Reset frame rate controller if layer is resumed after pause.
315 framerate_controller_[sl_idx].Reset();
316 }
317
318 framerate_controller_[sl_idx].SetTargetRate(
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200319 codec_.spatialLayers[sl_idx].maxFramerate);
sprangce4aef12015-11-02 07:23:20 -0800320 }
321 } else {
322 float rate_ratio[VPX_MAX_LAYERS] = {0};
323 float total = 0;
Sergey Silkin908689d2018-08-20 09:28:45 +0200324 for (int i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800325 if (svc_params_.scaling_factor_num[i] <= 0 ||
326 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100327 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800328 return false;
329 }
Yves Gerey665174f2018-06-19 15:03:05 +0200330 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
331 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800332 total += rate_ratio[i];
333 }
334
Sergey Silkin908689d2018-08-20 09:28:45 +0200335 for (int i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200336 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800337 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
338 config_->rc_target_bitrate * rate_ratio[i] / total);
339 if (num_temporal_layers_ == 1) {
340 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
341 } else if (num_temporal_layers_ == 2) {
342 config_->layer_target_bitrate[i * num_temporal_layers_] =
343 config_->ss_target_bitrate[i] * 2 / 3;
344 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
345 config_->ss_target_bitrate[i];
346 } else if (num_temporal_layers_ == 3) {
347 config_->layer_target_bitrate[i * num_temporal_layers_] =
348 config_->ss_target_bitrate[i] / 2;
349 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
350 config_->layer_target_bitrate[i * num_temporal_layers_] +
351 (config_->ss_target_bitrate[i] / 4);
352 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
353 config_->ss_target_bitrate[i];
354 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100355 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
356 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800357 return false;
358 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200359
360 framerate_controller_[i].SetTargetRate(codec_.maxFramerate);
asaperssona9455ab2015-07-31 06:10:09 -0700361 }
362 }
Sergey Silkin908689d2018-08-20 09:28:45 +0200363
364 num_active_spatial_layers_ = 0;
365 for (int i = 0; i < num_spatial_layers_; ++i) {
366 if (config_->ss_target_bitrate[i] > 0) {
367 ++num_active_spatial_layers_;
368 }
369 }
370 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
371
asaperssona9455ab2015-07-31 06:10:09 -0700372 return true;
373}
374
Erik Språng16cb8f52019-04-12 13:59:09 +0200375void VP9EncoderImpl::SetRates(const RateControlParameters& parameters) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000376 if (!inited_) {
Erik Språng16cb8f52019-04-12 13:59:09 +0200377 RTC_LOG(LS_WARNING) << "SetRates() calll while uninitialzied.";
378 return;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000379 }
380 if (encoder_->err) {
Erik Språng16cb8f52019-04-12 13:59:09 +0200381 RTC_LOG(LS_WARNING) << "Encoder in error state: " << encoder_->err;
382 return;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000383 }
Erik Språng16cb8f52019-04-12 13:59:09 +0200384 if (parameters.framerate_fps < 1.0) {
385 RTC_LOG(LS_WARNING) << "Unsupported framerate: "
386 << parameters.framerate_fps;
387 return;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000388 }
389 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100390 if (codec_.maxBitrate > 0 &&
Erik Språng16cb8f52019-04-12 13:59:09 +0200391 parameters.bitrate.get_sum_kbps() > codec_.maxBitrate) {
392 RTC_LOG(LS_WARNING) << "Target bitrate exceeds maximum: "
393 << parameters.bitrate.get_sum_kbps() << " vs "
394 << codec_.maxBitrate;
395 return;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000396 }
Erik Språng08127a92016-11-16 16:41:30 +0100397
Erik Språng16cb8f52019-04-12 13:59:09 +0200398 codec_.maxFramerate = static_cast<uint32_t>(parameters.framerate_fps + 0.5);
Erik Språng7a3fe892019-04-15 12:22:55 +0200399 requested_rate_settings_ = parameters;
asaperssona9455ab2015-07-31 06:10:09 -0700400
Erik Språng16cb8f52019-04-12 13:59:09 +0200401 return;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000402}
403
404int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
405 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000406 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700407 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000408 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
409 }
410 if (inst->maxFramerate < 1) {
411 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
412 }
413 // Allow zero to represent an unspecified maxBitRate
414 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
415 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
416 }
417 if (inst->width < 1 || inst->height < 1) {
418 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
419 }
420 if (number_of_cores < 1) {
421 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
422 }
hta257dc392016-10-25 09:05:06 -0700423 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700424 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
425 }
ilnik2a8c2f52017-02-15 02:23:28 -0800426 // libvpx probably does not support more than 3 spatial layers.
427 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700428 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
429 }
philipelcfc319b2015-11-10 07:17:23 -0800430
asapersson86956de2016-01-26 01:05:20 -0800431 int ret_val = Release();
432 if (ret_val < 0) {
433 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000434 }
sprang3958ed82017-08-17 08:12:10 -0700435 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000436 encoder_ = new vpx_codec_ctx_t;
437 }
sprang3958ed82017-08-17 08:12:10 -0700438 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000439 config_ = new vpx_codec_enc_cfg_t;
440 }
441 timestamp_ = 0;
442 if (&codec_ != inst) {
443 codec_ = *inst;
444 }
asaperssona9455ab2015-07-31 06:10:09 -0700445
Sergey Silkinb0bd03b2018-09-28 14:56:39 +0200446 force_key_frame_ = true;
447 pics_since_key_ = 0;
448
hta257dc392016-10-25 09:05:06 -0700449 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200450 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700451 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200452 if (num_temporal_layers_ == 0) {
asaperssona9455ab2015-07-31 06:10:09 -0700453 num_temporal_layers_ = 1;
Sergey Silkin042661b2018-09-10 10:39:35 +0000454 }
Sergey Silkinae9e1882018-09-05 21:07:17 +0200455
Sergey Silkin96f2c972018-09-05 21:07:17 +0200456 framerate_controller_ = std::vector<FramerateController>(
457 num_spatial_layers_, FramerateController(codec_.maxFramerate));
458
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200459 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200460
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000461 // Allocate memory for encoded image
Niels Möller48a79462018-12-07 16:21:18 +0100462 size_t frame_capacity =
nisseeb44b392017-04-28 07:18:05 -0700463 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
Niels Möllerdd1cc982019-02-07 18:52:50 +0100464 encoded_image_.Allocate(frame_capacity);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000465 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000466 // Populate encoder configuration with default values.
467 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
468 return WEBRTC_VIDEO_CODEC_ERROR;
469 }
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700470
471 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
472 unsigned int bits_for_storage = 8;
473 switch (profile_) {
474 case VP9Profile::kProfile0:
475 img_fmt = VPX_IMG_FMT_I420;
476 bits_for_storage = 8;
477 config_->g_bit_depth = VPX_BITS_8;
478 config_->g_profile = 0;
479 config_->g_input_bit_depth = 8;
480 break;
481 case VP9Profile::kProfile2:
482 img_fmt = VPX_IMG_FMT_I42016;
483 bits_for_storage = 16;
484 config_->g_bit_depth = VPX_BITS_10;
485 config_->g_profile = 2;
486 config_->g_input_bit_depth = 10;
487 break;
488 }
489
490 // Creating a wrapper to the image - setting image data to nullptr. Actual
491 // pointer will be set in encode. Setting align to 1, as it is meaningless
492 // (actual memory is not allocated).
493 raw_ =
494 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
495 raw_->bit_depth = bits_for_storage;
496
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000497 config_->g_w = codec_.width;
498 config_->g_h = codec_.height;
499 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200500 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000501 // Setting the time base of the codec.
502 config_->g_timebase.num = 1;
503 config_->g_timebase.den = 90000;
504 config_->g_lag_in_frames = 0; // 0- no frame lagging
505 config_->g_threads = 1;
506 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700507 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000508 config_->rc_end_usage = VPX_CBR;
509 config_->g_pass = VPX_RC_ONE_PASS;
Ilya Nikolaevskiy3a656d12019-02-14 14:44:22 +0100510 config_->rc_min_quantizer =
511 codec_.mode == VideoCodecMode::kScreensharing ? 8 : 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000512 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000513 config_->rc_undershoot_pct = 50;
514 config_->rc_overshoot_pct = 50;
515 config_->rc_buf_initial_sz = 500;
516 config_->rc_buf_optimal_sz = 600;
517 config_->rc_buf_sz = 1000;
518 // Set the maximum target size of any key-frame.
519 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100520 // Key-frame interval is enforced manually by this wrapper.
521 config_->kf_mode = VPX_KF_DISABLED;
522 // TODO(webm:1592): work-around for libvpx issue, as it can still
523 // put some key-frames at will even in VPX_KF_DISABLED kf_mode.
524 config_->kf_max_dist = inst->VP9().keyFrameInterval;
525 config_->kf_min_dist = config_->kf_max_dist;
hta257dc392016-10-25 09:05:06 -0700526 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000527 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800528 config_->g_threads =
529 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700530
Marco6e89b252015-07-07 14:40:38 -0700531 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700532
hta257dc392016-10-25 09:05:06 -0700533 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200534
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100535 inter_layer_pred_ = inst->VP9().interLayerPred;
536
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200537 if (num_spatial_layers_ > 1 &&
538 codec_.mode == VideoCodecMode::kScreensharing && !is_flexible_mode_) {
539 RTC_LOG(LS_ERROR) << "Flexible mode is required for screenshare with "
540 "several spatial layers";
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100541 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
542 }
543
544 // External reference control is required for different frame rate on spatial
545 // layers because libvpx generates rtp incompatible references in this case.
546 external_ref_control_ = field_trial::IsEnabled("WebRTC-Vp9ExternalRefCtrl") ||
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200547 (num_spatial_layers_ > 1 &&
548 codec_.mode == VideoCodecMode::kScreensharing) ||
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100549 inter_layer_pred_ == InterLayerPredMode::kOn;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100550
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200551 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700552 gof_.SetGofInfoVP9(kTemporalStructureMode1);
553 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
554 config_->ts_number_layers = 1;
555 config_->ts_rate_decimator[0] = 1;
556 config_->ts_periodicity = 1;
557 config_->ts_layer_id[0] = 0;
558 } else if (num_temporal_layers_ == 2) {
559 gof_.SetGofInfoVP9(kTemporalStructureMode2);
560 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
561 config_->ts_number_layers = 2;
562 config_->ts_rate_decimator[0] = 2;
563 config_->ts_rate_decimator[1] = 1;
564 config_->ts_periodicity = 2;
565 config_->ts_layer_id[0] = 0;
566 config_->ts_layer_id[1] = 1;
567 } else if (num_temporal_layers_ == 3) {
568 gof_.SetGofInfoVP9(kTemporalStructureMode3);
569 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
570 config_->ts_number_layers = 3;
571 config_->ts_rate_decimator[0] = 4;
572 config_->ts_rate_decimator[1] = 2;
573 config_->ts_rate_decimator[2] = 1;
574 config_->ts_periodicity = 4;
575 config_->ts_layer_id[0] = 0;
576 config_->ts_layer_id[1] = 2;
577 config_->ts_layer_id[2] = 1;
578 config_->ts_layer_id[3] = 2;
579 } else {
580 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
581 }
582
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100583 if (external_ref_control_) {
584 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200585 if (num_temporal_layers_ > 1 && num_spatial_layers_ > 1 &&
586 codec_.mode == VideoCodecMode::kScreensharing) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100587 // External reference control for several temporal layers with different
588 // frame rates on spatial layers is not implemented yet.
589 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
590 }
591 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200592 ref_buf_.clear();
593
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000594 return InitAndSetControlSettings(inst);
595}
596
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000597int VP9EncoderImpl::NumberOfThreads(int width,
598 int height,
599 int number_of_cores) {
600 // Keep the number of encoder threads equal to the possible number of column
601 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
602 if (width * height >= 1280 * 720 && number_of_cores > 4) {
603 return 4;
jianj23173a32017-07-12 16:11:09 -0700604 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000605 return 2;
606 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200607// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800608#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
609 defined(WEBRTC_ANDROID)
610 if (width * height >= 320 * 180 && number_of_cores > 2) {
611 return 2;
612 }
613#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000614 // 1 thread less than VGA.
615 return 1;
616 }
617}
618
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000619int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100620 // Set QP-min/max per spatial and temporal layer.
621 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
622 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800623 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
624 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100625 }
asaperssona9455ab2015-07-31 06:10:09 -0700626 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800627 if (ExplicitlyConfiguredSpatialLayers()) {
628 for (int i = 0; i < num_spatial_layers_; ++i) {
629 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200630 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100631 const int scale_factor = codec_.width / layer.width;
632 RTC_DCHECK_GT(scale_factor, 0);
633
634 // Ensure scaler factor is integer.
635 if (scale_factor * layer.width != codec_.width) {
636 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
637 }
638
639 // Ensure scale factor is the same in both dimensions.
640 if (scale_factor * layer.height != codec_.height) {
641 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
642 }
643
644 // Ensure scale factor is power of two.
645 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
646 if (!is_pow_of_two) {
647 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
648 }
649
650 svc_params_.scaling_factor_num[i] = 1;
651 svc_params_.scaling_factor_den[i] = scale_factor;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200652
653 RTC_DCHECK_GT(codec_.spatialLayers[i].maxFramerate, 0);
654 RTC_DCHECK_LE(codec_.spatialLayers[i].maxFramerate, codec_.maxFramerate);
655 if (i > 0) {
656 // Frame rate of high spatial layer is supposed to be equal or higher
657 // than frame rate of low spatial layer.
658 RTC_DCHECK_GE(codec_.spatialLayers[i].maxFramerate,
659 codec_.spatialLayers[i - 1].maxFramerate);
660 }
sprangce4aef12015-11-02 07:23:20 -0800661 }
662 } else {
663 int scaling_factor_num = 256;
664 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800665 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800666 svc_params_.scaling_factor_num[i] = scaling_factor_num;
667 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800668 }
asaperssona9455ab2015-07-31 06:10:09 -0700669 }
670
Sergey Silkin86684962018-03-28 19:32:37 +0200671 SvcRateAllocator init_allocator(codec_);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100672 current_bitrate_allocation_ = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200673 inst->startBitrate * 1000, inst->maxFramerate);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100674 if (!SetSvcRates(current_bitrate_allocation_)) {
asaperssona9455ab2015-07-31 06:10:09 -0700675 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
676 }
677
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700678 const vpx_codec_err_t rv = vpx_codec_enc_init(
679 encoder_, vpx_codec_vp9_cx(), config_,
680 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
681 if (rv != VPX_CODEC_OK) {
682 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000683 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
684 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000685 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
686 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
687 rc_max_intra_target_);
688 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700689 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700690
jianj822e5932017-07-12 16:09:58 -0700691 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100692 vpx_codec_control(encoder_, VP9E_SET_SVC_GF_TEMPORAL_REF, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200693
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200694 if (is_svc_) {
695 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
696 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700697 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200698
699 if (num_spatial_layers_ > 1) {
700 switch (inter_layer_pred_) {
701 case InterLayerPredMode::kOn:
702 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
703 break;
704 case InterLayerPredMode::kOff:
705 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
706 break;
707 case InterLayerPredMode::kOnKeyPic:
708 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
709 break;
710 default:
711 RTC_NOTREACHED();
712 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200713
Sergey Silkinee203362018-05-30 11:34:08 +0200714 // Configure encoder to drop entire superframe whenever it needs to drop
715 // a layer. This mode is prefered over per-layer dropping which causes
716 // quality flickering and is not compatible with RTP non-flexible mode.
717 vpx_svc_frame_drop_t svc_drop_frame;
718 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100719 svc_drop_frame.framedrop_mode =
720 full_superframe_drop_ ? FULL_SUPERFRAME_DROP : CONSTRAINED_LAYER_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200721 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200722 for (size_t i = 0; i < num_spatial_layers_; ++i) {
723 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200724 }
Sergey Silkinee203362018-05-30 11:34:08 +0200725 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200726 }
727
asaperssona9455ab2015-07-31 06:10:09 -0700728 // Register callback for getting each spatial layer.
729 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800730 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
731 reinterpret_cast<void*>(this)};
732 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
733 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700734
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000735 // Control function to set the number of column tiles in encoding a frame, in
736 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
737 // The number tile columns will be capped by the encoder based on image size
738 // (minimum width of tile column is 256 pixels, maximum is 4096).
739 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700740
741 // Turn on row-based multithreading.
742 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700743
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700744#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200745 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700746 // Do not enable the denoiser on ARM since optimization is pending.
747 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000748 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700749 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000750#endif
jianj6bf57e32017-06-05 13:43:49 -0700751
Niels Möllere3cf3d02018-06-13 11:52:16 +0200752 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700753 // Adjust internal parameters to screen content.
754 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700755 }
Marco2520e722015-09-16 14:05:00 -0700756 // Enable encoder skip of static/low content blocks.
757 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000758 inited_ = true;
759 return WEBRTC_VIDEO_CODEC_OK;
760}
761
762uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
763 // Set max to the optimal buffer level (normalized by target BR),
764 // and scaled by a scale_par.
765 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
766 // This value is presented in percentage of perFrameBw:
767 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
768 // The target in % is as follows:
769 float scale_par = 0.5;
770 uint32_t target_pct =
771 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
772 // Don't go below 3 times the per frame bandwidth.
773 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800774 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000775}
776
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700777int VP9EncoderImpl::Encode(const VideoFrame& input_image,
Niels Möller87e2d782019-03-07 10:18:23 +0100778 const std::vector<VideoFrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000779 if (!inited_) {
780 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
781 }
sprang3958ed82017-08-17 08:12:10 -0700782 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000783 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
784 }
Erik Språngbfa5d5d2019-02-04 16:40:19 +0100785 if (num_active_spatial_layers_ == 0) {
786 // All spatial layers are disabled, return without encoding anything.
787 return WEBRTC_VIDEO_CODEC_OK;
788 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200789
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000790 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200791 if (frame_types && !frame_types->empty()) {
Niels Möller8f7ce222019-03-21 15:43:58 +0100792 if ((*frame_types)[0] == VideoFrameType::kVideoFrameKey) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200793 force_key_frame_ = true;
794 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000795 }
Sergey Silkind902d582018-05-18 17:31:19 +0200796
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100797 if (pics_since_key_ + 1 ==
798 static_cast<size_t>(codec_.VP9()->keyFrameInterval)) {
799 force_key_frame_ = true;
800 }
801
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100802 vpx_svc_layer_id_t layer_id = {0};
803 if (!force_key_frame_) {
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000804 const size_t gof_idx = (pics_since_key_ + 1) % gof_.num_frames_in_gof;
805 layer_id.temporal_layer_id = gof_.temporal_idx[gof_idx];
Sergey Silkin96f2c972018-09-05 21:07:17 +0200806
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100807 if (VideoCodecMode::kScreensharing == codec_.mode) {
808 const uint32_t frame_timestamp_ms =
809 1000 * input_image.timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200810
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100811 // To ensure that several rate-limiters with different limits don't
812 // interfere, they must be queried in order of increasing limit.
813
814 bool use_steady_state_limiter =
815 variable_framerate_experiment_.enabled &&
816 input_image.update_rect().IsEmpty() &&
817 num_steady_state_frames_ >=
818 variable_framerate_experiment_.frames_before_steady_state;
819
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100820 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100821 const float layer_fps =
822 framerate_controller_[layer_id.spatial_layer_id].GetTargetRate();
823 // Use steady state rate-limiter at the correct place.
824 if (use_steady_state_limiter &&
825 layer_fps > variable_framerate_experiment_.framerate_limit - 1e-9) {
826 if (variable_framerate_controller_.DropFrame(frame_timestamp_ms)) {
827 layer_id.spatial_layer_id = num_active_spatial_layers_;
828 }
829 // Break always: if rate limiter triggered frame drop, no need to
830 // continue; otherwise, the rate is less than the next limiters.
831 break;
832 }
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100833 if (framerate_controller_[sl_idx].DropFrame(frame_timestamp_ms)) {
834 ++layer_id.spatial_layer_id;
835 } else {
836 break;
837 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200838 }
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100839
840 if (use_steady_state_limiter &&
841 layer_id.spatial_layer_id < num_active_spatial_layers_) {
842 variable_framerate_controller_.AddFrame(frame_timestamp_ms);
843 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200844 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000845
846 RTC_DCHECK_LE(layer_id.spatial_layer_id, num_active_spatial_layers_);
847 if (layer_id.spatial_layer_id >= num_active_spatial_layers_) {
848 // Drop entire picture.
849 return WEBRTC_VIDEO_CODEC_OK;
850 }
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100851 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000852
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100853 for (int sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
854 layer_id.temporal_layer_id_per_spatial[sl_idx] = layer_id.temporal_layer_id;
855 }
856
857 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
858
Erik Språng7a3fe892019-04-15 12:22:55 +0200859 if (requested_rate_settings_) {
860 if (dynamic_rate_settings_) {
861 // Tweak rate control settings based on available network headroom.
862 UpdateRateSettings(
863 config_,
864 GetRateSettings(
865 requested_rate_settings_->bandwidth_allocation.bps<double>() /
866 requested_rate_settings_->bitrate.get_sum_bps()));
867 }
868
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100869 bool more_layers_requested = MoreLayersEnabled(
Erik Språng7a3fe892019-04-15 12:22:55 +0200870 requested_rate_settings_->bitrate, current_bitrate_allocation_);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100871 bool less_layers_requested = MoreLayersEnabled(
Erik Språng7a3fe892019-04-15 12:22:55 +0200872 current_bitrate_allocation_, requested_rate_settings_->bitrate);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100873 // In SVC can enable new layers only if all lower layers are encoded and at
874 // the base temporal layer.
875 // This will delay rate allocation change until the next frame on the base
876 // spatial layer.
877 // In KSVC or simulcast modes KF will be generated for a new layer, so can
878 // update allocation any time.
879 bool can_upswitch =
880 inter_layer_pred_ != InterLayerPredMode::kOn ||
881 (layer_id.spatial_layer_id == 0 && layer_id.temporal_layer_id == 0);
882 if (!more_layers_requested || can_upswitch) {
Erik Språng7a3fe892019-04-15 12:22:55 +0200883 current_bitrate_allocation_ = requested_rate_settings_->bitrate;
884 requested_rate_settings_ = absl::nullopt;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100885 if (!SetSvcRates(current_bitrate_allocation_)) {
886 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
887 }
888 if (less_layers_requested || more_layers_requested) {
889 ss_info_needed_ = true;
890 }
891 }
892 }
893
894 if (vpx_codec_enc_config_set(encoder_, config_)) {
895 return WEBRTC_VIDEO_CODEC_ERROR;
Sergey Silkind902d582018-05-18 17:31:19 +0200896 }
897
kwiberg352444f2016-11-28 15:58:53 -0800898 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
899 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700900
901 // Set input image for use in the callback.
902 // This was necessary since you need some information from input_image.
903 // You can save only the necessary information (such as timestamp) instead of
904 // doing this.
905 input_image_ = &input_image;
906
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700907 // Keep reference to buffer until encode completes.
908 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
Ilya Nikolaevskiya8507e32019-05-03 11:39:26 +0200909 const I010BufferInterface* i010_buffer;
910 rtc::scoped_refptr<const I010BufferInterface> i010_copy;
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700911 switch (profile_) {
912 case VP9Profile::kProfile0: {
913 i420_buffer = input_image.video_frame_buffer()->ToI420();
914 // Image in vpx_image_t format.
915 // Input image is const. VPX's raw image is not defined as const.
916 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
917 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
918 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
919 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
920 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
921 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
922 break;
923 }
924 case VP9Profile::kProfile2: {
925 // We can inject kI010 frames directly for encode. All other formats
926 // should be converted to it.
927 switch (input_image.video_frame_buffer()->type()) {
928 case VideoFrameBuffer::Type::kI010: {
929 i010_buffer = input_image.video_frame_buffer()->GetI010();
930 break;
931 }
932 default: {
Ilya Nikolaevskiya8507e32019-05-03 11:39:26 +0200933 i010_copy =
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700934 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
Ilya Nikolaevskiya8507e32019-05-03 11:39:26 +0200935 i010_buffer = i010_copy.get();
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700936 }
937 }
938 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
939 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
940 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
941 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
942 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
943 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
944 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
945 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
946 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
947 break;
948 }
949 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000950
philipelcfc319b2015-11-10 07:17:23 -0800951 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200952 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000953 flags = VPX_EFLAG_FORCE_KF;
954 }
philipelcfc319b2015-11-10 07:17:23 -0800955
Sergey Silkin390f3582018-10-01 17:13:50 +0200956 if (external_ref_control_) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100957 vpx_svc_ref_frame_config_t ref_config =
958 SetReferences(force_key_frame_, layer_id.spatial_layer_id);
Sergey Silkina85995a2018-10-02 10:28:10 +0200959
960 if (VideoCodecMode::kScreensharing == codec_.mode) {
961 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
962 ref_config.duration[sl_idx] = static_cast<int64_t>(
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200963 90000 / (std::min(static_cast<float>(codec_.maxFramerate),
964 framerate_controller_[sl_idx].GetTargetRate())));
Sergey Silkina85995a2018-10-02 10:28:10 +0200965 }
966 }
967
Sergey Silkin390f3582018-10-01 17:13:50 +0200968 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &ref_config);
969 }
970
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100971 first_frame_in_picture_ = true;
972
Sergey Silkin96f2c972018-09-05 21:07:17 +0200973 // TODO(ssilkin): Frame duration should be specified per spatial layer
974 // since their frame rate can be different. For now calculate frame duration
975 // based on target frame rate of the highest spatial layer, which frame rate
976 // is supposed to be equal or higher than frame rate of low spatial layers.
977 // Also, timestamp should represent actual time passed since previous frame
978 // (not 'expected' time). Then rate controller can drain buffer more
979 // accurately.
980 RTC_DCHECK_GE(framerate_controller_.size(), num_active_spatial_layers_);
Sergey Silkinf87bb462018-09-17 09:37:37 +0200981 float target_framerate_fps =
982 (codec_.mode == VideoCodecMode::kScreensharing)
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200983 ? std::min(static_cast<float>(codec_.maxFramerate),
984 framerate_controller_[num_active_spatial_layers_ - 1]
985 .GetTargetRate())
Sergey Silkinf87bb462018-09-17 09:37:37 +0200986 : codec_.maxFramerate;
987 uint32_t duration = static_cast<uint32_t>(90000 / target_framerate_fps);
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700988 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
989 duration, flags, VPX_DL_REALTIME);
990 if (rv != VPX_CODEC_OK) {
991 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
992 << "\n"
993 << "Details: " << vpx_codec_error(encoder_) << "\n"
994 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000995 return WEBRTC_VIDEO_CODEC_ERROR;
996 }
997 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700998
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100999 if (!full_superframe_drop_) {
1000 const bool end_of_picture = true;
1001 DeliverBufferedFrame(end_of_picture);
1002 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001003
asaperssona9455ab2015-07-31 06:10:09 -07001004 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001005}
1006
1007void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
Niels Möllerd3b8c632018-08-27 15:33:42 +02001008 absl::optional<int>* spatial_idx,
philipelcce46fc2015-12-21 03:04:49 -08001009 const vpx_codec_cx_pkt& pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001010 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -07001011 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001012 codec_specific->codecType = kVideoCodecVP9;
philipelcce46fc2015-12-21 03:04:49 -08001013 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +02001014
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001015 vp9_info->first_frame_in_picture = first_frame_in_picture_;
Sergey Silkin738b7e92018-08-23 16:37:27 +02001016 vp9_info->flexible_mode = is_flexible_mode_;
asaperssona9455ab2015-07-31 06:10:09 -07001017
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001018 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
1019 pics_since_key_ = 0;
1020 } else if (first_frame_in_picture_) {
1021 ++pics_since_key_;
1022 }
1023
asaperssona9455ab2015-07-31 06:10:09 -07001024 vpx_svc_layer_id_t layer_id = {0};
1025 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1026
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001027 // Can't have keyframe with non-zero temporal layer.
1028 RTC_DCHECK(pics_since_key_ != 0 || layer_id.temporal_layer_id == 0);
1029
sprang3958ed82017-08-17 08:12:10 -07001030 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -05001031 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -07001032 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -07001033 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -07001034 vp9_info->temporal_idx = kNoTemporalIdx;
1035 } else {
1036 vp9_info->temporal_idx = layer_id.temporal_layer_id;
1037 }
“Michael23c5a992018-06-21 11:07:21 -05001038 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -07001039 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
Niels Möllerd3b8c632018-08-27 15:33:42 +02001040 *spatial_idx = absl::nullopt;
asaperssona9455ab2015-07-31 06:10:09 -07001041 } else {
Niels Möllerd3b8c632018-08-27 15:33:42 +02001042 *spatial_idx = layer_id.spatial_layer_id;
asaperssona9455ab2015-07-31 06:10:09 -07001043 }
asaperssona9455ab2015-07-31 06:10:09 -07001044
asaperssona9455ab2015-07-31 06:10:09 -07001045 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -08001046 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -07001047
Sergey Silkin6a8f30e2018-04-26 11:03:49 +02001048 const bool is_key_pic = (pics_since_key_ == 0);
1049 const bool is_inter_layer_pred_allowed =
1050 (inter_layer_pred_ == InterLayerPredMode::kOn ||
1051 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
1052
1053 // Always set inter_layer_predicted to true on high layer frame if inter-layer
1054 // prediction (ILP) is allowed even if encoder didn't actually use it.
1055 // Setting inter_layer_predicted to false would allow receiver to decode high
1056 // layer frame without decoding low layer frame. If that would happen (e.g.
1057 // if low layer frame is lost) then receiver won't be able to decode next high
1058 // layer frame which uses ILP.
1059 vp9_info->inter_layer_predicted =
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001060 first_frame_in_picture_ ? false : is_inter_layer_pred_allowed;
Sergey Silkin6a8f30e2018-04-26 11:03:49 +02001061
Sergey Silkinc5f152d2018-09-26 13:28:50 +02001062 // Mark all low spatial layer frames as references (not just frames of
1063 // active low spatial layers) if inter-layer prediction is enabled since
1064 // these frames are indirect references of high spatial layer, which can
1065 // later be enabled without key frame.
Sergey Silkin6a8f30e2018-04-26 11:03:49 +02001066 vp9_info->non_ref_for_inter_layer_pred =
Sergey Silkinc5f152d2018-09-26 13:28:50 +02001067 !is_inter_layer_pred_allowed ||
1068 layer_id.spatial_layer_id + 1 == num_spatial_layers_;
asapersson00ac85e2015-11-11 05:30:48 -08001069
ivica7f6a6fc2015-09-08 02:40:29 -07001070 // Always populate this, so that the packetizer can properly set the marker
1071 // bit.
“Michael23c5a992018-06-21 11:07:21 -05001072 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -08001073
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001074 vp9_info->num_ref_pics = 0;
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001075 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
1076 vp9_info);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001077 if (vp9_info->flexible_mode) {
1078 vp9_info->gof_idx = kNoGofIdx;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001079 } else {
1080 vp9_info->gof_idx =
1081 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
1082 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001083 RTC_DCHECK(vp9_info->num_ref_pics == gof_.num_ref_pics[vp9_info->gof_idx] ||
1084 vp9_info->num_ref_pics == 0);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001085 }
1086
1087 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
1088
Sergey Silkina323cc02019-04-23 10:09:28 +02001089 // Write SS on key frame of independently coded spatial layers and on base
1090 // temporal/spatial layer frame if number of layers changed without issuing
1091 // of key picture (inter-layer prediction is enabled).
1092 const bool is_key_frame = is_key_pic && !vp9_info->inter_layer_predicted;
1093 if (is_key_frame || (ss_info_needed_ && layer_id.temporal_layer_id == 0 &&
1094 layer_id.spatial_layer_id == 0)) {
1095 vp9_info->ss_data_available = true;
asaperssona9455ab2015-07-31 06:10:09 -07001096 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -05001097 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001098 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -08001099 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +02001100 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -08001101 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -07001102 }
Sergey Silkin738b7e92018-08-23 16:37:27 +02001103 if (vp9_info->flexible_mode) {
1104 vp9_info->gof.num_frames_in_gof = 0;
1105 } else {
asaperssona9455ab2015-07-31 06:10:09 -07001106 vp9_info->gof.CopyGofInfoVP9(gof_);
1107 }
Sergey Silkina323cc02019-04-23 10:09:28 +02001108
1109 ss_info_needed_ = false;
1110 } else {
1111 vp9_info->ss_data_available = false;
asaperssona9455ab2015-07-31 06:10:09 -07001112 }
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001113
1114 first_frame_in_picture_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001115}
1116
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001117void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
1118 const size_t pic_num,
1119 const bool inter_layer_predicted,
1120 CodecSpecificInfoVP9* vp9_info) {
1121 vpx_svc_layer_id_t layer_id = {0};
1122 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1123
Sergey Silkin76be2952018-08-21 12:30:33 +02001124 const bool is_key_frame =
1125 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001126
1127 std::vector<RefFrameBuffer> ref_buf_list;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001128
Sergey Silkin76be2952018-08-21 12:30:33 +02001129 if (is_svc_) {
1130 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1131 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
Sergey Silkin38fabff2019-03-21 10:08:40 +01001132 int ref_buf_flags = 0;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001133
Sergey Silkin76be2952018-08-21 12:30:33 +02001134 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
1135 const size_t fb_idx =
1136 enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
1137 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001138 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1139 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1140 ref_buf_list.push_back(ref_buf_.at(fb_idx));
Sergey Silkin38fabff2019-03-21 10:08:40 +01001141 ref_buf_flags |= 1 << fb_idx;
Sergey Silkin82276592018-08-27 14:54:20 +02001142 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001143 }
1144
1145 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
1146 const size_t fb_idx =
1147 enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
1148 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001149 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1150 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1151 ref_buf_list.push_back(ref_buf_.at(fb_idx));
Sergey Silkin38fabff2019-03-21 10:08:40 +01001152 ref_buf_flags |= 1 << fb_idx;
Sergey Silkin82276592018-08-27 14:54:20 +02001153 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001154 }
1155
1156 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
1157 const size_t fb_idx =
1158 enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
1159 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001160 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1161 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1162 ref_buf_list.push_back(ref_buf_.at(fb_idx));
Sergey Silkin38fabff2019-03-21 10:08:40 +01001163 ref_buf_flags |= 1 << fb_idx;
Sergey Silkin82276592018-08-27 14:54:20 +02001164 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001165 }
Sergey Silkin38fabff2019-03-21 10:08:40 +01001166
1167 RTC_LOG(LS_VERBOSE) << "Frame " << pic_num << " sl "
1168 << layer_id.spatial_layer_id << " tl "
1169 << layer_id.temporal_layer_id << " refered buffers "
1170 << (ref_buf_flags & (1 << 0) ? 1 : 0)
1171 << (ref_buf_flags & (1 << 1) ? 1 : 0)
1172 << (ref_buf_flags & (1 << 2) ? 1 : 0)
1173 << (ref_buf_flags & (1 << 3) ? 1 : 0)
1174 << (ref_buf_flags & (1 << 4) ? 1 : 0)
1175 << (ref_buf_flags & (1 << 5) ? 1 : 0)
1176 << (ref_buf_flags & (1 << 6) ? 1 : 0)
1177 << (ref_buf_flags & (1 << 7) ? 1 : 0);
1178
Sergey Silkin76be2952018-08-21 12:30:33 +02001179 } else if (!is_key_frame) {
1180 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1181 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1182 // In non-SVC mode encoder doesn't provide reference list. Assume each frame
1183 // refers previous one, which is stored in buffer 0.
1184 ref_buf_list.push_back(ref_buf_.at(0));
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001185 }
1186
1187 size_t max_ref_temporal_layer_id = 0;
1188
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001189 std::vector<size_t> ref_pid_list;
1190
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001191 vp9_info->num_ref_pics = 0;
1192 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
1193 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
1194 if (ref_buf.pic_num < pic_num) {
1195 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
1196 // RTP spec limits temporal prediction to the same spatial layer.
1197 // It is safe to ignore this requirement if inter-layer prediction is
1198 // enabled for all frames when all base frames are relayed to receiver.
1199 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +02001200 } else {
1201 RTC_DCHECK_LE(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001202 }
1203 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
1204
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001205 // Encoder may reference several spatial layers on the same previous
1206 // frame in case if some spatial layers are skipped on the current frame.
1207 // We shouldn't put duplicate references as it may break some old
1208 // clients and isn't RTP compatible.
1209 if (std::find(ref_pid_list.begin(), ref_pid_list.end(),
1210 ref_buf.pic_num) != ref_pid_list.end()) {
1211 continue;
1212 }
1213 ref_pid_list.push_back(ref_buf.pic_num);
1214
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001215 const size_t p_diff = pic_num - ref_buf.pic_num;
1216 RTC_DCHECK_LE(p_diff, 127UL);
1217
1218 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
1219 ++vp9_info->num_ref_pics;
1220
1221 max_ref_temporal_layer_id =
1222 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
1223 } else {
1224 RTC_DCHECK(inter_layer_predicted);
1225 // RTP spec only allows to use previous spatial layer for inter-layer
1226 // prediction.
1227 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
1228 }
1229 }
1230
1231 vp9_info->temporal_up_switch =
1232 (max_ref_temporal_layer_id <
1233 static_cast<size_t>(layer_id.temporal_layer_id));
1234}
1235
1236void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
1237 const size_t pic_num) {
1238 vpx_svc_layer_id_t layer_id = {0};
1239 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1240
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001241 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
1242 layer_id.temporal_layer_id);
1243
Sergey Silkin38fabff2019-03-21 10:08:40 +01001244 if (is_svc_) {
Sergey Silkin76be2952018-08-21 12:30:33 +02001245 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1246 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
Sergey Silkin38fabff2019-03-21 10:08:40 +01001247 const int update_buffer_slot =
1248 enc_layer_conf.update_buffer_slot[layer_id.spatial_layer_id];
Sergey Silkin76be2952018-08-21 12:30:33 +02001249
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001250 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
Sergey Silkin38fabff2019-03-21 10:08:40 +01001251 if (update_buffer_slot & (1 << i)) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001252 ref_buf_[i] = frame_buf;
1253 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001254 }
Sergey Silkin38fabff2019-03-21 10:08:40 +01001255
1256 RTC_LOG(LS_VERBOSE) << "Frame " << pic_num << " sl "
1257 << layer_id.spatial_layer_id << " tl "
1258 << layer_id.temporal_layer_id << " updated buffers "
1259 << (update_buffer_slot & (1 << 0) ? 1 : 0)
1260 << (update_buffer_slot & (1 << 1) ? 1 : 0)
1261 << (update_buffer_slot & (1 << 2) ? 1 : 0)
1262 << (update_buffer_slot & (1 << 3) ? 1 : 0)
1263 << (update_buffer_slot & (1 << 4) ? 1 : 0)
1264 << (update_buffer_slot & (1 << 5) ? 1 : 0)
1265 << (update_buffer_slot & (1 << 6) ? 1 : 0)
1266 << (update_buffer_slot & (1 << 7) ? 1 : 0);
Sergey Silkin76be2952018-08-21 12:30:33 +02001267 } else {
1268 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1269 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1270 // In non-svc mode encoder doesn't provide reference list. Assume each frame
1271 // is reference and stored in buffer 0.
1272 ref_buf_[0] = frame_buf;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001273 }
1274}
1275
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001276vpx_svc_ref_frame_config_t VP9EncoderImpl::SetReferences(
1277 bool is_key_pic,
1278 size_t first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001279 // kRefBufIdx, kUpdBufIdx need to be updated to support longer GOFs.
1280 RTC_DCHECK_LE(gof_.num_frames_in_gof, 4);
1281
1282 vpx_svc_ref_frame_config_t ref_config;
1283 memset(&ref_config, 0, sizeof(ref_config));
1284
1285 const size_t num_temporal_refs = std::max(1, num_temporal_layers_ - 1);
1286 const bool is_inter_layer_pred_allowed =
1287 inter_layer_pred_ == InterLayerPredMode::kOn ||
1288 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic);
1289 absl::optional<int> last_updated_buf_idx;
1290
1291 // Put temporal reference to LAST and spatial reference to GOLDEN. Update
1292 // frame buffer (i.e. store encoded frame) if current frame is a temporal
1293 // reference (i.e. it belongs to a low temporal layer) or it is a spatial
1294 // reference. In later case, always store spatial reference in the last
1295 // reference frame buffer.
1296 // For the case of 3 temporal and 3 spatial layers we need 6 frame buffers
1297 // for temporal references plus 1 buffer for spatial reference. 7 buffers
1298 // in total.
1299
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001300 for (size_t sl_idx = first_active_spatial_layer_id;
1301 sl_idx < num_active_spatial_layers_; ++sl_idx) {
1302 const size_t curr_pic_num = is_key_pic ? 0 : pics_since_key_ + 1;
1303 const size_t gof_idx = curr_pic_num % gof_.num_frames_in_gof;
Sergey Silkin390f3582018-10-01 17:13:50 +02001304
1305 if (!is_key_pic) {
1306 // Set up temporal reference.
1307 const int buf_idx = sl_idx * num_temporal_refs + kRefBufIdx[gof_idx];
1308
1309 // Last reference frame buffer is reserved for spatial reference. It is
1310 // not supposed to be used for temporal prediction.
1311 RTC_DCHECK_LT(buf_idx, kNumVp9Buffers - 1);
1312
1313 // Sanity check that reference picture number is smaller than current
1314 // picture number.
Sergey Silkin390f3582018-10-01 17:13:50 +02001315 RTC_DCHECK_LT(ref_buf_[buf_idx].pic_num, curr_pic_num);
1316 const size_t pid_diff = curr_pic_num - ref_buf_[buf_idx].pic_num;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001317 // Incorrect spatial layer may be in the buffer due to a key-frame.
1318 const bool same_spatial_layer =
1319 ref_buf_[buf_idx].spatial_layer_id == sl_idx;
1320 bool correct_pid = false;
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +02001321 if (is_flexible_mode_) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001322 correct_pid = pid_diff < kMaxAllowedPidDIff;
1323 } else {
1324 // Below code assumes single temporal referecence.
1325 RTC_DCHECK_EQ(gof_.num_ref_pics[gof_idx], 1);
1326 correct_pid = pid_diff == gof_.pid_diff[gof_idx][0];
1327 }
Sergey Silkin390f3582018-10-01 17:13:50 +02001328
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001329 if (same_spatial_layer && correct_pid) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001330 ref_config.lst_fb_idx[sl_idx] = buf_idx;
1331 ref_config.reference_last[sl_idx] = 1;
1332 } else {
1333 // This reference doesn't match with one specified by GOF. This can
1334 // only happen if spatial layer is enabled dynamically without key
1335 // frame. Spatial prediction is supposed to be enabled in this case.
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001336 RTC_DCHECK(is_inter_layer_pred_allowed &&
1337 sl_idx > first_active_spatial_layer_id);
Sergey Silkin390f3582018-10-01 17:13:50 +02001338 }
1339 }
1340
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001341 if (is_inter_layer_pred_allowed && sl_idx > first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001342 // Set up spatial reference.
1343 RTC_DCHECK(last_updated_buf_idx);
1344 ref_config.gld_fb_idx[sl_idx] = *last_updated_buf_idx;
1345 ref_config.reference_golden[sl_idx] = 1;
1346 } else {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001347 RTC_DCHECK(ref_config.reference_last[sl_idx] != 0 ||
1348 sl_idx == first_active_spatial_layer_id ||
Sergey Silkin390f3582018-10-01 17:13:50 +02001349 inter_layer_pred_ == InterLayerPredMode::kOff);
1350 }
1351
1352 last_updated_buf_idx.reset();
1353
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001354 if (gof_.temporal_idx[gof_idx] < num_temporal_layers_ - 1 ||
1355 num_temporal_layers_ == 1) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001356 last_updated_buf_idx = sl_idx * num_temporal_refs + kUpdBufIdx[gof_idx];
1357
1358 // Ensure last frame buffer is not used for temporal prediction (it is
1359 // reserved for spatial reference).
1360 RTC_DCHECK_LT(*last_updated_buf_idx, kNumVp9Buffers - 1);
1361 } else if (is_inter_layer_pred_allowed) {
1362 last_updated_buf_idx = kNumVp9Buffers - 1;
1363 }
1364
1365 if (last_updated_buf_idx) {
1366 ref_config.update_buffer_slot[sl_idx] = 1 << *last_updated_buf_idx;
1367 }
1368 }
1369
1370 return ref_config;
1371}
1372
asaperssona9455ab2015-07-31 06:10:09 -07001373int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -08001374 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -07001375
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001376 if (pkt->data.frame.sz == 0) {
1377 // Ignore dropped frame.
1378 return WEBRTC_VIDEO_CODEC_OK;
1379 }
1380
Sergey Silkin07f80cc2018-04-09 13:11:59 +02001381 vpx_svc_layer_id_t layer_id = {0};
1382 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1383
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001384 if (!full_superframe_drop_) {
1385 // Deliver buffered low spatial layer frame.
1386 const bool end_of_picture = false;
1387 DeliverBufferedFrame(end_of_picture);
1388 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001389
Niels Möller48a79462018-12-07 16:21:18 +01001390 if (pkt->data.frame.sz > encoded_image_.capacity()) {
Niels Möllerdd1cc982019-02-07 18:52:50 +01001391 encoded_image_.Allocate(pkt->data.frame.sz);
asaperssond9f641e2016-01-21 01:11:35 -08001392 }
Niels Möller24871e42019-01-17 11:31:13 +01001393 memcpy(encoded_image_.data(), pkt->data.frame.buf, pkt->data.frame.sz);
Niels Möller77536a22019-01-15 08:50:01 +01001394 encoded_image_.set_size(pkt->data.frame.sz);
asaperssond9f641e2016-01-21 01:11:35 -08001395
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001396 const bool is_key_frame =
1397 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1398 // Ensure encoder issued key frame on request.
1399 RTC_DCHECK(is_key_frame || !force_key_frame_);
1400
asaperssona9455ab2015-07-31 06:10:09 -07001401 // Check if encoded frame is a key frame.
Niels Möller8f7ce222019-03-21 15:43:58 +01001402 encoded_image_._frameType = VideoFrameType::kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001403 if (is_key_frame) {
Niels Möller8f7ce222019-03-21 15:43:58 +01001404 encoded_image_._frameType = VideoFrameType::kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001405 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001406 }
Niels Möller77536a22019-01-15 08:50:01 +01001407 RTC_DCHECK_LE(encoded_image_.size(), encoded_image_.capacity());
asapersson86956de2016-01-26 01:05:20 -08001408
philipeld1d03592019-03-01 13:53:55 +01001409 codec_specific_ = {};
Niels Möllerd3b8c632018-08-27 15:33:42 +02001410 absl::optional<int> spatial_index;
1411 PopulateCodecSpecific(&codec_specific_, &spatial_index, *pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001412 input_image_->timestamp());
Niels Möllerd3b8c632018-08-27 15:33:42 +02001413 encoded_image_.SetSpatialIndex(spatial_index);
asaperssona9455ab2015-07-31 06:10:09 -07001414
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001415 UpdateReferenceBuffers(*pkt, pics_since_key_);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001416
Niels Möller77536a22019-01-15 08:50:01 +01001417 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_.size());
Niels Möller23775882018-08-16 10:24:12 +02001418 encoded_image_.SetTimestamp(input_image_->timestamp());
Artem Titarenko84ae2b62019-04-24 12:56:36 +00001419 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
1420 encoded_image_.rotation_ = input_image_->rotation();
1421 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
1422 ? VideoContentType::SCREENSHARE
1423 : VideoContentType::UNSPECIFIED;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001424 encoded_image_._encodedHeight =
1425 pkt->data.frame.height[layer_id.spatial_layer_id];
1426 encoded_image_._encodedWidth =
1427 pkt->data.frame.width[layer_id.spatial_layer_id];
Artem Titarenko84ae2b62019-04-24 12:56:36 +00001428 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001429 int qp = -1;
1430 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
1431 encoded_image_.qp_ = qp;
Artem Titarenko84ae2b62019-04-24 12:56:36 +00001432 encoded_image_.SetColorSpace(input_image_->color_space());
ilnik04f4d122017-06-19 07:18:55 -07001433
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001434 if (full_superframe_drop_) {
1435 const bool end_of_picture = encoded_image_.SpatialIndex().value_or(0) + 1 ==
1436 num_active_spatial_layers_;
1437 DeliverBufferedFrame(end_of_picture);
1438 }
1439
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001440 return WEBRTC_VIDEO_CODEC_OK;
1441}
1442
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001443void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Niels Möller77536a22019-01-15 08:50:01 +01001444 if (encoded_image_.size() > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001445 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001446
1447 // No data partitioning in VP9, so 1 partition only.
1448 int part_idx = 0;
1449 RTPFragmentationHeader frag_info;
1450 frag_info.VerifyAndAllocateFragmentationHeader(1);
1451 frag_info.fragmentationOffset[part_idx] = 0;
Niels Möller77536a22019-01-15 08:50:01 +01001452 frag_info.fragmentationLength[part_idx] = encoded_image_.size();
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001453
1454 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
1455 &frag_info);
Sergey Silkind902d582018-05-18 17:31:19 +02001456
Sergey Silkin96f2c972018-09-05 21:07:17 +02001457 if (codec_.mode == VideoCodecMode::kScreensharing) {
1458 const uint8_t spatial_idx = encoded_image_.SpatialIndex().value_or(0);
1459 const uint32_t frame_timestamp_ms =
Niels Möller23775882018-08-16 10:24:12 +02001460 1000 * encoded_image_.Timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +02001461 framerate_controller_[spatial_idx].AddFrame(frame_timestamp_ms);
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001462
1463 const size_t steady_state_size = SteadyStateSize(
1464 spatial_idx, codec_specific_.codecSpecific.VP9.temporal_idx);
1465
1466 // Only frames on spatial layers, which may be limited in a steady state
1467 // are considered for steady state detection.
1468 if (framerate_controller_[spatial_idx].GetTargetRate() >
1469 variable_framerate_experiment_.framerate_limit + 1e-9) {
1470 if (encoded_image_.qp_ <=
1471 variable_framerate_experiment_.steady_state_qp &&
1472 encoded_image_.size() <= steady_state_size) {
1473 ++num_steady_state_frames_;
1474 } else {
1475 num_steady_state_frames_ = 0;
1476 }
1477 }
Sergey Silkind902d582018-05-18 17:31:19 +02001478 }
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001479 encoded_image_.set_size(0);
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001480 }
1481}
1482
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001483int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1484 EncodedImageCallback* callback) {
1485 encoded_complete_callback_ = callback;
1486 return WEBRTC_VIDEO_CODEC_OK;
1487}
1488
Erik Språng727d1642018-11-07 16:54:15 +01001489VideoEncoder::EncoderInfo VP9EncoderImpl::GetEncoderInfo() const {
1490 EncoderInfo info;
1491 info.supports_native_handle = false;
1492 info.implementation_name = "libvpx";
1493 info.scaling_settings = VideoEncoder::ScalingSettings::kOff;
Erik Språngd3438aa2018-11-08 16:56:43 +01001494 info.has_trusted_rate_controller = trusted_rate_controller_;
Mirta Dvornicic897a9912018-11-30 13:12:21 +01001495 info.is_hardware_accelerated = false;
1496 info.has_internal_source = false;
Erik Språngdbdd8392019-01-17 15:27:50 +01001497 for (size_t si = 0; si < num_spatial_layers_; ++si) {
1498 info.fps_allocation[si].clear();
1499 if (!codec_.spatialLayers[si].active) {
1500 continue;
1501 }
1502 // This spatial layer may already use a fraction of the total frame rate.
1503 const float sl_fps_fraction =
1504 codec_.spatialLayers[si].maxFramerate / codec_.maxFramerate;
1505 for (size_t ti = 0; ti < num_temporal_layers_; ++ti) {
1506 const uint32_t decimator =
1507 num_temporal_layers_ <= 1 ? 1 : config_->ts_rate_decimator[ti];
1508 RTC_DCHECK_GT(decimator, 0);
1509 info.fps_allocation[si].push_back(rtc::saturated_cast<uint8_t>(
1510 EncoderInfo::kMaxFramerateFraction * (sl_fps_fraction / decimator)));
1511 }
1512 }
Erik Språng727d1642018-11-07 16:54:15 +01001513 return info;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001514}
1515
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001516size_t VP9EncoderImpl::SteadyStateSize(int sid, int tid) {
1517 const size_t bitrate_bps = current_bitrate_allocation_.GetBitrate(
1518 sid, tid == kNoTemporalIdx ? 0 : tid);
1519 const float fps = (codec_.mode == VideoCodecMode::kScreensharing)
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +02001520 ? std::min(static_cast<float>(codec_.maxFramerate),
1521 framerate_controller_[sid].GetTargetRate())
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001522 : codec_.maxFramerate;
1523 return static_cast<size_t>(
1524 bitrate_bps / (8 * fps) *
1525 (100 -
1526 variable_framerate_experiment_.steady_state_undershoot_percentage) /
1527 100 +
1528 0.5);
1529}
1530
1531// static
1532VP9EncoderImpl::VariableFramerateExperiment
1533VP9EncoderImpl::ParseVariableFramerateConfig(std::string group_name) {
1534 FieldTrialFlag enabled = FieldTrialFlag("Enabled");
1535 FieldTrialParameter<double> framerate_limit("min_fps", 5.0);
1536 FieldTrialParameter<int> qp("min_qp", 32);
1537 FieldTrialParameter<int> undershoot_percentage("undershoot", 30);
1538 FieldTrialParameter<int> frames_before_steady_state(
1539 "frames_before_steady_state", 5);
1540 ParseFieldTrial({&enabled, &framerate_limit, &qp, &undershoot_percentage,
1541 &frames_before_steady_state},
1542 field_trial::FindFullName(group_name));
1543 VariableFramerateExperiment config;
1544 config.enabled = enabled.Get();
1545 config.framerate_limit = framerate_limit.Get();
1546 config.steady_state_qp = qp.Get();
1547 config.steady_state_undershoot_percentage = undershoot_percentage.Get();
1548 config.frames_before_steady_state = frames_before_steady_state.Get();
1549
1550 return config;
1551}
1552
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001553VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001554 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001555 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001556 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001557 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001558
1559VP9DecoderImpl::~VP9DecoderImpl() {
1560 inited_ = true; // in order to do the actual release
1561 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001562 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1563 if (num_buffers_in_use > 0) {
1564 // The frame buffers are reference counted and frames are exposed after
1565 // decoding. There may be valid usage cases where previous frames are still
1566 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001567 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1568 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001569 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001570}
1571
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001572int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001573 int ret_val = Release();
1574 if (ret_val < 0) {
1575 return ret_val;
1576 }
Sergey Silkinb674cd12018-10-09 10:59:06 +02001577
sprang3958ed82017-08-17 08:12:10 -07001578 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001579 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001580 }
philipelcce46fc2015-12-21 03:04:49 -08001581 vpx_codec_dec_cfg_t cfg;
Sergey Silkinb674cd12018-10-09 10:59:06 +02001582 memset(&cfg, 0, sizeof(cfg));
1583
1584 // We want to use multithreading when decoding high resolution videos. But,
1585 // since we don't know resolution of input stream at this stage, we always
1586 // enable it.
1587 cfg.threads = std::min(number_of_cores, kMaxNumTiles4kVideo);
1588
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001589 vpx_codec_flags_t flags = 0;
1590 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1591 return WEBRTC_VIDEO_CODEC_MEMORY;
1592 }
Henrik Boström9695d852015-05-06 10:42:15 +02001593
1594 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1595 return WEBRTC_VIDEO_CODEC_MEMORY;
1596 }
1597
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001598 inited_ = true;
1599 // Always start with a complete key frame.
1600 key_frame_required_ = true;
1601 return WEBRTC_VIDEO_CODEC_OK;
1602}
1603
1604int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1605 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001606 int64_t /*render_time_ms*/) {
1607 if (!inited_) {
1608 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1609 }
sprang3958ed82017-08-17 08:12:10 -07001610 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001611 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1612 }
1613 // Always start with a complete key frame.
1614 if (key_frame_required_) {
Niels Möller8f7ce222019-03-21 15:43:58 +01001615 if (input_image._frameType != VideoFrameType::kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001616 return WEBRTC_VIDEO_CODEC_ERROR;
1617 // We have a key frame - is it complete?
1618 if (input_image._completeFrame) {
1619 key_frame_required_ = false;
1620 } else {
1621 return WEBRTC_VIDEO_CODEC_ERROR;
1622 }
1623 }
sprang3958ed82017-08-17 08:12:10 -07001624 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001625 vpx_image_t* img;
Niels Möller24871e42019-01-17 11:31:13 +01001626 const uint8_t* buffer = input_image.data();
Niels Möller77536a22019-01-15 08:50:01 +01001627 if (input_image.size() == 0) {
sprang3958ed82017-08-17 08:12:10 -07001628 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001629 }
Henrik Boström9695d852015-05-06 10:42:15 +02001630 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1631 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001632 if (vpx_codec_decode(decoder_, buffer,
Niels Möller77536a22019-01-15 08:50:01 +01001633 static_cast<unsigned int>(input_image.size()), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001634 VPX_DL_REALTIME)) {
1635 return WEBRTC_VIDEO_CODEC_ERROR;
1636 }
Henrik Boström9695d852015-05-06 10:42:15 +02001637 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1638 // It may be released by libvpx during future vpx_codec_decode or
1639 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001640 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001641 int qp;
1642 vpx_codec_err_t vpx_ret =
1643 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1644 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
Artem Titarenko84ae2b62019-04-24 12:56:36 +00001645 int ret = ReturnFrame(img, input_image.Timestamp(), input_image.ntp_time_ms_,
1646 qp, input_image.ColorSpace());
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001647 if (ret != 0) {
1648 return ret;
1649 }
1650 return WEBRTC_VIDEO_CODEC_OK;
1651}
1652
Artem Titarenko84ae2b62019-04-24 12:56:36 +00001653int VP9DecoderImpl::ReturnFrame(
1654 const vpx_image_t* img,
1655 uint32_t timestamp,
1656 int64_t ntp_time_ms,
1657 int qp,
1658 const webrtc::ColorSpace* explicit_color_space) {
sprang3958ed82017-08-17 08:12:10 -07001659 if (img == nullptr) {
1660 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001661 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1662 }
Henrik Boström9695d852015-05-06 10:42:15 +02001663
1664 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001665 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001666 // vpx_codec_decode calls or vpx_codec_destroy).
1667 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1668 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001669
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001670 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001671 // using a Wrapped*Buffer.
1672 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1673 switch (img->bit_depth) {
1674 case 8:
1675 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001676 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1677 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1678 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1679 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001680 // WrappedI420Buffer's mechanism for allowing the release of its frame
1681 // buffer is through a callback function. This is where we should
1682 // release |img_buffer|.
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001683 rtc::KeepRefUntilDone(img_buffer));
1684 break;
1685 case 10:
1686 img_wrapped_buffer = WrapI010Buffer(
1687 img->d_w, img->d_h,
1688 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1689 img->stride[VPX_PLANE_Y] / 2,
1690 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1691 img->stride[VPX_PLANE_U] / 2,
1692 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1693 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1694 break;
1695 default:
1696 RTC_NOTREACHED();
1697 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1698 }
nisseca6d5d12016-06-17 05:03:04 -07001699
Johannes Kron4749e4e2018-11-21 10:18:18 +01001700 auto builder = VideoFrame::Builder()
1701 .set_video_frame_buffer(img_wrapped_buffer)
Artem Titarenko84ae2b62019-04-24 12:56:36 +00001702 .set_timestamp_ms(0)
Johannes Kron4749e4e2018-11-21 10:18:18 +01001703 .set_timestamp_rtp(timestamp)
Artem Titarenko84ae2b62019-04-24 12:56:36 +00001704 .set_ntp_time_ms(ntp_time_ms)
1705 .set_rotation(webrtc::kVideoRotation_0);
1706 if (explicit_color_space) {
1707 builder.set_color_space(*explicit_color_space);
1708 } else {
1709 builder.set_color_space(
1710 ExtractVP9ColorSpace(img->cs, img->range, img->bit_depth));
1711 }
Johannes Kron4749e4e2018-11-21 10:18:18 +01001712
1713 VideoFrame decoded_image = builder.build();
1714
Danil Chapovalov0040b662018-06-18 10:48:16 +02001715 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001716 return WEBRTC_VIDEO_CODEC_OK;
1717}
1718
1719int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1720 DecodedImageCallback* callback) {
1721 decode_complete_callback_ = callback;
1722 return WEBRTC_VIDEO_CODEC_OK;
1723}
1724
1725int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001726 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1727
sprang3958ed82017-08-17 08:12:10 -07001728 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001729 if (inited_) {
1730 // When a codec is destroyed libvpx will release any buffers of
1731 // |frame_buffer_pool_| it is currently using.
1732 if (vpx_codec_destroy(decoder_)) {
1733 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1734 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001735 }
1736 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001737 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001738 }
Henrik Boström9695d852015-05-06 10:42:15 +02001739 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1740 // still referenced externally are deleted once fully released, not returning
1741 // to the pool.
1742 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001743 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001744 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001745}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001746
1747const char* VP9DecoderImpl::ImplementationName() const {
1748 return "libvpx";
1749}
1750
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001751} // namespace webrtc
Mirko Bonadei95adedb2018-11-19 09:52:37 +01001752
1753#endif // RTC_ENABLE_VP9