blob: a342b39d22ab4774cd3fc1dd983c03f598265d11 [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
Marco6e89b252015-07-07 14:40:38 -070053// Only positive speeds, range for real-time coding currently is: 5 - 8.
54// Lower means slower/better quality, higher means fastest/lower quality.
55int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070056#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080057 return 8;
58#else
Marco6e89b252015-07-07 14:40:38 -070059 // For smaller resolutions, use lower speed setting (get some coding gain at
60 // the cost of increased encoding complexity).
61 if (width * height <= 352 * 288)
62 return 5;
63 else
64 return 7;
Marco002f0d02015-12-17 09:49:31 -080065#endif
Marco6e89b252015-07-07 14:40:38 -070066}
Emircan Uysaler715cc232018-07-23 17:50:43 -070067// Helper class for extracting VP9 colorspace.
68ColorSpace ExtractVP9ColorSpace(vpx_color_space_t space_t,
69 vpx_color_range_t range_t,
70 unsigned int bit_depth) {
Johannes Kronb47ccc32018-12-07 11:12:44 +010071 ColorSpace::PrimaryID primaries = ColorSpace::PrimaryID::kUnspecified;
72 ColorSpace::TransferID transfer = ColorSpace::TransferID::kUnspecified;
73 ColorSpace::MatrixID matrix = ColorSpace::MatrixID::kUnspecified;
Emircan Uysaler715cc232018-07-23 17:50:43 -070074 switch (space_t) {
75 case VPX_CS_BT_601:
76 case VPX_CS_SMPTE_170:
77 primaries = ColorSpace::PrimaryID::kSMPTE170M;
78 transfer = ColorSpace::TransferID::kSMPTE170M;
79 matrix = ColorSpace::MatrixID::kSMPTE170M;
80 break;
81 case VPX_CS_SMPTE_240:
82 primaries = ColorSpace::PrimaryID::kSMPTE240M;
83 transfer = ColorSpace::TransferID::kSMPTE240M;
84 matrix = ColorSpace::MatrixID::kSMPTE240M;
85 break;
86 case VPX_CS_BT_709:
87 primaries = ColorSpace::PrimaryID::kBT709;
88 transfer = ColorSpace::TransferID::kBT709;
89 matrix = ColorSpace::MatrixID::kBT709;
90 break;
91 case VPX_CS_BT_2020:
92 primaries = ColorSpace::PrimaryID::kBT2020;
93 switch (bit_depth) {
94 case 8:
95 transfer = ColorSpace::TransferID::kBT709;
96 break;
97 case 10:
98 transfer = ColorSpace::TransferID::kBT2020_10;
99 break;
100 default:
101 RTC_NOTREACHED();
102 break;
103 }
104 matrix = ColorSpace::MatrixID::kBT2020_NCL;
105 break;
106 case VPX_CS_SRGB:
107 primaries = ColorSpace::PrimaryID::kBT709;
108 transfer = ColorSpace::TransferID::kIEC61966_2_1;
109 matrix = ColorSpace::MatrixID::kBT709;
110 break;
111 default:
112 break;
113 }
114
115 ColorSpace::RangeID range = ColorSpace::RangeID::kInvalid;
116 switch (range_t) {
117 case VPX_CR_STUDIO_RANGE:
118 range = ColorSpace::RangeID::kLimited;
119 break;
120 case VPX_CR_FULL_RANGE:
121 range = ColorSpace::RangeID::kFull;
122 break;
123 default:
124 break;
125 }
126 return ColorSpace(primaries, transfer, matrix, range);
127}
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100128
129bool MoreLayersEnabled(const VideoBitrateAllocation& first,
130 const VideoBitrateAllocation& second) {
131 for (size_t sl_idx = 0; sl_idx < kMaxSpatialLayers; ++sl_idx) {
132 if (first.GetSpatialLayerSum(sl_idx) > 0 &&
133 second.GetSpatialLayerSum(sl_idx) == 0) {
134 return true;
135 }
136 }
137 return false;
138}
139
Emircan Uysaler715cc232018-07-23 17:50:43 -0700140} // namespace
Marco6e89b252015-07-07 14:40:38 -0700141
asaperssona9455ab2015-07-31 06:10:09 -0700142void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
143 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -0800144 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -0700145 enc->GetEncodedLayerFrame(pkt);
146}
147
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700148VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000149 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -0700150 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700151 profile_(
152 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000153 inited_(false),
154 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000155 cpu_speed_(3),
156 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -0700157 encoder_(nullptr),
158 config_(nullptr),
159 raw_(nullptr),
160 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200161 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200162 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -0700163 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -0800164 num_spatial_layers_(0),
Sergey Silkin390f3582018-10-01 17:13:50 +0200165 num_active_spatial_layers_(0),
Erik Språngd3438aa2018-11-08 16:56:43 +0100166 layer_deactivation_requires_key_frame_(
167 field_trial::IsEnabled("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation")),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200168 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200169 inter_layer_pred_(InterLayerPredMode::kOn),
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100170 external_ref_control_(false), // Set in InitEncode because of tests.
Erik Språng4b4266f2019-01-23 12:48:13 +0100171 trusted_rate_controller_(RateControlSettings::ParseFromFieldTrials()
172 .LibvpxVp9TrustedRateController()),
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100173 full_superframe_drop_(true),
174 first_frame_in_picture_(true),
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100175 ss_info_needed_(false),
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100176 is_flexible_mode_(false),
177 variable_framerate_experiment_(ParseVariableFramerateConfig(
178 "WebRTC-VP9VariableFramerateScreenshare")),
179 variable_framerate_controller_(
180 variable_framerate_experiment_.framerate_limit),
181 num_steady_state_frames_(0) {
philipeld1d03592019-03-01 13:53:55 +0100182 codec_ = {};
johannkoenig8225c402017-01-26 13:23:44 -0800183 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000184}
185
186VP9EncoderImpl::~VP9EncoderImpl() {
187 Release();
188}
189
190int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100191 int ret_val = WEBRTC_VIDEO_CODEC_OK;
192
Niels Möllerdd1cc982019-02-07 18:52:50 +0100193 encoded_image_.Allocate(0);
sprang3958ed82017-08-17 08:12:10 -0700194 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100195 if (inited_) {
196 if (vpx_codec_destroy(encoder_)) {
197 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
198 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000199 }
200 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700201 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000202 }
sprang3958ed82017-08-17 08:12:10 -0700203 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000204 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700205 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000206 }
sprang3958ed82017-08-17 08:12:10 -0700207 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000208 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700209 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000210 }
211 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100212 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000213}
214
sprangce4aef12015-11-02 07:23:20 -0800215bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
216 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
217 // (i.e. bitrates) were explicitly configured.
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200218 return codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800219}
220
Erik Språng566124a2018-04-23 12:32:22 +0200221bool VP9EncoderImpl::SetSvcRates(
222 const VideoBitrateAllocation& bitrate_allocation) {
Sergey Silkin86684962018-03-28 19:32:37 +0200223 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200224
sprangce4aef12015-11-02 07:23:20 -0800225 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200226 const bool layer_activation_requires_key_frame =
227 inter_layer_pred_ == InterLayerPredMode::kOff ||
228 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic;
229
Sergey Silkin86684962018-03-28 19:32:37 +0200230 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200231 const bool was_layer_active = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200232 config_->ss_target_bitrate[sl_idx] =
233 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
234
235 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
236 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
237 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
238 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200239
Sergey Silkine7ce8882018-10-03 18:04:57 +0200240 const bool is_active_layer = (config_->ss_target_bitrate[sl_idx] > 0);
241 if (!was_layer_active && is_active_layer &&
242 layer_activation_requires_key_frame) {
243 force_key_frame_ = true;
244 } else if (was_layer_active && !is_active_layer &&
245 layer_deactivation_requires_key_frame_) {
246 force_key_frame_ = true;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200247 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200248
Sergey Silkine7ce8882018-10-03 18:04:57 +0200249 if (!was_layer_active) {
Sergey Silkin96f2c972018-09-05 21:07:17 +0200250 // Reset frame rate controller if layer is resumed after pause.
251 framerate_controller_[sl_idx].Reset();
252 }
253
254 framerate_controller_[sl_idx].SetTargetRate(
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200255 std::min(static_cast<float>(codec_.maxFramerate),
256 codec_.spatialLayers[sl_idx].maxFramerate));
sprangce4aef12015-11-02 07:23:20 -0800257 }
258 } else {
259 float rate_ratio[VPX_MAX_LAYERS] = {0};
260 float total = 0;
Sergey Silkin908689d2018-08-20 09:28:45 +0200261 for (int i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800262 if (svc_params_.scaling_factor_num[i] <= 0 ||
263 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100264 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800265 return false;
266 }
Yves Gerey665174f2018-06-19 15:03:05 +0200267 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
268 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800269 total += rate_ratio[i];
270 }
271
Sergey Silkin908689d2018-08-20 09:28:45 +0200272 for (int i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200273 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800274 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
275 config_->rc_target_bitrate * rate_ratio[i] / total);
276 if (num_temporal_layers_ == 1) {
277 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
278 } else if (num_temporal_layers_ == 2) {
279 config_->layer_target_bitrate[i * num_temporal_layers_] =
280 config_->ss_target_bitrate[i] * 2 / 3;
281 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
282 config_->ss_target_bitrate[i];
283 } else if (num_temporal_layers_ == 3) {
284 config_->layer_target_bitrate[i * num_temporal_layers_] =
285 config_->ss_target_bitrate[i] / 2;
286 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
287 config_->layer_target_bitrate[i * num_temporal_layers_] +
288 (config_->ss_target_bitrate[i] / 4);
289 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
290 config_->ss_target_bitrate[i];
291 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100292 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
293 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800294 return false;
295 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200296
297 framerate_controller_[i].SetTargetRate(codec_.maxFramerate);
asaperssona9455ab2015-07-31 06:10:09 -0700298 }
299 }
Sergey Silkin908689d2018-08-20 09:28:45 +0200300
301 num_active_spatial_layers_ = 0;
302 for (int i = 0; i < num_spatial_layers_; ++i) {
303 if (config_->ss_target_bitrate[i] > 0) {
304 ++num_active_spatial_layers_;
305 }
306 }
307 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
308
asaperssona9455ab2015-07-31 06:10:09 -0700309 return true;
310}
311
Erik Språng08127a92016-11-16 16:41:30 +0100312int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200313 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100314 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000315 if (!inited_) {
316 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
317 }
318 if (encoder_->err) {
319 return WEBRTC_VIDEO_CODEC_ERROR;
320 }
Erik Språng08127a92016-11-16 16:41:30 +0100321 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000322 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
323 }
324 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100325 if (codec_.maxBitrate > 0 &&
326 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
327 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000328 }
Erik Språng08127a92016-11-16 16:41:30 +0100329
Erik Språng08127a92016-11-16 16:41:30 +0100330 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700331
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100332 requested_bitrate_allocation_ = bitrate_allocation;
asaperssona9455ab2015-07-31 06:10:09 -0700333
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000334 return WEBRTC_VIDEO_CODEC_OK;
335}
336
337int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
338 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000339 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700340 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000341 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
342 }
343 if (inst->maxFramerate < 1) {
344 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
345 }
346 // Allow zero to represent an unspecified maxBitRate
347 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
348 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
349 }
350 if (inst->width < 1 || inst->height < 1) {
351 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
352 }
353 if (number_of_cores < 1) {
354 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
355 }
hta257dc392016-10-25 09:05:06 -0700356 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700357 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
358 }
ilnik2a8c2f52017-02-15 02:23:28 -0800359 // libvpx probably does not support more than 3 spatial layers.
360 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700361 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
362 }
philipelcfc319b2015-11-10 07:17:23 -0800363
asapersson86956de2016-01-26 01:05:20 -0800364 int ret_val = Release();
365 if (ret_val < 0) {
366 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000367 }
sprang3958ed82017-08-17 08:12:10 -0700368 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000369 encoder_ = new vpx_codec_ctx_t;
370 }
sprang3958ed82017-08-17 08:12:10 -0700371 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000372 config_ = new vpx_codec_enc_cfg_t;
373 }
374 timestamp_ = 0;
375 if (&codec_ != inst) {
376 codec_ = *inst;
377 }
asaperssona9455ab2015-07-31 06:10:09 -0700378
Sergey Silkinb0bd03b2018-09-28 14:56:39 +0200379 force_key_frame_ = true;
380 pics_since_key_ = 0;
381
hta257dc392016-10-25 09:05:06 -0700382 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200383 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700384 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200385 if (num_temporal_layers_ == 0) {
asaperssona9455ab2015-07-31 06:10:09 -0700386 num_temporal_layers_ = 1;
Sergey Silkin042661b2018-09-10 10:39:35 +0000387 }
Sergey Silkinae9e1882018-09-05 21:07:17 +0200388
Sergey Silkin96f2c972018-09-05 21:07:17 +0200389 framerate_controller_ = std::vector<FramerateController>(
390 num_spatial_layers_, FramerateController(codec_.maxFramerate));
391
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200392 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200393
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000394 // Allocate memory for encoded image
Niels Möller48a79462018-12-07 16:21:18 +0100395 size_t frame_capacity =
nisseeb44b392017-04-28 07:18:05 -0700396 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
Niels Möllerdd1cc982019-02-07 18:52:50 +0100397 encoded_image_.Allocate(frame_capacity);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000398 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000399 // Populate encoder configuration with default values.
400 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
401 return WEBRTC_VIDEO_CODEC_ERROR;
402 }
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700403
404 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
405 unsigned int bits_for_storage = 8;
406 switch (profile_) {
407 case VP9Profile::kProfile0:
408 img_fmt = VPX_IMG_FMT_I420;
409 bits_for_storage = 8;
410 config_->g_bit_depth = VPX_BITS_8;
411 config_->g_profile = 0;
412 config_->g_input_bit_depth = 8;
413 break;
414 case VP9Profile::kProfile2:
415 img_fmt = VPX_IMG_FMT_I42016;
416 bits_for_storage = 16;
417 config_->g_bit_depth = VPX_BITS_10;
418 config_->g_profile = 2;
419 config_->g_input_bit_depth = 10;
420 break;
421 }
422
423 // Creating a wrapper to the image - setting image data to nullptr. Actual
424 // pointer will be set in encode. Setting align to 1, as it is meaningless
425 // (actual memory is not allocated).
426 raw_ =
427 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
428 raw_->bit_depth = bits_for_storage;
429
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000430 config_->g_w = codec_.width;
431 config_->g_h = codec_.height;
432 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200433 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000434 // Setting the time base of the codec.
435 config_->g_timebase.num = 1;
436 config_->g_timebase.den = 90000;
437 config_->g_lag_in_frames = 0; // 0- no frame lagging
438 config_->g_threads = 1;
439 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700440 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000441 config_->rc_end_usage = VPX_CBR;
442 config_->g_pass = VPX_RC_ONE_PASS;
Ilya Nikolaevskiy3a656d12019-02-14 14:44:22 +0100443 config_->rc_min_quantizer =
444 codec_.mode == VideoCodecMode::kScreensharing ? 8 : 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000445 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000446 config_->rc_undershoot_pct = 50;
447 config_->rc_overshoot_pct = 50;
448 config_->rc_buf_initial_sz = 500;
449 config_->rc_buf_optimal_sz = 600;
450 config_->rc_buf_sz = 1000;
451 // Set the maximum target size of any key-frame.
452 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100453 // Key-frame interval is enforced manually by this wrapper.
454 config_->kf_mode = VPX_KF_DISABLED;
455 // TODO(webm:1592): work-around for libvpx issue, as it can still
456 // put some key-frames at will even in VPX_KF_DISABLED kf_mode.
457 config_->kf_max_dist = inst->VP9().keyFrameInterval;
458 config_->kf_min_dist = config_->kf_max_dist;
hta257dc392016-10-25 09:05:06 -0700459 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000460 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800461 config_->g_threads =
462 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700463
Marco6e89b252015-07-07 14:40:38 -0700464 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700465
hta257dc392016-10-25 09:05:06 -0700466 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200467
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100468 inter_layer_pred_ = inst->VP9().interLayerPred;
469
470 different_framerates_used_ = false;
471 for (size_t sl_idx = 1; sl_idx < num_spatial_layers_; ++sl_idx) {
472 if (std::abs(codec_.spatialLayers[sl_idx].maxFramerate -
473 codec_.spatialLayers[0].maxFramerate) > 1e-9) {
474 different_framerates_used_ = true;
475 }
476 }
477
478 if (different_framerates_used_ && !is_flexible_mode_) {
479 RTC_LOG(LS_ERROR) << "Flexible mode required for different framerates on "
480 "different spatial layers";
481 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
482 }
483
484 // External reference control is required for different frame rate on spatial
485 // layers because libvpx generates rtp incompatible references in this case.
486 external_ref_control_ = field_trial::IsEnabled("WebRTC-Vp9ExternalRefCtrl") ||
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100487 different_framerates_used_ ||
488 inter_layer_pred_ == InterLayerPredMode::kOn;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100489
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200490 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700491 gof_.SetGofInfoVP9(kTemporalStructureMode1);
492 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
493 config_->ts_number_layers = 1;
494 config_->ts_rate_decimator[0] = 1;
495 config_->ts_periodicity = 1;
496 config_->ts_layer_id[0] = 0;
497 } else if (num_temporal_layers_ == 2) {
498 gof_.SetGofInfoVP9(kTemporalStructureMode2);
499 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
500 config_->ts_number_layers = 2;
501 config_->ts_rate_decimator[0] = 2;
502 config_->ts_rate_decimator[1] = 1;
503 config_->ts_periodicity = 2;
504 config_->ts_layer_id[0] = 0;
505 config_->ts_layer_id[1] = 1;
506 } else if (num_temporal_layers_ == 3) {
507 gof_.SetGofInfoVP9(kTemporalStructureMode3);
508 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
509 config_->ts_number_layers = 3;
510 config_->ts_rate_decimator[0] = 4;
511 config_->ts_rate_decimator[1] = 2;
512 config_->ts_rate_decimator[2] = 1;
513 config_->ts_periodicity = 4;
514 config_->ts_layer_id[0] = 0;
515 config_->ts_layer_id[1] = 2;
516 config_->ts_layer_id[2] = 1;
517 config_->ts_layer_id[3] = 2;
518 } else {
519 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
520 }
521
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100522 if (external_ref_control_) {
523 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
524 if (num_temporal_layers_ > 1 && different_framerates_used_) {
525 // External reference control for several temporal layers with different
526 // frame rates on spatial layers is not implemented yet.
527 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
528 }
529 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200530 ref_buf_.clear();
531
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000532 return InitAndSetControlSettings(inst);
533}
534
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000535int VP9EncoderImpl::NumberOfThreads(int width,
536 int height,
537 int number_of_cores) {
538 // Keep the number of encoder threads equal to the possible number of column
539 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
540 if (width * height >= 1280 * 720 && number_of_cores > 4) {
541 return 4;
jianj23173a32017-07-12 16:11:09 -0700542 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000543 return 2;
544 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200545// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800546#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
547 defined(WEBRTC_ANDROID)
548 if (width * height >= 320 * 180 && number_of_cores > 2) {
549 return 2;
550 }
551#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000552 // 1 thread less than VGA.
553 return 1;
554 }
555}
556
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000557int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100558 // Set QP-min/max per spatial and temporal layer.
559 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
560 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800561 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
562 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100563 }
asaperssona9455ab2015-07-31 06:10:09 -0700564 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800565 if (ExplicitlyConfiguredSpatialLayers()) {
566 for (int i = 0; i < num_spatial_layers_; ++i) {
567 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200568 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100569 const int scale_factor = codec_.width / layer.width;
570 RTC_DCHECK_GT(scale_factor, 0);
571
572 // Ensure scaler factor is integer.
573 if (scale_factor * layer.width != codec_.width) {
574 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
575 }
576
577 // Ensure scale factor is the same in both dimensions.
578 if (scale_factor * layer.height != codec_.height) {
579 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
580 }
581
582 // Ensure scale factor is power of two.
583 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
584 if (!is_pow_of_two) {
585 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
586 }
587
588 svc_params_.scaling_factor_num[i] = 1;
589 svc_params_.scaling_factor_den[i] = scale_factor;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200590
591 RTC_DCHECK_GT(codec_.spatialLayers[i].maxFramerate, 0);
592 RTC_DCHECK_LE(codec_.spatialLayers[i].maxFramerate, codec_.maxFramerate);
593 if (i > 0) {
594 // Frame rate of high spatial layer is supposed to be equal or higher
595 // than frame rate of low spatial layer.
596 RTC_DCHECK_GE(codec_.spatialLayers[i].maxFramerate,
597 codec_.spatialLayers[i - 1].maxFramerate);
598 }
sprangce4aef12015-11-02 07:23:20 -0800599 }
600 } else {
601 int scaling_factor_num = 256;
602 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800603 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800604 svc_params_.scaling_factor_num[i] = scaling_factor_num;
605 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800606 }
asaperssona9455ab2015-07-31 06:10:09 -0700607 }
608
Sergey Silkin86684962018-03-28 19:32:37 +0200609 SvcRateAllocator init_allocator(codec_);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100610 current_bitrate_allocation_ = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200611 inst->startBitrate * 1000, inst->maxFramerate);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100612 if (!SetSvcRates(current_bitrate_allocation_)) {
asaperssona9455ab2015-07-31 06:10:09 -0700613 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
614 }
615
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700616 const vpx_codec_err_t rv = vpx_codec_enc_init(
617 encoder_, vpx_codec_vp9_cx(), config_,
618 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
619 if (rv != VPX_CODEC_OK) {
620 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000621 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
622 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000623 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
624 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
625 rc_max_intra_target_);
626 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700627 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700628
jianj822e5932017-07-12 16:09:58 -0700629 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100630 vpx_codec_control(encoder_, VP9E_SET_SVC_GF_TEMPORAL_REF, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200631
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200632 if (is_svc_) {
633 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
634 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700635 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200636
637 if (num_spatial_layers_ > 1) {
638 switch (inter_layer_pred_) {
639 case InterLayerPredMode::kOn:
640 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
641 break;
642 case InterLayerPredMode::kOff:
643 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
644 break;
645 case InterLayerPredMode::kOnKeyPic:
646 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
647 break;
648 default:
649 RTC_NOTREACHED();
650 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200651
Sergey Silkinee203362018-05-30 11:34:08 +0200652 // Configure encoder to drop entire superframe whenever it needs to drop
653 // a layer. This mode is prefered over per-layer dropping which causes
654 // quality flickering and is not compatible with RTP non-flexible mode.
655 vpx_svc_frame_drop_t svc_drop_frame;
656 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100657 svc_drop_frame.framedrop_mode =
658 full_superframe_drop_ ? FULL_SUPERFRAME_DROP : CONSTRAINED_LAYER_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200659 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200660 for (size_t i = 0; i < num_spatial_layers_; ++i) {
661 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200662 }
Sergey Silkinee203362018-05-30 11:34:08 +0200663 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200664 }
665
asaperssona9455ab2015-07-31 06:10:09 -0700666 // Register callback for getting each spatial layer.
667 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800668 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
669 reinterpret_cast<void*>(this)};
670 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
671 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700672
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000673 // Control function to set the number of column tiles in encoding a frame, in
674 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
675 // The number tile columns will be capped by the encoder based on image size
676 // (minimum width of tile column is 256 pixels, maximum is 4096).
677 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700678
679 // Turn on row-based multithreading.
680 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700681
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700682#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200683 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700684 // Do not enable the denoiser on ARM since optimization is pending.
685 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000686 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700687 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000688#endif
jianj6bf57e32017-06-05 13:43:49 -0700689
Niels Möllere3cf3d02018-06-13 11:52:16 +0200690 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700691 // Adjust internal parameters to screen content.
692 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700693 }
Marco2520e722015-09-16 14:05:00 -0700694 // Enable encoder skip of static/low content blocks.
695 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000696 inited_ = true;
697 return WEBRTC_VIDEO_CODEC_OK;
698}
699
700uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
701 // Set max to the optimal buffer level (normalized by target BR),
702 // and scaled by a scale_par.
703 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
704 // This value is presented in percentage of perFrameBw:
705 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
706 // The target in % is as follows:
707 float scale_par = 0.5;
708 uint32_t target_pct =
709 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
710 // Don't go below 3 times the per frame bandwidth.
711 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800712 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000713}
714
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700715int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000716 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700717 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000718 if (!inited_) {
719 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
720 }
sprang3958ed82017-08-17 08:12:10 -0700721 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000722 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
723 }
Erik Språngbfa5d5d2019-02-04 16:40:19 +0100724 if (num_active_spatial_layers_ == 0) {
725 // All spatial layers are disabled, return without encoding anything.
726 return WEBRTC_VIDEO_CODEC_OK;
727 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200728
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000729 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200730 if (frame_types && !frame_types->empty()) {
731 if ((*frame_types)[0] == kVideoFrameKey) {
732 force_key_frame_ = true;
733 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000734 }
Sergey Silkind902d582018-05-18 17:31:19 +0200735
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100736 if (pics_since_key_ + 1 ==
737 static_cast<size_t>(codec_.VP9()->keyFrameInterval)) {
738 force_key_frame_ = true;
739 }
740
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100741 vpx_svc_layer_id_t layer_id = {0};
742 if (!force_key_frame_) {
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000743 const size_t gof_idx = (pics_since_key_ + 1) % gof_.num_frames_in_gof;
744 layer_id.temporal_layer_id = gof_.temporal_idx[gof_idx];
Sergey Silkin96f2c972018-09-05 21:07:17 +0200745
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100746 if (VideoCodecMode::kScreensharing == codec_.mode) {
747 const uint32_t frame_timestamp_ms =
748 1000 * input_image.timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200749
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100750 // To ensure that several rate-limiters with different limits don't
751 // interfere, they must be queried in order of increasing limit.
752
753 bool use_steady_state_limiter =
754 variable_framerate_experiment_.enabled &&
755 input_image.update_rect().IsEmpty() &&
756 num_steady_state_frames_ >=
757 variable_framerate_experiment_.frames_before_steady_state;
758
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100759 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100760 const float layer_fps =
761 framerate_controller_[layer_id.spatial_layer_id].GetTargetRate();
762 // Use steady state rate-limiter at the correct place.
763 if (use_steady_state_limiter &&
764 layer_fps > variable_framerate_experiment_.framerate_limit - 1e-9) {
765 if (variable_framerate_controller_.DropFrame(frame_timestamp_ms)) {
766 layer_id.spatial_layer_id = num_active_spatial_layers_;
767 }
768 // Break always: if rate limiter triggered frame drop, no need to
769 // continue; otherwise, the rate is less than the next limiters.
770 break;
771 }
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100772 if (framerate_controller_[sl_idx].DropFrame(frame_timestamp_ms)) {
773 ++layer_id.spatial_layer_id;
774 } else {
775 break;
776 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200777 }
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100778
779 if (use_steady_state_limiter &&
780 layer_id.spatial_layer_id < num_active_spatial_layers_) {
781 variable_framerate_controller_.AddFrame(frame_timestamp_ms);
782 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200783 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000784
785 RTC_DCHECK_LE(layer_id.spatial_layer_id, num_active_spatial_layers_);
786 if (layer_id.spatial_layer_id >= num_active_spatial_layers_) {
787 // Drop entire picture.
788 return WEBRTC_VIDEO_CODEC_OK;
789 }
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100790 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000791
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100792 for (int sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
793 layer_id.temporal_layer_id_per_spatial[sl_idx] = layer_id.temporal_layer_id;
794 }
795
796 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
797
798 if (requested_bitrate_allocation_) {
799 bool more_layers_requested = MoreLayersEnabled(
800 *requested_bitrate_allocation_, current_bitrate_allocation_);
801 bool less_layers_requested = MoreLayersEnabled(
802 current_bitrate_allocation_, *requested_bitrate_allocation_);
803 // In SVC can enable new layers only if all lower layers are encoded and at
804 // the base temporal layer.
805 // This will delay rate allocation change until the next frame on the base
806 // spatial layer.
807 // In KSVC or simulcast modes KF will be generated for a new layer, so can
808 // update allocation any time.
809 bool can_upswitch =
810 inter_layer_pred_ != InterLayerPredMode::kOn ||
811 (layer_id.spatial_layer_id == 0 && layer_id.temporal_layer_id == 0);
812 if (!more_layers_requested || can_upswitch) {
813 current_bitrate_allocation_ = *requested_bitrate_allocation_;
814 requested_bitrate_allocation_ = absl::nullopt;
815 if (!SetSvcRates(current_bitrate_allocation_)) {
816 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
817 }
818 if (less_layers_requested || more_layers_requested) {
819 ss_info_needed_ = true;
820 }
821 }
822 }
823
824 if (vpx_codec_enc_config_set(encoder_, config_)) {
825 return WEBRTC_VIDEO_CODEC_ERROR;
Sergey Silkind902d582018-05-18 17:31:19 +0200826 }
827
kwiberg352444f2016-11-28 15:58:53 -0800828 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
829 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700830
831 // Set input image for use in the callback.
832 // This was necessary since you need some information from input_image.
833 // You can save only the necessary information (such as timestamp) instead of
834 // doing this.
835 input_image_ = &input_image;
836
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700837 // Keep reference to buffer until encode completes.
838 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
839 rtc::scoped_refptr<I010BufferInterface> i010_buffer;
840 switch (profile_) {
841 case VP9Profile::kProfile0: {
842 i420_buffer = input_image.video_frame_buffer()->ToI420();
843 // Image in vpx_image_t format.
844 // Input image is const. VPX's raw image is not defined as const.
845 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
846 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
847 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
848 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
849 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
850 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
851 break;
852 }
853 case VP9Profile::kProfile2: {
854 // We can inject kI010 frames directly for encode. All other formats
855 // should be converted to it.
856 switch (input_image.video_frame_buffer()->type()) {
857 case VideoFrameBuffer::Type::kI010: {
858 i010_buffer = input_image.video_frame_buffer()->GetI010();
859 break;
860 }
861 default: {
862 i010_buffer =
863 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
864 }
865 }
866 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
867 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
868 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
869 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
870 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
871 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
872 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
873 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
874 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
875 break;
876 }
877 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000878
philipelcfc319b2015-11-10 07:17:23 -0800879 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200880 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000881 flags = VPX_EFLAG_FORCE_KF;
882 }
philipelcfc319b2015-11-10 07:17:23 -0800883
Sergey Silkin390f3582018-10-01 17:13:50 +0200884 if (external_ref_control_) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100885 vpx_svc_ref_frame_config_t ref_config =
886 SetReferences(force_key_frame_, layer_id.spatial_layer_id);
Sergey Silkina85995a2018-10-02 10:28:10 +0200887
888 if (VideoCodecMode::kScreensharing == codec_.mode) {
889 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
890 ref_config.duration[sl_idx] = static_cast<int64_t>(
891 90000 / framerate_controller_[sl_idx].GetTargetRate());
892 }
893 }
894
Sergey Silkin390f3582018-10-01 17:13:50 +0200895 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &ref_config);
896 }
897
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100898 first_frame_in_picture_ = true;
899
Sergey Silkin96f2c972018-09-05 21:07:17 +0200900 // TODO(ssilkin): Frame duration should be specified per spatial layer
901 // since their frame rate can be different. For now calculate frame duration
902 // based on target frame rate of the highest spatial layer, which frame rate
903 // is supposed to be equal or higher than frame rate of low spatial layers.
904 // Also, timestamp should represent actual time passed since previous frame
905 // (not 'expected' time). Then rate controller can drain buffer more
906 // accurately.
907 RTC_DCHECK_GE(framerate_controller_.size(), num_active_spatial_layers_);
Sergey Silkinf87bb462018-09-17 09:37:37 +0200908 float target_framerate_fps =
909 (codec_.mode == VideoCodecMode::kScreensharing)
910 ? framerate_controller_[num_active_spatial_layers_ - 1]
911 .GetTargetRate()
912 : codec_.maxFramerate;
913 uint32_t duration = static_cast<uint32_t>(90000 / target_framerate_fps);
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700914 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
915 duration, flags, VPX_DL_REALTIME);
916 if (rv != VPX_CODEC_OK) {
917 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
918 << "\n"
919 << "Details: " << vpx_codec_error(encoder_) << "\n"
920 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000921 return WEBRTC_VIDEO_CODEC_ERROR;
922 }
923 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700924
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100925 if (!full_superframe_drop_) {
926 const bool end_of_picture = true;
927 DeliverBufferedFrame(end_of_picture);
928 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200929
asaperssona9455ab2015-07-31 06:10:09 -0700930 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000931}
932
933void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
Niels Möllerd3b8c632018-08-27 15:33:42 +0200934 absl::optional<int>* spatial_idx,
philipelcce46fc2015-12-21 03:04:49 -0800935 const vpx_codec_cx_pkt& pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100936 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -0700937 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000938 codec_specific->codecType = kVideoCodecVP9;
philipelcce46fc2015-12-21 03:04:49 -0800939 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200940
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100941 vp9_info->first_frame_in_picture = first_frame_in_picture_;
Sergey Silkin738b7e92018-08-23 16:37:27 +0200942 vp9_info->flexible_mode = is_flexible_mode_;
hta257dc392016-10-25 09:05:06 -0700943 vp9_info->ss_data_available =
Sergey Silkin738b7e92018-08-23 16:37:27 +0200944 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
asaperssona9455ab2015-07-31 06:10:09 -0700945
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100946 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
947 pics_since_key_ = 0;
948 } else if (first_frame_in_picture_) {
949 ++pics_since_key_;
950 }
951
asaperssona9455ab2015-07-31 06:10:09 -0700952 vpx_svc_layer_id_t layer_id = {0};
953 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
954
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100955 // Can't have keyframe with non-zero temporal layer.
956 RTC_DCHECK(pics_since_key_ != 0 || layer_id.temporal_layer_id == 0);
957
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100958 if (ss_info_needed_ && layer_id.temporal_layer_id == 0 &&
959 layer_id.spatial_layer_id == 0) {
960 // Force SS info after the layers configuration has changed.
961 vp9_info->ss_data_available = true;
962 ss_info_needed_ = false;
963 }
964
sprang3958ed82017-08-17 08:12:10 -0700965 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -0500966 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700967 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700968 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700969 vp9_info->temporal_idx = kNoTemporalIdx;
970 } else {
971 vp9_info->temporal_idx = layer_id.temporal_layer_id;
972 }
“Michael23c5a992018-06-21 11:07:21 -0500973 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700974 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
Niels Möllerd3b8c632018-08-27 15:33:42 +0200975 *spatial_idx = absl::nullopt;
asaperssona9455ab2015-07-31 06:10:09 -0700976 } else {
Niels Möllerd3b8c632018-08-27 15:33:42 +0200977 *spatial_idx = layer_id.spatial_layer_id;
asaperssona9455ab2015-07-31 06:10:09 -0700978 }
979 if (layer_id.spatial_layer_id != 0) {
980 vp9_info->ss_data_available = false;
981 }
982
asaperssona9455ab2015-07-31 06:10:09 -0700983 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800984 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700985
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200986 const bool is_key_pic = (pics_since_key_ == 0);
987 const bool is_inter_layer_pred_allowed =
988 (inter_layer_pred_ == InterLayerPredMode::kOn ||
989 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
990
991 // Always set inter_layer_predicted to true on high layer frame if inter-layer
992 // prediction (ILP) is allowed even if encoder didn't actually use it.
993 // Setting inter_layer_predicted to false would allow receiver to decode high
994 // layer frame without decoding low layer frame. If that would happen (e.g.
995 // if low layer frame is lost) then receiver won't be able to decode next high
996 // layer frame which uses ILP.
997 vp9_info->inter_layer_predicted =
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100998 first_frame_in_picture_ ? false : is_inter_layer_pred_allowed;
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200999
Sergey Silkinc5f152d2018-09-26 13:28:50 +02001000 // Mark all low spatial layer frames as references (not just frames of
1001 // active low spatial layers) if inter-layer prediction is enabled since
1002 // these frames are indirect references of high spatial layer, which can
1003 // later be enabled without key frame.
Sergey Silkin6a8f30e2018-04-26 11:03:49 +02001004 vp9_info->non_ref_for_inter_layer_pred =
Sergey Silkinc5f152d2018-09-26 13:28:50 +02001005 !is_inter_layer_pred_allowed ||
1006 layer_id.spatial_layer_id + 1 == num_spatial_layers_;
asapersson00ac85e2015-11-11 05:30:48 -08001007
ivica7f6a6fc2015-09-08 02:40:29 -07001008 // Always populate this, so that the packetizer can properly set the marker
1009 // bit.
“Michael23c5a992018-06-21 11:07:21 -05001010 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -08001011
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001012 vp9_info->num_ref_pics = 0;
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001013 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
1014 vp9_info);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001015 if (vp9_info->flexible_mode) {
1016 vp9_info->gof_idx = kNoGofIdx;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001017 } else {
1018 vp9_info->gof_idx =
1019 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
1020 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001021 RTC_DCHECK(vp9_info->num_ref_pics == gof_.num_ref_pics[vp9_info->gof_idx] ||
1022 vp9_info->num_ref_pics == 0);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001023 }
1024
1025 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
1026
asaperssona9455ab2015-07-31 06:10:09 -07001027 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -07001028 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -05001029 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001030 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -08001031 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +02001032 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -08001033 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -07001034 }
Sergey Silkin738b7e92018-08-23 16:37:27 +02001035 if (vp9_info->flexible_mode) {
1036 vp9_info->gof.num_frames_in_gof = 0;
1037 } else {
asaperssona9455ab2015-07-31 06:10:09 -07001038 vp9_info->gof.CopyGofInfoVP9(gof_);
1039 }
1040 }
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001041
1042 first_frame_in_picture_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001043}
1044
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001045void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
1046 const size_t pic_num,
1047 const bool inter_layer_predicted,
1048 CodecSpecificInfoVP9* vp9_info) {
1049 vpx_svc_layer_id_t layer_id = {0};
1050 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1051
Sergey Silkin76be2952018-08-21 12:30:33 +02001052 const bool is_key_frame =
1053 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001054
1055 std::vector<RefFrameBuffer> ref_buf_list;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001056
Sergey Silkin76be2952018-08-21 12:30:33 +02001057 if (is_svc_) {
1058 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1059 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001060
Sergey Silkin76be2952018-08-21 12:30:33 +02001061 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
1062 const size_t fb_idx =
1063 enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
1064 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001065 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1066 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1067 ref_buf_list.push_back(ref_buf_.at(fb_idx));
1068 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001069 }
1070
1071 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
1072 const size_t fb_idx =
1073 enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
1074 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001075 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1076 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1077 ref_buf_list.push_back(ref_buf_.at(fb_idx));
1078 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001079 }
1080
1081 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
1082 const size_t fb_idx =
1083 enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
1084 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001085 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1086 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1087 ref_buf_list.push_back(ref_buf_.at(fb_idx));
1088 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001089 }
1090 } else if (!is_key_frame) {
1091 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1092 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1093 // In non-SVC mode encoder doesn't provide reference list. Assume each frame
1094 // refers previous one, which is stored in buffer 0.
1095 ref_buf_list.push_back(ref_buf_.at(0));
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001096 }
1097
1098 size_t max_ref_temporal_layer_id = 0;
1099
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001100 std::vector<size_t> ref_pid_list;
1101
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001102 vp9_info->num_ref_pics = 0;
1103 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
1104 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
1105 if (ref_buf.pic_num < pic_num) {
1106 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
1107 // RTP spec limits temporal prediction to the same spatial layer.
1108 // It is safe to ignore this requirement if inter-layer prediction is
1109 // enabled for all frames when all base frames are relayed to receiver.
1110 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
1111 }
1112 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
1113
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001114 // Encoder may reference several spatial layers on the same previous
1115 // frame in case if some spatial layers are skipped on the current frame.
1116 // We shouldn't put duplicate references as it may break some old
1117 // clients and isn't RTP compatible.
1118 if (std::find(ref_pid_list.begin(), ref_pid_list.end(),
1119 ref_buf.pic_num) != ref_pid_list.end()) {
1120 continue;
1121 }
1122 ref_pid_list.push_back(ref_buf.pic_num);
1123
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001124 const size_t p_diff = pic_num - ref_buf.pic_num;
1125 RTC_DCHECK_LE(p_diff, 127UL);
1126
1127 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
1128 ++vp9_info->num_ref_pics;
1129
1130 max_ref_temporal_layer_id =
1131 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
1132 } else {
1133 RTC_DCHECK(inter_layer_predicted);
1134 // RTP spec only allows to use previous spatial layer for inter-layer
1135 // prediction.
1136 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
1137 }
1138 }
1139
1140 vp9_info->temporal_up_switch =
1141 (max_ref_temporal_layer_id <
1142 static_cast<size_t>(layer_id.temporal_layer_id));
1143}
1144
1145void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
1146 const size_t pic_num) {
1147 vpx_svc_layer_id_t layer_id = {0};
1148 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1149
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001150 const bool is_key_frame =
1151 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1152
1153 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
1154 layer_id.temporal_layer_id);
1155
1156 if (is_key_frame && layer_id.spatial_layer_id == 0) {
1157 // Key frame updates all ref buffers.
1158 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
1159 ref_buf_[i] = frame_buf;
1160 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001161 } else if (is_svc_) {
1162 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1163 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
1164
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001165 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
1166 if (enc_layer_conf.update_buffer_slot[layer_id.spatial_layer_id] &
1167 (1 << i)) {
1168 ref_buf_[i] = frame_buf;
1169 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001170 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001171 } else {
1172 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1173 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1174 // In non-svc mode encoder doesn't provide reference list. Assume each frame
1175 // is reference and stored in buffer 0.
1176 ref_buf_[0] = frame_buf;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001177 }
1178}
1179
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001180vpx_svc_ref_frame_config_t VP9EncoderImpl::SetReferences(
1181 bool is_key_pic,
1182 size_t first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001183 // kRefBufIdx, kUpdBufIdx need to be updated to support longer GOFs.
1184 RTC_DCHECK_LE(gof_.num_frames_in_gof, 4);
1185
1186 vpx_svc_ref_frame_config_t ref_config;
1187 memset(&ref_config, 0, sizeof(ref_config));
1188
1189 const size_t num_temporal_refs = std::max(1, num_temporal_layers_ - 1);
1190 const bool is_inter_layer_pred_allowed =
1191 inter_layer_pred_ == InterLayerPredMode::kOn ||
1192 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic);
1193 absl::optional<int> last_updated_buf_idx;
1194
1195 // Put temporal reference to LAST and spatial reference to GOLDEN. Update
1196 // frame buffer (i.e. store encoded frame) if current frame is a temporal
1197 // reference (i.e. it belongs to a low temporal layer) or it is a spatial
1198 // reference. In later case, always store spatial reference in the last
1199 // reference frame buffer.
1200 // For the case of 3 temporal and 3 spatial layers we need 6 frame buffers
1201 // for temporal references plus 1 buffer for spatial reference. 7 buffers
1202 // in total.
1203
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001204 for (size_t sl_idx = first_active_spatial_layer_id;
1205 sl_idx < num_active_spatial_layers_; ++sl_idx) {
1206 const size_t curr_pic_num = is_key_pic ? 0 : pics_since_key_ + 1;
1207 const size_t gof_idx = curr_pic_num % gof_.num_frames_in_gof;
Sergey Silkin390f3582018-10-01 17:13:50 +02001208
1209 if (!is_key_pic) {
1210 // Set up temporal reference.
1211 const int buf_idx = sl_idx * num_temporal_refs + kRefBufIdx[gof_idx];
1212
1213 // Last reference frame buffer is reserved for spatial reference. It is
1214 // not supposed to be used for temporal prediction.
1215 RTC_DCHECK_LT(buf_idx, kNumVp9Buffers - 1);
1216
1217 // Sanity check that reference picture number is smaller than current
1218 // picture number.
Sergey Silkin390f3582018-10-01 17:13:50 +02001219 RTC_DCHECK_LT(ref_buf_[buf_idx].pic_num, curr_pic_num);
1220 const size_t pid_diff = curr_pic_num - ref_buf_[buf_idx].pic_num;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001221 // Incorrect spatial layer may be in the buffer due to a key-frame.
1222 const bool same_spatial_layer =
1223 ref_buf_[buf_idx].spatial_layer_id == sl_idx;
1224 bool correct_pid = false;
1225 if (different_framerates_used_) {
1226 correct_pid = pid_diff < kMaxAllowedPidDIff;
1227 } else {
1228 // Below code assumes single temporal referecence.
1229 RTC_DCHECK_EQ(gof_.num_ref_pics[gof_idx], 1);
1230 correct_pid = pid_diff == gof_.pid_diff[gof_idx][0];
1231 }
Sergey Silkin390f3582018-10-01 17:13:50 +02001232
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001233 if (same_spatial_layer && correct_pid) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001234 ref_config.lst_fb_idx[sl_idx] = buf_idx;
1235 ref_config.reference_last[sl_idx] = 1;
1236 } else {
1237 // This reference doesn't match with one specified by GOF. This can
1238 // only happen if spatial layer is enabled dynamically without key
1239 // frame. Spatial prediction is supposed to be enabled in this case.
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001240 RTC_DCHECK(is_inter_layer_pred_allowed &&
1241 sl_idx > first_active_spatial_layer_id);
Sergey Silkin390f3582018-10-01 17:13:50 +02001242 }
1243 }
1244
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001245 if (is_inter_layer_pred_allowed && sl_idx > first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001246 // Set up spatial reference.
1247 RTC_DCHECK(last_updated_buf_idx);
1248 ref_config.gld_fb_idx[sl_idx] = *last_updated_buf_idx;
1249 ref_config.reference_golden[sl_idx] = 1;
1250 } else {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001251 RTC_DCHECK(ref_config.reference_last[sl_idx] != 0 ||
1252 sl_idx == first_active_spatial_layer_id ||
Sergey Silkin390f3582018-10-01 17:13:50 +02001253 inter_layer_pred_ == InterLayerPredMode::kOff);
1254 }
1255
1256 last_updated_buf_idx.reset();
1257
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001258 if (gof_.temporal_idx[gof_idx] < num_temporal_layers_ - 1 ||
1259 num_temporal_layers_ == 1) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001260 last_updated_buf_idx = sl_idx * num_temporal_refs + kUpdBufIdx[gof_idx];
1261
1262 // Ensure last frame buffer is not used for temporal prediction (it is
1263 // reserved for spatial reference).
1264 RTC_DCHECK_LT(*last_updated_buf_idx, kNumVp9Buffers - 1);
1265 } else if (is_inter_layer_pred_allowed) {
1266 last_updated_buf_idx = kNumVp9Buffers - 1;
1267 }
1268
1269 if (last_updated_buf_idx) {
1270 ref_config.update_buffer_slot[sl_idx] = 1 << *last_updated_buf_idx;
1271 }
1272 }
1273
1274 return ref_config;
1275}
1276
asaperssona9455ab2015-07-31 06:10:09 -07001277int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -08001278 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -07001279
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001280 if (pkt->data.frame.sz == 0) {
1281 // Ignore dropped frame.
1282 return WEBRTC_VIDEO_CODEC_OK;
1283 }
1284
Sergey Silkin07f80cc2018-04-09 13:11:59 +02001285 vpx_svc_layer_id_t layer_id = {0};
1286 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1287
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001288 if (!full_superframe_drop_) {
1289 // Deliver buffered low spatial layer frame.
1290 const bool end_of_picture = false;
1291 DeliverBufferedFrame(end_of_picture);
1292 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001293
Niels Möller48a79462018-12-07 16:21:18 +01001294 if (pkt->data.frame.sz > encoded_image_.capacity()) {
Niels Möllerdd1cc982019-02-07 18:52:50 +01001295 encoded_image_.Allocate(pkt->data.frame.sz);
asaperssond9f641e2016-01-21 01:11:35 -08001296 }
Niels Möller24871e42019-01-17 11:31:13 +01001297 memcpy(encoded_image_.data(), pkt->data.frame.buf, pkt->data.frame.sz);
Niels Möller77536a22019-01-15 08:50:01 +01001298 encoded_image_.set_size(pkt->data.frame.sz);
asaperssond9f641e2016-01-21 01:11:35 -08001299
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001300 const bool is_key_frame =
1301 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1302 // Ensure encoder issued key frame on request.
1303 RTC_DCHECK(is_key_frame || !force_key_frame_);
1304
asaperssona9455ab2015-07-31 06:10:09 -07001305 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -08001306 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001307 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +02001308 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001309 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001310 }
Niels Möller77536a22019-01-15 08:50:01 +01001311 RTC_DCHECK_LE(encoded_image_.size(), encoded_image_.capacity());
asapersson86956de2016-01-26 01:05:20 -08001312
philipeld1d03592019-03-01 13:53:55 +01001313 codec_specific_ = {};
Niels Möllerd3b8c632018-08-27 15:33:42 +02001314 absl::optional<int> spatial_index;
1315 PopulateCodecSpecific(&codec_specific_, &spatial_index, *pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001316 input_image_->timestamp());
Niels Möllerd3b8c632018-08-27 15:33:42 +02001317 encoded_image_.SetSpatialIndex(spatial_index);
asaperssona9455ab2015-07-31 06:10:09 -07001318
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001319 UpdateReferenceBuffers(*pkt, pics_since_key_);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001320
Niels Möller77536a22019-01-15 08:50:01 +01001321 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_.size());
Niels Möller23775882018-08-16 10:24:12 +02001322 encoded_image_.SetTimestamp(input_image_->timestamp());
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001323 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
1324 encoded_image_.rotation_ = input_image_->rotation();
Niels Möllere3cf3d02018-06-13 11:52:16 +02001325 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001326 ? VideoContentType::SCREENSHARE
1327 : VideoContentType::UNSPECIFIED;
1328 encoded_image_._encodedHeight =
1329 pkt->data.frame.height[layer_id.spatial_layer_id];
1330 encoded_image_._encodedWidth =
1331 pkt->data.frame.width[layer_id.spatial_layer_id];
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +02001332 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001333 int qp = -1;
1334 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
1335 encoded_image_.qp_ = qp;
Johannes Kron4749e4e2018-11-21 10:18:18 +01001336 encoded_image_.SetColorSpace(input_image_->color_space());
ilnik04f4d122017-06-19 07:18:55 -07001337
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001338 if (full_superframe_drop_) {
1339 const bool end_of_picture = encoded_image_.SpatialIndex().value_or(0) + 1 ==
1340 num_active_spatial_layers_;
1341 DeliverBufferedFrame(end_of_picture);
1342 }
1343
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001344 return WEBRTC_VIDEO_CODEC_OK;
1345}
1346
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001347void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Niels Möller77536a22019-01-15 08:50:01 +01001348 if (encoded_image_.size() > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001349 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001350
1351 // No data partitioning in VP9, so 1 partition only.
1352 int part_idx = 0;
1353 RTPFragmentationHeader frag_info;
1354 frag_info.VerifyAndAllocateFragmentationHeader(1);
1355 frag_info.fragmentationOffset[part_idx] = 0;
Niels Möller77536a22019-01-15 08:50:01 +01001356 frag_info.fragmentationLength[part_idx] = encoded_image_.size();
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001357 frag_info.fragmentationPlType[part_idx] = 0;
1358 frag_info.fragmentationTimeDiff[part_idx] = 0;
1359
1360 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
1361 &frag_info);
Sergey Silkind902d582018-05-18 17:31:19 +02001362
Sergey Silkin96f2c972018-09-05 21:07:17 +02001363 if (codec_.mode == VideoCodecMode::kScreensharing) {
1364 const uint8_t spatial_idx = encoded_image_.SpatialIndex().value_or(0);
1365 const uint32_t frame_timestamp_ms =
Niels Möller23775882018-08-16 10:24:12 +02001366 1000 * encoded_image_.Timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +02001367 framerate_controller_[spatial_idx].AddFrame(frame_timestamp_ms);
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001368
1369 const size_t steady_state_size = SteadyStateSize(
1370 spatial_idx, codec_specific_.codecSpecific.VP9.temporal_idx);
1371
1372 // Only frames on spatial layers, which may be limited in a steady state
1373 // are considered for steady state detection.
1374 if (framerate_controller_[spatial_idx].GetTargetRate() >
1375 variable_framerate_experiment_.framerate_limit + 1e-9) {
1376 if (encoded_image_.qp_ <=
1377 variable_framerate_experiment_.steady_state_qp &&
1378 encoded_image_.size() <= steady_state_size) {
1379 ++num_steady_state_frames_;
1380 } else {
1381 num_steady_state_frames_ = 0;
1382 }
1383 }
Sergey Silkind902d582018-05-18 17:31:19 +02001384 }
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001385 encoded_image_.set_size(0);
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001386 }
1387}
1388
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001389int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1390 EncodedImageCallback* callback) {
1391 encoded_complete_callback_ = callback;
1392 return WEBRTC_VIDEO_CODEC_OK;
1393}
1394
Erik Språng727d1642018-11-07 16:54:15 +01001395VideoEncoder::EncoderInfo VP9EncoderImpl::GetEncoderInfo() const {
1396 EncoderInfo info;
1397 info.supports_native_handle = false;
1398 info.implementation_name = "libvpx";
1399 info.scaling_settings = VideoEncoder::ScalingSettings::kOff;
Erik Språngd3438aa2018-11-08 16:56:43 +01001400 info.has_trusted_rate_controller = trusted_rate_controller_;
Mirta Dvornicic897a9912018-11-30 13:12:21 +01001401 info.is_hardware_accelerated = false;
1402 info.has_internal_source = false;
Erik Språngdbdd8392019-01-17 15:27:50 +01001403 for (size_t si = 0; si < num_spatial_layers_; ++si) {
1404 info.fps_allocation[si].clear();
1405 if (!codec_.spatialLayers[si].active) {
1406 continue;
1407 }
1408 // This spatial layer may already use a fraction of the total frame rate.
1409 const float sl_fps_fraction =
1410 codec_.spatialLayers[si].maxFramerate / codec_.maxFramerate;
1411 for (size_t ti = 0; ti < num_temporal_layers_; ++ti) {
1412 const uint32_t decimator =
1413 num_temporal_layers_ <= 1 ? 1 : config_->ts_rate_decimator[ti];
1414 RTC_DCHECK_GT(decimator, 0);
1415 info.fps_allocation[si].push_back(rtc::saturated_cast<uint8_t>(
1416 EncoderInfo::kMaxFramerateFraction * (sl_fps_fraction / decimator)));
1417 }
1418 }
Erik Språng727d1642018-11-07 16:54:15 +01001419 return info;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001420}
1421
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001422size_t VP9EncoderImpl::SteadyStateSize(int sid, int tid) {
1423 const size_t bitrate_bps = current_bitrate_allocation_.GetBitrate(
1424 sid, tid == kNoTemporalIdx ? 0 : tid);
1425 const float fps = (codec_.mode == VideoCodecMode::kScreensharing)
1426 ? framerate_controller_[sid].GetTargetRate()
1427 : codec_.maxFramerate;
1428 return static_cast<size_t>(
1429 bitrate_bps / (8 * fps) *
1430 (100 -
1431 variable_framerate_experiment_.steady_state_undershoot_percentage) /
1432 100 +
1433 0.5);
1434}
1435
1436// static
1437VP9EncoderImpl::VariableFramerateExperiment
1438VP9EncoderImpl::ParseVariableFramerateConfig(std::string group_name) {
1439 FieldTrialFlag enabled = FieldTrialFlag("Enabled");
1440 FieldTrialParameter<double> framerate_limit("min_fps", 5.0);
1441 FieldTrialParameter<int> qp("min_qp", 32);
1442 FieldTrialParameter<int> undershoot_percentage("undershoot", 30);
1443 FieldTrialParameter<int> frames_before_steady_state(
1444 "frames_before_steady_state", 5);
1445 ParseFieldTrial({&enabled, &framerate_limit, &qp, &undershoot_percentage,
1446 &frames_before_steady_state},
1447 field_trial::FindFullName(group_name));
1448 VariableFramerateExperiment config;
1449 config.enabled = enabled.Get();
1450 config.framerate_limit = framerate_limit.Get();
1451 config.steady_state_qp = qp.Get();
1452 config.steady_state_undershoot_percentage = undershoot_percentage.Get();
1453 config.frames_before_steady_state = frames_before_steady_state.Get();
1454
1455 return config;
1456}
1457
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001458VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001459 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001460 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001461 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001462 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001463
1464VP9DecoderImpl::~VP9DecoderImpl() {
1465 inited_ = true; // in order to do the actual release
1466 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001467 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1468 if (num_buffers_in_use > 0) {
1469 // The frame buffers are reference counted and frames are exposed after
1470 // decoding. There may be valid usage cases where previous frames are still
1471 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001472 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1473 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001474 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001475}
1476
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001477int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001478 int ret_val = Release();
1479 if (ret_val < 0) {
1480 return ret_val;
1481 }
Sergey Silkinb674cd12018-10-09 10:59:06 +02001482
sprang3958ed82017-08-17 08:12:10 -07001483 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001484 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001485 }
philipelcce46fc2015-12-21 03:04:49 -08001486 vpx_codec_dec_cfg_t cfg;
Sergey Silkinb674cd12018-10-09 10:59:06 +02001487 memset(&cfg, 0, sizeof(cfg));
1488
1489 // We want to use multithreading when decoding high resolution videos. But,
1490 // since we don't know resolution of input stream at this stage, we always
1491 // enable it.
1492 cfg.threads = std::min(number_of_cores, kMaxNumTiles4kVideo);
1493
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001494 vpx_codec_flags_t flags = 0;
1495 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1496 return WEBRTC_VIDEO_CODEC_MEMORY;
1497 }
Henrik Boström9695d852015-05-06 10:42:15 +02001498
1499 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1500 return WEBRTC_VIDEO_CODEC_MEMORY;
1501 }
1502
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001503 inited_ = true;
1504 // Always start with a complete key frame.
1505 key_frame_required_ = true;
1506 return WEBRTC_VIDEO_CODEC_OK;
1507}
1508
1509int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1510 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001511 const CodecSpecificInfo* codec_specific_info,
1512 int64_t /*render_time_ms*/) {
1513 if (!inited_) {
1514 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1515 }
sprang3958ed82017-08-17 08:12:10 -07001516 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001517 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1518 }
1519 // Always start with a complete key frame.
1520 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +02001521 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001522 return WEBRTC_VIDEO_CODEC_ERROR;
1523 // We have a key frame - is it complete?
1524 if (input_image._completeFrame) {
1525 key_frame_required_ = false;
1526 } else {
1527 return WEBRTC_VIDEO_CODEC_ERROR;
1528 }
1529 }
sprang3958ed82017-08-17 08:12:10 -07001530 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001531 vpx_image_t* img;
Niels Möller24871e42019-01-17 11:31:13 +01001532 const uint8_t* buffer = input_image.data();
Niels Möller77536a22019-01-15 08:50:01 +01001533 if (input_image.size() == 0) {
sprang3958ed82017-08-17 08:12:10 -07001534 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001535 }
Henrik Boström9695d852015-05-06 10:42:15 +02001536 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1537 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001538 if (vpx_codec_decode(decoder_, buffer,
Niels Möller77536a22019-01-15 08:50:01 +01001539 static_cast<unsigned int>(input_image.size()), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001540 VPX_DL_REALTIME)) {
1541 return WEBRTC_VIDEO_CODEC_ERROR;
1542 }
Henrik Boström9695d852015-05-06 10:42:15 +02001543 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1544 // It may be released by libvpx during future vpx_codec_decode or
1545 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001546 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001547 int qp;
1548 vpx_codec_err_t vpx_ret =
1549 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1550 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
Johannes Kron9973fa82018-11-07 14:39:26 +01001551 int ret = ReturnFrame(img, input_image.Timestamp(), input_image.ntp_time_ms_,
Johannes Kron4749e4e2018-11-21 10:18:18 +01001552 qp, input_image.ColorSpace());
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001553 if (ret != 0) {
1554 return ret;
1555 }
1556 return WEBRTC_VIDEO_CODEC_OK;
1557}
1558
Danil Chapovalovb7698942019-02-05 11:32:19 +01001559int VP9DecoderImpl::ReturnFrame(
1560 const vpx_image_t* img,
1561 uint32_t timestamp,
1562 int64_t ntp_time_ms,
1563 int qp,
1564 const webrtc::ColorSpace* explicit_color_space) {
sprang3958ed82017-08-17 08:12:10 -07001565 if (img == nullptr) {
1566 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001567 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1568 }
Henrik Boström9695d852015-05-06 10:42:15 +02001569
1570 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001571 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001572 // vpx_codec_decode calls or vpx_codec_destroy).
1573 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1574 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001575
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001576 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001577 // using a Wrapped*Buffer.
1578 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1579 switch (img->bit_depth) {
1580 case 8:
1581 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001582 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1583 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1584 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1585 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001586 // WrappedI420Buffer's mechanism for allowing the release of its frame
1587 // buffer is through a callback function. This is where we should
1588 // release |img_buffer|.
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001589 rtc::KeepRefUntilDone(img_buffer));
1590 break;
1591 case 10:
1592 img_wrapped_buffer = WrapI010Buffer(
1593 img->d_w, img->d_h,
1594 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1595 img->stride[VPX_PLANE_Y] / 2,
1596 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1597 img->stride[VPX_PLANE_U] / 2,
1598 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1599 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1600 break;
1601 default:
1602 RTC_NOTREACHED();
1603 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1604 }
nisseca6d5d12016-06-17 05:03:04 -07001605
Johannes Kron4749e4e2018-11-21 10:18:18 +01001606 auto builder = VideoFrame::Builder()
1607 .set_video_frame_buffer(img_wrapped_buffer)
1608 .set_timestamp_ms(0)
1609 .set_timestamp_rtp(timestamp)
1610 .set_ntp_time_ms(ntp_time_ms)
1611 .set_rotation(webrtc::kVideoRotation_0);
1612 if (explicit_color_space) {
Danil Chapovalovb7698942019-02-05 11:32:19 +01001613 builder.set_color_space(*explicit_color_space);
Johannes Kron4749e4e2018-11-21 10:18:18 +01001614 } else {
1615 builder.set_color_space(
1616 ExtractVP9ColorSpace(img->cs, img->range, img->bit_depth));
1617 }
1618
1619 VideoFrame decoded_image = builder.build();
1620
Danil Chapovalov0040b662018-06-18 10:48:16 +02001621 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001622 return WEBRTC_VIDEO_CODEC_OK;
1623}
1624
1625int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1626 DecodedImageCallback* callback) {
1627 decode_complete_callback_ = callback;
1628 return WEBRTC_VIDEO_CODEC_OK;
1629}
1630
1631int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001632 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1633
sprang3958ed82017-08-17 08:12:10 -07001634 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001635 if (inited_) {
1636 // When a codec is destroyed libvpx will release any buffers of
1637 // |frame_buffer_pool_| it is currently using.
1638 if (vpx_codec_destroy(decoder_)) {
1639 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1640 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001641 }
1642 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001643 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001644 }
Henrik Boström9695d852015-05-06 10:42:15 +02001645 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1646 // still referenced externally are deleted once fully released, not returning
1647 // to the pool.
1648 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001649 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001650 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001651}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001652
1653const char* VP9DecoderImpl::ImplementationName() const {
1654 return "libvpx";
1655}
1656
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001657} // namespace webrtc
Mirko Bonadei95adedb2018-11-19 09:52:37 +01001658
1659#endif // RTC_ENABLE_VP9