blob: d8f5877e24b40aedadb4bf22d547f7f5b81b29be [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 Bonadei92ea95e2017-09-15 06:47:31 +020012#include "modules/video_coding/codecs/vp9/vp9_impl.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000013
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +020014#include <algorithm>
Sergey Silkind45b3452018-05-31 16:00:24 +020015#include <limits>
marpan@webrtc.org5b883172014-11-01 06:10:48 +000016#include <vector>
17
marpan@webrtc.org5b883172014-11-01 06:10:48 +000018#include "vpx/vp8cx.h"
19#include "vpx/vp8dx.h"
Yves Gerey665174f2018-06-19 15:03:05 +020020#include "vpx/vpx_decoder.h"
21#include "vpx/vpx_encoder.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000022
Karl Wiberg918f50c2018-07-05 11:40:33 +020023#include "absl/memory/memory.h"
Emircan Uysaler800787f2018-07-16 10:01:49 -070024#include "api/video/color_space.h"
Emircan Uysaler0823eec2018-07-13 17:10:00 -070025#include "api/video/i010_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "common_video/include/video_frame_buffer.h"
27#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkind902d582018-05-18 17:31:19 +020028#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020029#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/checks.h"
31#include "rtc_base/keep_ref_until_done.h"
32#include "rtc_base/logging.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/timeutils.h"
34#include "rtc_base/trace_event.h"
Sergey Silkin390f3582018-10-01 17:13:50 +020035#include "system_wrappers/include/field_trial.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000036
37namespace webrtc {
38
Sergey Silkind902d582018-05-18 17:31:19 +020039namespace {
Sergey Silkin390f3582018-10-01 17:13:50 +020040// Maps from gof_idx to encoder internal reference frame buffer index. These
41// maps work for 1,2 and 3 temporal layers with GOF length of 1,2 and 4 frames.
42uint8_t kRefBufIdx[4] = {0, 0, 0, 1};
43uint8_t kUpdBufIdx[4] = {0, 0, 1, 0};
44
Sergey Silkinb674cd12018-10-09 10:59:06 +020045int kMaxNumTiles4kVideo = 8;
46
Marco6e89b252015-07-07 14:40:38 -070047// Only positive speeds, range for real-time coding currently is: 5 - 8.
48// Lower means slower/better quality, higher means fastest/lower quality.
49int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070050#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080051 return 8;
52#else
Marco6e89b252015-07-07 14:40:38 -070053 // For smaller resolutions, use lower speed setting (get some coding gain at
54 // the cost of increased encoding complexity).
55 if (width * height <= 352 * 288)
56 return 5;
57 else
58 return 7;
Marco002f0d02015-12-17 09:49:31 -080059#endif
Marco6e89b252015-07-07 14:40:38 -070060}
Emircan Uysaler715cc232018-07-23 17:50:43 -070061// Helper class for extracting VP9 colorspace.
62ColorSpace ExtractVP9ColorSpace(vpx_color_space_t space_t,
63 vpx_color_range_t range_t,
64 unsigned int bit_depth) {
65 ColorSpace::PrimaryID primaries = ColorSpace::PrimaryID::kInvalid;
66 ColorSpace::TransferID transfer = ColorSpace::TransferID::kInvalid;
67 ColorSpace::MatrixID matrix = ColorSpace::MatrixID::kInvalid;
68 switch (space_t) {
69 case VPX_CS_BT_601:
70 case VPX_CS_SMPTE_170:
71 primaries = ColorSpace::PrimaryID::kSMPTE170M;
72 transfer = ColorSpace::TransferID::kSMPTE170M;
73 matrix = ColorSpace::MatrixID::kSMPTE170M;
74 break;
75 case VPX_CS_SMPTE_240:
76 primaries = ColorSpace::PrimaryID::kSMPTE240M;
77 transfer = ColorSpace::TransferID::kSMPTE240M;
78 matrix = ColorSpace::MatrixID::kSMPTE240M;
79 break;
80 case VPX_CS_BT_709:
81 primaries = ColorSpace::PrimaryID::kBT709;
82 transfer = ColorSpace::TransferID::kBT709;
83 matrix = ColorSpace::MatrixID::kBT709;
84 break;
85 case VPX_CS_BT_2020:
86 primaries = ColorSpace::PrimaryID::kBT2020;
87 switch (bit_depth) {
88 case 8:
89 transfer = ColorSpace::TransferID::kBT709;
90 break;
91 case 10:
92 transfer = ColorSpace::TransferID::kBT2020_10;
93 break;
94 default:
95 RTC_NOTREACHED();
96 break;
97 }
98 matrix = ColorSpace::MatrixID::kBT2020_NCL;
99 break;
100 case VPX_CS_SRGB:
101 primaries = ColorSpace::PrimaryID::kBT709;
102 transfer = ColorSpace::TransferID::kIEC61966_2_1;
103 matrix = ColorSpace::MatrixID::kBT709;
104 break;
105 default:
106 break;
107 }
108
109 ColorSpace::RangeID range = ColorSpace::RangeID::kInvalid;
110 switch (range_t) {
111 case VPX_CR_STUDIO_RANGE:
112 range = ColorSpace::RangeID::kLimited;
113 break;
114 case VPX_CR_FULL_RANGE:
115 range = ColorSpace::RangeID::kFull;
116 break;
117 default:
118 break;
119 }
120 return ColorSpace(primaries, transfer, matrix, range);
121}
122} // namespace
Marco6e89b252015-07-07 14:40:38 -0700123
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700124std::vector<SdpVideoFormat> SupportedVP9Codecs() {
Max Morin221ee3c2018-09-14 07:50:07 +0000125 // TODO(emircan): Add Profile 2 support after fixing browser_tests.
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700126 std::vector<SdpVideoFormat> supported_formats{SdpVideoFormat(
127 cricket::kVp9CodecName,
128 {{kVP9FmtpProfileId, VP9ProfileToString(VP9Profile::kProfile0)}})};
129 return supported_formats;
Peter Boström12996152016-05-14 02:03:18 +0200130}
131
Magnus Jedvert46a27652017-11-13 14:10:02 +0100132std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200133 return absl::make_unique<VP9EncoderImpl>(cricket::VideoCodec());
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700134}
135
136std::unique_ptr<VP9Encoder> VP9Encoder::Create(
137 const cricket::VideoCodec& codec) {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200138 return absl::make_unique<VP9EncoderImpl>(codec);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000139}
140
asaperssona9455ab2015-07-31 06:10:09 -0700141void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
142 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -0800143 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -0700144 enc->GetEncodedLayerFrame(pkt);
145}
146
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700147VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000148 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -0700149 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700150 profile_(
151 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000152 inited_(false),
153 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000154 cpu_speed_(3),
155 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -0700156 encoder_(nullptr),
157 config_(nullptr),
158 raw_(nullptr),
159 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200160 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200161 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -0700162 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -0800163 num_spatial_layers_(0),
Sergey Silkin390f3582018-10-01 17:13:50 +0200164 num_active_spatial_layers_(0),
Sergey Silkine7ce8882018-10-03 18:04:57 +0200165 layer_deactivation_requires_key_frame_(webrtc::field_trial::IsEnabled(
166 "WebRTC-Vp9IssueKeyFrameOnLayerDeactivation")),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200167 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200168 inter_layer_pred_(InterLayerPredMode::kOn),
Sergey Silkin390f3582018-10-01 17:13:50 +0200169 external_ref_control_(
170 webrtc::field_trial::IsEnabled("WebRTC-Vp9ExternalRefCtrl")),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200171 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000172 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -0800173 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000174}
175
176VP9EncoderImpl::~VP9EncoderImpl() {
177 Release();
178}
179
180int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100181 int ret_val = WEBRTC_VIDEO_CODEC_OK;
182
sprang3958ed82017-08-17 08:12:10 -0700183 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800184 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -0700185 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000186 }
sprang3958ed82017-08-17 08:12:10 -0700187 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100188 if (inited_) {
189 if (vpx_codec_destroy(encoder_)) {
190 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
191 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000192 }
193 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700194 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000195 }
sprang3958ed82017-08-17 08:12:10 -0700196 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000197 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700198 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000199 }
sprang3958ed82017-08-17 08:12:10 -0700200 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000201 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700202 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000203 }
204 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100205 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000206}
207
sprangce4aef12015-11-02 07:23:20 -0800208bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
209 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
210 // (i.e. bitrates) were explicitly configured.
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200211 return codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800212}
213
Erik Språng566124a2018-04-23 12:32:22 +0200214bool VP9EncoderImpl::SetSvcRates(
215 const VideoBitrateAllocation& bitrate_allocation) {
Sergey Silkin86684962018-03-28 19:32:37 +0200216 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200217
sprangce4aef12015-11-02 07:23:20 -0800218 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200219 const bool layer_activation_requires_key_frame =
220 inter_layer_pred_ == InterLayerPredMode::kOff ||
221 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic;
222
Sergey Silkin86684962018-03-28 19:32:37 +0200223 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200224 const bool was_layer_active = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200225 config_->ss_target_bitrate[sl_idx] =
226 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
227
228 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
229 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
230 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
231 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200232
Sergey Silkine7ce8882018-10-03 18:04:57 +0200233 const bool is_active_layer = (config_->ss_target_bitrate[sl_idx] > 0);
234 if (!was_layer_active && is_active_layer &&
235 layer_activation_requires_key_frame) {
236 force_key_frame_ = true;
237 } else if (was_layer_active && !is_active_layer &&
238 layer_deactivation_requires_key_frame_) {
239 force_key_frame_ = true;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200240 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200241
Sergey Silkine7ce8882018-10-03 18:04:57 +0200242 if (!was_layer_active) {
Sergey Silkin96f2c972018-09-05 21:07:17 +0200243 // Reset frame rate controller if layer is resumed after pause.
244 framerate_controller_[sl_idx].Reset();
245 }
246
247 framerate_controller_[sl_idx].SetTargetRate(
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200248 std::min(static_cast<float>(codec_.maxFramerate),
249 codec_.spatialLayers[sl_idx].maxFramerate));
sprangce4aef12015-11-02 07:23:20 -0800250 }
251 } else {
252 float rate_ratio[VPX_MAX_LAYERS] = {0};
253 float total = 0;
Sergey Silkin908689d2018-08-20 09:28:45 +0200254 for (int i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800255 if (svc_params_.scaling_factor_num[i] <= 0 ||
256 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100257 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800258 return false;
259 }
Yves Gerey665174f2018-06-19 15:03:05 +0200260 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
261 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800262 total += rate_ratio[i];
263 }
264
Sergey Silkin908689d2018-08-20 09:28:45 +0200265 for (int i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200266 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800267 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
268 config_->rc_target_bitrate * rate_ratio[i] / total);
269 if (num_temporal_layers_ == 1) {
270 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
271 } else if (num_temporal_layers_ == 2) {
272 config_->layer_target_bitrate[i * num_temporal_layers_] =
273 config_->ss_target_bitrate[i] * 2 / 3;
274 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
275 config_->ss_target_bitrate[i];
276 } else if (num_temporal_layers_ == 3) {
277 config_->layer_target_bitrate[i * num_temporal_layers_] =
278 config_->ss_target_bitrate[i] / 2;
279 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
280 config_->layer_target_bitrate[i * num_temporal_layers_] +
281 (config_->ss_target_bitrate[i] / 4);
282 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
283 config_->ss_target_bitrate[i];
284 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100285 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
286 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800287 return false;
288 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200289
290 framerate_controller_[i].SetTargetRate(codec_.maxFramerate);
asaperssona9455ab2015-07-31 06:10:09 -0700291 }
292 }
Sergey Silkin908689d2018-08-20 09:28:45 +0200293
294 num_active_spatial_layers_ = 0;
295 for (int i = 0; i < num_spatial_layers_; ++i) {
296 if (config_->ss_target_bitrate[i] > 0) {
297 ++num_active_spatial_layers_;
298 }
299 }
300 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
301
asaperssona9455ab2015-07-31 06:10:09 -0700302 return true;
303}
304
Erik Språng08127a92016-11-16 16:41:30 +0100305int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200306 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100307 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000308 if (!inited_) {
309 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
310 }
311 if (encoder_->err) {
312 return WEBRTC_VIDEO_CODEC_ERROR;
313 }
Erik Språng08127a92016-11-16 16:41:30 +0100314 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000315 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
316 }
317 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100318 if (codec_.maxBitrate > 0 &&
319 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
320 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000321 }
Erik Språng08127a92016-11-16 16:41:30 +0100322
Erik Språng08127a92016-11-16 16:41:30 +0100323 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700324
Sergey Silkin86684962018-03-28 19:32:37 +0200325 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700326 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
327 }
328
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000329 // Update encoder context
330 if (vpx_codec_enc_config_set(encoder_, config_)) {
331 return WEBRTC_VIDEO_CODEC_ERROR;
332 }
333 return WEBRTC_VIDEO_CODEC_OK;
334}
335
336int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
337 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000338 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700339 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000340 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
341 }
342 if (inst->maxFramerate < 1) {
343 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
344 }
345 // Allow zero to represent an unspecified maxBitRate
346 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
347 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
348 }
349 if (inst->width < 1 || inst->height < 1) {
350 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
351 }
352 if (number_of_cores < 1) {
353 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
354 }
hta257dc392016-10-25 09:05:06 -0700355 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700356 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
357 }
ilnik2a8c2f52017-02-15 02:23:28 -0800358 // libvpx probably does not support more than 3 spatial layers.
359 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700360 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
361 }
philipelcfc319b2015-11-10 07:17:23 -0800362
asapersson86956de2016-01-26 01:05:20 -0800363 int ret_val = Release();
364 if (ret_val < 0) {
365 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000366 }
sprang3958ed82017-08-17 08:12:10 -0700367 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000368 encoder_ = new vpx_codec_ctx_t;
369 }
sprang3958ed82017-08-17 08:12:10 -0700370 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000371 config_ = new vpx_codec_enc_cfg_t;
372 }
373 timestamp_ = 0;
374 if (&codec_ != inst) {
375 codec_ = *inst;
376 }
asaperssona9455ab2015-07-31 06:10:09 -0700377
Sergey Silkinb0bd03b2018-09-28 14:56:39 +0200378 force_key_frame_ = true;
379 pics_since_key_ = 0;
380
hta257dc392016-10-25 09:05:06 -0700381 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200382 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700383 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200384 if (num_temporal_layers_ == 0) {
asaperssona9455ab2015-07-31 06:10:09 -0700385 num_temporal_layers_ = 1;
Sergey Silkin042661b2018-09-10 10:39:35 +0000386 }
Sergey Silkinae9e1882018-09-05 21:07:17 +0200387
Sergey Silkin96f2c972018-09-05 21:07:17 +0200388 framerate_controller_ = std::vector<FramerateController>(
389 num_spatial_layers_, FramerateController(codec_.maxFramerate));
390
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200391 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200392
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000393 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700394 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800395 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000396 }
nisseeb44b392017-04-28 07:18:05 -0700397 encoded_image_._size =
398 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000399 encoded_image_._buffer = new uint8_t[encoded_image_._size];
400 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000401 // Populate encoder configuration with default values.
402 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
403 return WEBRTC_VIDEO_CODEC_ERROR;
404 }
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700405
406 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
407 unsigned int bits_for_storage = 8;
408 switch (profile_) {
409 case VP9Profile::kProfile0:
410 img_fmt = VPX_IMG_FMT_I420;
411 bits_for_storage = 8;
412 config_->g_bit_depth = VPX_BITS_8;
413 config_->g_profile = 0;
414 config_->g_input_bit_depth = 8;
415 break;
416 case VP9Profile::kProfile2:
417 img_fmt = VPX_IMG_FMT_I42016;
418 bits_for_storage = 16;
419 config_->g_bit_depth = VPX_BITS_10;
420 config_->g_profile = 2;
421 config_->g_input_bit_depth = 10;
422 break;
423 }
424
425 // Creating a wrapper to the image - setting image data to nullptr. Actual
426 // pointer will be set in encode. Setting align to 1, as it is meaningless
427 // (actual memory is not allocated).
428 raw_ =
429 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
430 raw_->bit_depth = bits_for_storage;
431
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000432 config_->g_w = codec_.width;
433 config_->g_h = codec_.height;
434 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200435 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000436 // Setting the time base of the codec.
437 config_->g_timebase.num = 1;
438 config_->g_timebase.den = 90000;
439 config_->g_lag_in_frames = 0; // 0- no frame lagging
440 config_->g_threads = 1;
441 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700442 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000443 config_->rc_end_usage = VPX_CBR;
444 config_->g_pass = VPX_RC_ONE_PASS;
445 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000446 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000447 config_->rc_undershoot_pct = 50;
448 config_->rc_overshoot_pct = 50;
449 config_->rc_buf_initial_sz = 500;
450 config_->rc_buf_optimal_sz = 600;
451 config_->rc_buf_sz = 1000;
452 // Set the maximum target size of any key-frame.
453 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700454 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000455 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700456 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100457 // Needs to be set (in svc mode) to get correct periodic key frame interval
458 // (will have no effect in non-svc).
459 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000460 } else {
461 config_->kf_mode = VPX_KF_DISABLED;
462 }
hta257dc392016-10-25 09:05:06 -0700463 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000464 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800465 config_->g_threads =
466 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700467
Marco6e89b252015-07-07 14:40:38 -0700468 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700469
hta257dc392016-10-25 09:05:06 -0700470 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200471
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200472 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700473 gof_.SetGofInfoVP9(kTemporalStructureMode1);
474 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
475 config_->ts_number_layers = 1;
476 config_->ts_rate_decimator[0] = 1;
477 config_->ts_periodicity = 1;
478 config_->ts_layer_id[0] = 0;
479 } else if (num_temporal_layers_ == 2) {
480 gof_.SetGofInfoVP9(kTemporalStructureMode2);
481 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
482 config_->ts_number_layers = 2;
483 config_->ts_rate_decimator[0] = 2;
484 config_->ts_rate_decimator[1] = 1;
485 config_->ts_periodicity = 2;
486 config_->ts_layer_id[0] = 0;
487 config_->ts_layer_id[1] = 1;
488 } else if (num_temporal_layers_ == 3) {
489 gof_.SetGofInfoVP9(kTemporalStructureMode3);
490 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
491 config_->ts_number_layers = 3;
492 config_->ts_rate_decimator[0] = 4;
493 config_->ts_rate_decimator[1] = 2;
494 config_->ts_rate_decimator[2] = 1;
495 config_->ts_periodicity = 4;
496 config_->ts_layer_id[0] = 0;
497 config_->ts_layer_id[1] = 2;
498 config_->ts_layer_id[2] = 1;
499 config_->ts_layer_id[3] = 2;
500 } else {
501 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
502 }
503
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200504 inter_layer_pred_ = inst->VP9().interLayerPred;
505
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200506 ref_buf_.clear();
507
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000508 return InitAndSetControlSettings(inst);
509}
510
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000511int VP9EncoderImpl::NumberOfThreads(int width,
512 int height,
513 int number_of_cores) {
514 // Keep the number of encoder threads equal to the possible number of column
515 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
516 if (width * height >= 1280 * 720 && number_of_cores > 4) {
517 return 4;
jianj23173a32017-07-12 16:11:09 -0700518 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000519 return 2;
520 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200521// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800522#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
523 defined(WEBRTC_ANDROID)
524 if (width * height >= 320 * 180 && number_of_cores > 2) {
525 return 2;
526 }
527#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000528 // 1 thread less than VGA.
529 return 1;
530 }
531}
532
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000533int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100534 // Set QP-min/max per spatial and temporal layer.
535 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
536 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800537 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
538 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100539 }
asaperssona9455ab2015-07-31 06:10:09 -0700540 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800541 if (ExplicitlyConfiguredSpatialLayers()) {
542 for (int i = 0; i < num_spatial_layers_; ++i) {
543 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200544 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100545 const int scale_factor = codec_.width / layer.width;
546 RTC_DCHECK_GT(scale_factor, 0);
547
548 // Ensure scaler factor is integer.
549 if (scale_factor * layer.width != codec_.width) {
550 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
551 }
552
553 // Ensure scale factor is the same in both dimensions.
554 if (scale_factor * layer.height != codec_.height) {
555 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
556 }
557
558 // Ensure scale factor is power of two.
559 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
560 if (!is_pow_of_two) {
561 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
562 }
563
564 svc_params_.scaling_factor_num[i] = 1;
565 svc_params_.scaling_factor_den[i] = scale_factor;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200566
567 RTC_DCHECK_GT(codec_.spatialLayers[i].maxFramerate, 0);
568 RTC_DCHECK_LE(codec_.spatialLayers[i].maxFramerate, codec_.maxFramerate);
569 if (i > 0) {
570 // Frame rate of high spatial layer is supposed to be equal or higher
571 // than frame rate of low spatial layer.
572 RTC_DCHECK_GE(codec_.spatialLayers[i].maxFramerate,
573 codec_.spatialLayers[i - 1].maxFramerate);
574 }
sprangce4aef12015-11-02 07:23:20 -0800575 }
576 } else {
577 int scaling_factor_num = 256;
578 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800579 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800580 svc_params_.scaling_factor_num[i] = scaling_factor_num;
581 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800582 }
asaperssona9455ab2015-07-31 06:10:09 -0700583 }
584
Sergey Silkin86684962018-03-28 19:32:37 +0200585 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200586 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200587 inst->startBitrate * 1000, inst->maxFramerate);
588 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700589 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
590 }
591
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700592 const vpx_codec_err_t rv = vpx_codec_enc_init(
593 encoder_, vpx_codec_vp9_cx(), config_,
594 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
595 if (rv != VPX_CODEC_OK) {
596 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000597 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
598 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000599 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
600 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
601 rc_max_intra_target_);
602 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700603 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700604
jianj822e5932017-07-12 16:09:58 -0700605 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200606
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200607 if (is_svc_) {
608 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
609 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700610 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200611
612 if (num_spatial_layers_ > 1) {
613 switch (inter_layer_pred_) {
614 case InterLayerPredMode::kOn:
615 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
616 break;
617 case InterLayerPredMode::kOff:
618 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
619 break;
620 case InterLayerPredMode::kOnKeyPic:
621 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
622 break;
623 default:
624 RTC_NOTREACHED();
625 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200626
Sergey Silkinee203362018-05-30 11:34:08 +0200627 // Configure encoder to drop entire superframe whenever it needs to drop
628 // a layer. This mode is prefered over per-layer dropping which causes
629 // quality flickering and is not compatible with RTP non-flexible mode.
630 vpx_svc_frame_drop_t svc_drop_frame;
631 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
632 svc_drop_frame.framedrop_mode = FULL_SUPERFRAME_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200633 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200634 for (size_t i = 0; i < num_spatial_layers_; ++i) {
635 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200636 }
Sergey Silkinee203362018-05-30 11:34:08 +0200637 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200638 }
639
asaperssona9455ab2015-07-31 06:10:09 -0700640 // Register callback for getting each spatial layer.
641 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800642 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
643 reinterpret_cast<void*>(this)};
644 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
645 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700646
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000647 // Control function to set the number of column tiles in encoding a frame, in
648 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
649 // The number tile columns will be capped by the encoder based on image size
650 // (minimum width of tile column is 256 pixels, maximum is 4096).
651 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700652
653 // Turn on row-based multithreading.
654 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700655
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700656#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200657 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700658 // Do not enable the denoiser on ARM since optimization is pending.
659 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000660 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700661 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000662#endif
jianj6bf57e32017-06-05 13:43:49 -0700663
Niels Möllere3cf3d02018-06-13 11:52:16 +0200664 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700665 // Adjust internal parameters to screen content.
666 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700667 }
Marco2520e722015-09-16 14:05:00 -0700668 // Enable encoder skip of static/low content blocks.
669 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000670 inited_ = true;
671 return WEBRTC_VIDEO_CODEC_OK;
672}
673
674uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
675 // Set max to the optimal buffer level (normalized by target BR),
676 // and scaled by a scale_par.
677 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
678 // This value is presented in percentage of perFrameBw:
679 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
680 // The target in % is as follows:
681 float scale_par = 0.5;
682 uint32_t target_pct =
683 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
684 // Don't go below 3 times the per frame bandwidth.
685 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800686 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000687}
688
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700689int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000690 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700691 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000692 if (!inited_) {
693 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
694 }
sprang3958ed82017-08-17 08:12:10 -0700695 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000696 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
697 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200698
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000699 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200700 if (frame_types && !frame_types->empty()) {
701 if ((*frame_types)[0] == kVideoFrameKey) {
702 force_key_frame_ = true;
703 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000704 }
Sergey Silkind902d582018-05-18 17:31:19 +0200705
Niels Möllere3cf3d02018-06-13 11:52:16 +0200706 if (VideoCodecMode::kScreensharing == codec_.mode && !force_key_frame_) {
Sergey Silkin96f2c972018-09-05 21:07:17 +0200707 // Skip encoding spatial layer frames if their target frame rate is lower
708 // than actual input frame rate.
709 vpx_svc_layer_id_t layer_id = {0};
710 const size_t gof_idx = (pics_since_key_ + 1) % gof_.num_frames_in_gof;
711 layer_id.temporal_layer_id = gof_.temporal_idx[gof_idx];
712
713 const uint32_t frame_timestamp_ms =
714 1000 * input_image.timestamp() / kVideoPayloadTypeFrequency;
715
716 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
717 if (framerate_controller_[sl_idx].DropFrame(frame_timestamp_ms)) {
718 ++layer_id.spatial_layer_id;
719 } else {
720 break;
721 }
722 }
723
724 RTC_DCHECK_LE(layer_id.spatial_layer_id, num_active_spatial_layers_);
725 if (layer_id.spatial_layer_id >= num_active_spatial_layers_) {
726 // Drop entire picture.
Sergey Silkind902d582018-05-18 17:31:19 +0200727 return WEBRTC_VIDEO_CODEC_OK;
728 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200729
730 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
Sergey Silkind902d582018-05-18 17:31:19 +0200731 }
732
kwiberg352444f2016-11-28 15:58:53 -0800733 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
734 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700735
736 // Set input image for use in the callback.
737 // This was necessary since you need some information from input_image.
738 // You can save only the necessary information (such as timestamp) instead of
739 // doing this.
740 input_image_ = &input_image;
741
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700742 // Keep reference to buffer until encode completes.
743 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
744 rtc::scoped_refptr<I010BufferInterface> i010_buffer;
745 switch (profile_) {
746 case VP9Profile::kProfile0: {
747 i420_buffer = input_image.video_frame_buffer()->ToI420();
748 // Image in vpx_image_t format.
749 // Input image is const. VPX's raw image is not defined as const.
750 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
751 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
752 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
753 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
754 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
755 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
756 break;
757 }
758 case VP9Profile::kProfile2: {
759 // We can inject kI010 frames directly for encode. All other formats
760 // should be converted to it.
761 switch (input_image.video_frame_buffer()->type()) {
762 case VideoFrameBuffer::Type::kI010: {
763 i010_buffer = input_image.video_frame_buffer()->GetI010();
764 break;
765 }
766 default: {
767 i010_buffer =
768 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
769 }
770 }
771 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
772 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
773 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
774 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
775 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
776 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
777 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
778 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
779 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
780 break;
781 }
782 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000783
philipelcfc319b2015-11-10 07:17:23 -0800784 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200785 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000786 flags = VPX_EFLAG_FORCE_KF;
787 }
philipelcfc319b2015-11-10 07:17:23 -0800788
Sergey Silkin390f3582018-10-01 17:13:50 +0200789 if (external_ref_control_) {
790 vpx_svc_ref_frame_config_t ref_config = SetReferences(force_key_frame_);
791 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &ref_config);
792 }
793
Sergey Silkin96f2c972018-09-05 21:07:17 +0200794 // TODO(ssilkin): Frame duration should be specified per spatial layer
795 // since their frame rate can be different. For now calculate frame duration
796 // based on target frame rate of the highest spatial layer, which frame rate
797 // is supposed to be equal or higher than frame rate of low spatial layers.
798 // Also, timestamp should represent actual time passed since previous frame
799 // (not 'expected' time). Then rate controller can drain buffer more
800 // accurately.
801 RTC_DCHECK_GE(framerate_controller_.size(), num_active_spatial_layers_);
Sergey Silkinf87bb462018-09-17 09:37:37 +0200802 float target_framerate_fps =
803 (codec_.mode == VideoCodecMode::kScreensharing)
804 ? framerate_controller_[num_active_spatial_layers_ - 1]
805 .GetTargetRate()
806 : codec_.maxFramerate;
807 uint32_t duration = static_cast<uint32_t>(90000 / target_framerate_fps);
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700808 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
809 duration, flags, VPX_DL_REALTIME);
810 if (rv != VPX_CODEC_OK) {
811 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
812 << "\n"
813 << "Details: " << vpx_codec_error(encoder_) << "\n"
814 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000815 return WEBRTC_VIDEO_CODEC_ERROR;
816 }
817 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700818
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200819 const bool end_of_picture = true;
820 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200821
asaperssona9455ab2015-07-31 06:10:09 -0700822 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000823}
824
825void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
Niels Möllerd3b8c632018-08-27 15:33:42 +0200826 absl::optional<int>* spatial_idx,
philipelcce46fc2015-12-21 03:04:49 -0800827 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200828 uint32_t timestamp,
829 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700830 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000831 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700832 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800833 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200834
835 vp9_info->first_frame_in_picture = first_frame_in_picture;
Sergey Silkin738b7e92018-08-23 16:37:27 +0200836 vp9_info->flexible_mode = is_flexible_mode_;
hta257dc392016-10-25 09:05:06 -0700837 vp9_info->ss_data_available =
Sergey Silkin738b7e92018-08-23 16:37:27 +0200838 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
asaperssona9455ab2015-07-31 06:10:09 -0700839
840 vpx_svc_layer_id_t layer_id = {0};
841 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
842
sprang3958ed82017-08-17 08:12:10 -0700843 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -0500844 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700845 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700846 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700847 vp9_info->temporal_idx = kNoTemporalIdx;
848 } else {
849 vp9_info->temporal_idx = layer_id.temporal_layer_id;
850 }
“Michael23c5a992018-06-21 11:07:21 -0500851 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700852 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
Niels Möllerd3b8c632018-08-27 15:33:42 +0200853 *spatial_idx = absl::nullopt;
asaperssona9455ab2015-07-31 06:10:09 -0700854 } else {
Niels Möllerd3b8c632018-08-27 15:33:42 +0200855 *spatial_idx = layer_id.spatial_layer_id;
asaperssona9455ab2015-07-31 06:10:09 -0700856 }
857 if (layer_id.spatial_layer_id != 0) {
858 vp9_info->ss_data_available = false;
859 }
860
asaperssona9455ab2015-07-31 06:10:09 -0700861 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800862 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700863
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200864 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
865 pics_since_key_ = 0;
866 } else if (first_frame_in_picture) {
867 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700868 }
869
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200870 const bool is_key_pic = (pics_since_key_ == 0);
871 const bool is_inter_layer_pred_allowed =
872 (inter_layer_pred_ == InterLayerPredMode::kOn ||
873 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
874
875 // Always set inter_layer_predicted to true on high layer frame if inter-layer
876 // prediction (ILP) is allowed even if encoder didn't actually use it.
877 // Setting inter_layer_predicted to false would allow receiver to decode high
878 // layer frame without decoding low layer frame. If that would happen (e.g.
879 // if low layer frame is lost) then receiver won't be able to decode next high
880 // layer frame which uses ILP.
881 vp9_info->inter_layer_predicted =
882 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
883
Sergey Silkinc5f152d2018-09-26 13:28:50 +0200884 // Mark all low spatial layer frames as references (not just frames of
885 // active low spatial layers) if inter-layer prediction is enabled since
886 // these frames are indirect references of high spatial layer, which can
887 // later be enabled without key frame.
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200888 vp9_info->non_ref_for_inter_layer_pred =
Sergey Silkinc5f152d2018-09-26 13:28:50 +0200889 !is_inter_layer_pred_allowed ||
890 layer_id.spatial_layer_id + 1 == num_spatial_layers_;
asapersson00ac85e2015-11-11 05:30:48 -0800891
ivica7f6a6fc2015-09-08 02:40:29 -0700892 // Always populate this, so that the packetizer can properly set the marker
893 // bit.
“Michael23c5a992018-06-21 11:07:21 -0500894 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800895
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200896 vp9_info->num_ref_pics = 0;
897 if (vp9_info->flexible_mode) {
898 vp9_info->gof_idx = kNoGofIdx;
899 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
900 vp9_info);
Sergey Silkin390f3582018-10-01 17:13:50 +0200901 // TODO(webrtc:9794): Add fake reference to empty reference list to
902 // workaround the frame buffer issue on receiver.
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200903 } else {
904 vp9_info->gof_idx =
905 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
906 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
907 vp9_info->num_ref_pics = gof_.num_ref_pics[vp9_info->gof_idx];
908 }
909
910 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
911
asaperssona9455ab2015-07-31 06:10:09 -0700912 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700913 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -0500914 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +0200915 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800916 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +0200917 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800918 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700919 }
Sergey Silkin738b7e92018-08-23 16:37:27 +0200920 if (vp9_info->flexible_mode) {
921 vp9_info->gof.num_frames_in_gof = 0;
922 } else {
asaperssona9455ab2015-07-31 06:10:09 -0700923 vp9_info->gof.CopyGofInfoVP9(gof_);
924 }
925 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000926}
927
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200928void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
929 const size_t pic_num,
930 const bool inter_layer_predicted,
931 CodecSpecificInfoVP9* vp9_info) {
932 vpx_svc_layer_id_t layer_id = {0};
933 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
934
Sergey Silkin76be2952018-08-21 12:30:33 +0200935 const bool is_key_frame =
936 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200937
938 std::vector<RefFrameBuffer> ref_buf_list;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200939
Sergey Silkin76be2952018-08-21 12:30:33 +0200940 if (is_svc_) {
941 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
942 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200943
Sergey Silkin76be2952018-08-21 12:30:33 +0200944 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
945 const size_t fb_idx =
946 enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
947 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +0200948 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
949 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
950 ref_buf_list.push_back(ref_buf_.at(fb_idx));
951 }
Sergey Silkin76be2952018-08-21 12:30:33 +0200952 }
953
954 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
955 const size_t fb_idx =
956 enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
957 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +0200958 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
959 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
960 ref_buf_list.push_back(ref_buf_.at(fb_idx));
961 }
Sergey Silkin76be2952018-08-21 12:30:33 +0200962 }
963
964 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
965 const size_t fb_idx =
966 enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
967 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +0200968 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
969 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
970 ref_buf_list.push_back(ref_buf_.at(fb_idx));
971 }
Sergey Silkin76be2952018-08-21 12:30:33 +0200972 }
973 } else if (!is_key_frame) {
974 RTC_DCHECK_EQ(num_spatial_layers_, 1);
975 RTC_DCHECK_EQ(num_temporal_layers_, 1);
976 // In non-SVC mode encoder doesn't provide reference list. Assume each frame
977 // refers previous one, which is stored in buffer 0.
978 ref_buf_list.push_back(ref_buf_.at(0));
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200979 }
980
981 size_t max_ref_temporal_layer_id = 0;
982
983 vp9_info->num_ref_pics = 0;
984 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
985 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
986 if (ref_buf.pic_num < pic_num) {
987 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
988 // RTP spec limits temporal prediction to the same spatial layer.
989 // It is safe to ignore this requirement if inter-layer prediction is
990 // enabled for all frames when all base frames are relayed to receiver.
991 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
992 }
993 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
994
995 const size_t p_diff = pic_num - ref_buf.pic_num;
996 RTC_DCHECK_LE(p_diff, 127UL);
997
998 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
999 ++vp9_info->num_ref_pics;
1000
1001 max_ref_temporal_layer_id =
1002 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
1003 } else {
1004 RTC_DCHECK(inter_layer_predicted);
1005 // RTP spec only allows to use previous spatial layer for inter-layer
1006 // prediction.
1007 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
1008 }
1009 }
1010
1011 vp9_info->temporal_up_switch =
1012 (max_ref_temporal_layer_id <
1013 static_cast<size_t>(layer_id.temporal_layer_id));
1014}
1015
1016void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
1017 const size_t pic_num) {
1018 vpx_svc_layer_id_t layer_id = {0};
1019 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1020
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001021 const bool is_key_frame =
1022 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1023
1024 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
1025 layer_id.temporal_layer_id);
1026
1027 if (is_key_frame && layer_id.spatial_layer_id == 0) {
1028 // Key frame updates all ref buffers.
1029 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
1030 ref_buf_[i] = frame_buf;
1031 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001032 } else if (is_svc_) {
1033 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1034 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
1035
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001036 if (enc_layer_conf.update_last[layer_id.spatial_layer_id]) {
1037 ref_buf_[enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id]] =
1038 frame_buf;
1039 }
1040
1041 if (enc_layer_conf.update_alt_ref[layer_id.spatial_layer_id]) {
1042 ref_buf_[enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id]] =
1043 frame_buf;
1044 }
1045
1046 if (enc_layer_conf.update_golden[layer_id.spatial_layer_id]) {
1047 ref_buf_[enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id]] =
1048 frame_buf;
1049 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001050 } else {
1051 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1052 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1053 // In non-svc mode encoder doesn't provide reference list. Assume each frame
1054 // is reference and stored in buffer 0.
1055 ref_buf_[0] = frame_buf;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001056 }
1057}
1058
Sergey Silkin390f3582018-10-01 17:13:50 +02001059vpx_svc_ref_frame_config_t VP9EncoderImpl::SetReferences(bool is_key_pic) {
1060 // kRefBufIdx, kUpdBufIdx need to be updated to support longer GOFs.
1061 RTC_DCHECK_LE(gof_.num_frames_in_gof, 4);
1062
1063 vpx_svc_ref_frame_config_t ref_config;
1064 memset(&ref_config, 0, sizeof(ref_config));
1065
1066 const size_t num_temporal_refs = std::max(1, num_temporal_layers_ - 1);
1067 const bool is_inter_layer_pred_allowed =
1068 inter_layer_pred_ == InterLayerPredMode::kOn ||
1069 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic);
1070 absl::optional<int> last_updated_buf_idx;
1071
1072 // Put temporal reference to LAST and spatial reference to GOLDEN. Update
1073 // frame buffer (i.e. store encoded frame) if current frame is a temporal
1074 // reference (i.e. it belongs to a low temporal layer) or it is a spatial
1075 // reference. In later case, always store spatial reference in the last
1076 // reference frame buffer.
1077 // For the case of 3 temporal and 3 spatial layers we need 6 frame buffers
1078 // for temporal references plus 1 buffer for spatial reference. 7 buffers
1079 // in total.
1080
1081 for (size_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
1082 const size_t gof_idx = pics_since_key_ % gof_.num_frames_in_gof;
1083
1084 if (!is_key_pic) {
1085 // Set up temporal reference.
1086 const int buf_idx = sl_idx * num_temporal_refs + kRefBufIdx[gof_idx];
1087
1088 // Last reference frame buffer is reserved for spatial reference. It is
1089 // not supposed to be used for temporal prediction.
1090 RTC_DCHECK_LT(buf_idx, kNumVp9Buffers - 1);
1091
1092 // Sanity check that reference picture number is smaller than current
1093 // picture number.
1094 const size_t curr_pic_num = pics_since_key_ + 1;
1095 RTC_DCHECK_LT(ref_buf_[buf_idx].pic_num, curr_pic_num);
1096 const size_t pid_diff = curr_pic_num - ref_buf_[buf_idx].pic_num;
1097
1098 // Below code assumes single temporal referecence.
1099 RTC_DCHECK_EQ(gof_.num_ref_pics[gof_idx], 1);
1100 if (pid_diff == gof_.pid_diff[gof_idx][0]) {
1101 ref_config.lst_fb_idx[sl_idx] = buf_idx;
1102 ref_config.reference_last[sl_idx] = 1;
1103 } else {
1104 // This reference doesn't match with one specified by GOF. This can
1105 // only happen if spatial layer is enabled dynamically without key
1106 // frame. Spatial prediction is supposed to be enabled in this case.
1107 RTC_DCHECK(is_inter_layer_pred_allowed);
1108 }
1109 }
1110
1111 if (is_inter_layer_pred_allowed && sl_idx > 0) {
1112 // Set up spatial reference.
1113 RTC_DCHECK(last_updated_buf_idx);
1114 ref_config.gld_fb_idx[sl_idx] = *last_updated_buf_idx;
1115 ref_config.reference_golden[sl_idx] = 1;
1116 } else {
1117 RTC_DCHECK(ref_config.reference_last[sl_idx] != 0 || sl_idx == 0 ||
1118 inter_layer_pred_ == InterLayerPredMode::kOff);
1119 }
1120
1121 last_updated_buf_idx.reset();
1122
1123 if (gof_.temporal_idx[gof_idx] <= num_temporal_layers_ - 1) {
1124 last_updated_buf_idx = sl_idx * num_temporal_refs + kUpdBufIdx[gof_idx];
1125
1126 // Ensure last frame buffer is not used for temporal prediction (it is
1127 // reserved for spatial reference).
1128 RTC_DCHECK_LT(*last_updated_buf_idx, kNumVp9Buffers - 1);
1129 } else if (is_inter_layer_pred_allowed) {
1130 last_updated_buf_idx = kNumVp9Buffers - 1;
1131 }
1132
1133 if (last_updated_buf_idx) {
1134 ref_config.update_buffer_slot[sl_idx] = 1 << *last_updated_buf_idx;
1135 }
1136 }
1137
1138 return ref_config;
1139}
1140
asaperssona9455ab2015-07-31 06:10:09 -07001141int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -08001142 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -07001143
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001144 if (pkt->data.frame.sz == 0) {
1145 // Ignore dropped frame.
1146 return WEBRTC_VIDEO_CODEC_OK;
1147 }
1148
Sergey Silkin07f80cc2018-04-09 13:11:59 +02001149 vpx_svc_layer_id_t layer_id = {0};
1150 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1151
1152 const bool first_frame_in_picture = encoded_image_._length == 0;
1153 // Ensure we don't buffer layers of previous picture (superframe).
1154 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
1155
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001156 const bool end_of_picture = false;
1157 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001158
asaperssond9f641e2016-01-21 01:11:35 -08001159 if (pkt->data.frame.sz > encoded_image_._size) {
1160 delete[] encoded_image_._buffer;
1161 encoded_image_._size = pkt->data.frame.sz;
1162 encoded_image_._buffer = new uint8_t[encoded_image_._size];
1163 }
asapersson86956de2016-01-26 01:05:20 -08001164 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
1165 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -08001166
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001167 const bool is_key_frame =
1168 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1169 // Ensure encoder issued key frame on request.
1170 RTC_DCHECK(is_key_frame || !force_key_frame_);
1171
asaperssona9455ab2015-07-31 06:10:09 -07001172 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -08001173 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001174 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +02001175 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001176 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001177 }
asapersson86956de2016-01-26 01:05:20 -08001178 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
1179
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001180 memset(&codec_specific_, 0, sizeof(codec_specific_));
Niels Möllerd3b8c632018-08-27 15:33:42 +02001181 absl::optional<int> spatial_index;
1182 PopulateCodecSpecific(&codec_specific_, &spatial_index, *pkt,
1183 input_image_->timestamp(), first_frame_in_picture);
1184 encoded_image_.SetSpatialIndex(spatial_index);
asaperssona9455ab2015-07-31 06:10:09 -07001185
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001186 if (is_flexible_mode_) {
1187 UpdateReferenceBuffers(*pkt, pics_since_key_);
1188 }
1189
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001190 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
Niels Möller23775882018-08-16 10:24:12 +02001191 encoded_image_.SetTimestamp(input_image_->timestamp());
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001192 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
1193 encoded_image_.rotation_ = input_image_->rotation();
Niels Möllere3cf3d02018-06-13 11:52:16 +02001194 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001195 ? VideoContentType::SCREENSHARE
1196 : VideoContentType::UNSPECIFIED;
1197 encoded_image_._encodedHeight =
1198 pkt->data.frame.height[layer_id.spatial_layer_id];
1199 encoded_image_._encodedWidth =
1200 pkt->data.frame.width[layer_id.spatial_layer_id];
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +02001201 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001202 int qp = -1;
1203 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
1204 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -07001205
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001206 return WEBRTC_VIDEO_CODEC_OK;
1207}
1208
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001209void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001210 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001211 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001212
1213 // No data partitioning in VP9, so 1 partition only.
1214 int part_idx = 0;
1215 RTPFragmentationHeader frag_info;
1216 frag_info.VerifyAndAllocateFragmentationHeader(1);
1217 frag_info.fragmentationOffset[part_idx] = 0;
1218 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
1219 frag_info.fragmentationPlType[part_idx] = 0;
1220 frag_info.fragmentationTimeDiff[part_idx] = 0;
1221
1222 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
1223 &frag_info);
1224 encoded_image_._length = 0;
Sergey Silkind902d582018-05-18 17:31:19 +02001225
Sergey Silkin96f2c972018-09-05 21:07:17 +02001226 if (codec_.mode == VideoCodecMode::kScreensharing) {
1227 const uint8_t spatial_idx = encoded_image_.SpatialIndex().value_or(0);
1228 const uint32_t frame_timestamp_ms =
Niels Möller23775882018-08-16 10:24:12 +02001229 1000 * encoded_image_.Timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +02001230 framerate_controller_[spatial_idx].AddFrame(frame_timestamp_ms);
Sergey Silkind902d582018-05-18 17:31:19 +02001231 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001232 }
1233}
1234
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001235int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001236 return WEBRTC_VIDEO_CODEC_OK;
1237}
1238
1239int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1240 EncodedImageCallback* callback) {
1241 encoded_complete_callback_ = callback;
1242 return WEBRTC_VIDEO_CODEC_OK;
1243}
1244
Peter Boströmb7d9a972015-12-18 16:01:11 +01001245const char* VP9EncoderImpl::ImplementationName() const {
1246 return "libvpx";
1247}
1248
Magnus Jedvert46a27652017-11-13 14:10:02 +01001249std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001250 return absl::make_unique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001251}
1252
1253VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001254 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001255 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001256 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001257 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001258
1259VP9DecoderImpl::~VP9DecoderImpl() {
1260 inited_ = true; // in order to do the actual release
1261 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001262 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1263 if (num_buffers_in_use > 0) {
1264 // The frame buffers are reference counted and frames are exposed after
1265 // decoding. There may be valid usage cases where previous frames are still
1266 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001267 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1268 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001269 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001270}
1271
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001272int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001273 int ret_val = Release();
1274 if (ret_val < 0) {
1275 return ret_val;
1276 }
Sergey Silkinb674cd12018-10-09 10:59:06 +02001277
sprang3958ed82017-08-17 08:12:10 -07001278 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001279 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001280 }
philipelcce46fc2015-12-21 03:04:49 -08001281 vpx_codec_dec_cfg_t cfg;
Sergey Silkinb674cd12018-10-09 10:59:06 +02001282 memset(&cfg, 0, sizeof(cfg));
1283
1284 // We want to use multithreading when decoding high resolution videos. But,
1285 // since we don't know resolution of input stream at this stage, we always
1286 // enable it.
1287 cfg.threads = std::min(number_of_cores, kMaxNumTiles4kVideo);
1288
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001289 vpx_codec_flags_t flags = 0;
1290 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1291 return WEBRTC_VIDEO_CODEC_MEMORY;
1292 }
Henrik Boström9695d852015-05-06 10:42:15 +02001293
1294 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1295 return WEBRTC_VIDEO_CODEC_MEMORY;
1296 }
1297
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001298 inited_ = true;
1299 // Always start with a complete key frame.
1300 key_frame_required_ = true;
1301 return WEBRTC_VIDEO_CODEC_OK;
1302}
1303
1304int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1305 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001306 const CodecSpecificInfo* codec_specific_info,
1307 int64_t /*render_time_ms*/) {
1308 if (!inited_) {
1309 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1310 }
sprang3958ed82017-08-17 08:12:10 -07001311 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001312 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1313 }
1314 // Always start with a complete key frame.
1315 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +02001316 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001317 return WEBRTC_VIDEO_CODEC_ERROR;
1318 // We have a key frame - is it complete?
1319 if (input_image._completeFrame) {
1320 key_frame_required_ = false;
1321 } else {
1322 return WEBRTC_VIDEO_CODEC_ERROR;
1323 }
1324 }
sprang3958ed82017-08-17 08:12:10 -07001325 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001326 vpx_image_t* img;
1327 uint8_t* buffer = input_image._buffer;
1328 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -07001329 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001330 }
Henrik Boström9695d852015-05-06 10:42:15 +02001331 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1332 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001333 if (vpx_codec_decode(decoder_, buffer,
1334 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001335 VPX_DL_REALTIME)) {
1336 return WEBRTC_VIDEO_CODEC_ERROR;
1337 }
Henrik Boström9695d852015-05-06 10:42:15 +02001338 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1339 // It may be released by libvpx during future vpx_codec_decode or
1340 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001341 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001342 int qp;
1343 vpx_codec_err_t vpx_ret =
1344 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1345 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
1346 int ret =
Niels Möller23775882018-08-16 10:24:12 +02001347 ReturnFrame(img, input_image.Timestamp(), input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001348 if (ret != 0) {
1349 return ret;
1350 }
1351 return WEBRTC_VIDEO_CODEC_OK;
1352}
1353
asapersson1490f7a2016-09-23 02:09:46 -07001354int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
1355 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -08001356 int64_t ntp_time_ms,
1357 int qp) {
sprang3958ed82017-08-17 08:12:10 -07001358 if (img == nullptr) {
1359 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001360 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1361 }
Henrik Boström9695d852015-05-06 10:42:15 +02001362
1363 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001364 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001365 // vpx_codec_decode calls or vpx_codec_destroy).
1366 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1367 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001368
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001369 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001370 // using a Wrapped*Buffer.
1371 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1372 switch (img->bit_depth) {
1373 case 8:
1374 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001375 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1376 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1377 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1378 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001379 // WrappedI420Buffer's mechanism for allowing the release of its frame
1380 // buffer is through a callback function. This is where we should
1381 // release |img_buffer|.
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001382 rtc::KeepRefUntilDone(img_buffer));
1383 break;
1384 case 10:
1385 img_wrapped_buffer = WrapI010Buffer(
1386 img->d_w, img->d_h,
1387 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1388 img->stride[VPX_PLANE_Y] / 2,
1389 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1390 img->stride[VPX_PLANE_U] / 2,
1391 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1392 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1393 break;
1394 default:
1395 RTC_NOTREACHED();
1396 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1397 }
nisseca6d5d12016-06-17 05:03:04 -07001398
Emircan Uysaler715cc232018-07-23 17:50:43 -07001399 VideoFrame decoded_image = VideoFrame::Builder()
1400 .set_video_frame_buffer(img_wrapped_buffer)
1401 .set_timestamp_ms(0)
1402 .set_timestamp_rtp(timestamp)
1403 .set_ntp_time_ms(ntp_time_ms)
1404 .set_rotation(webrtc::kVideoRotation_0)
1405 .set_color_space(ExtractVP9ColorSpace(
1406 img->cs, img->range, img->bit_depth))
1407 .build();
Danil Chapovalov0040b662018-06-18 10:48:16 +02001408 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001409 return WEBRTC_VIDEO_CODEC_OK;
1410}
1411
1412int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1413 DecodedImageCallback* callback) {
1414 decode_complete_callback_ = callback;
1415 return WEBRTC_VIDEO_CODEC_OK;
1416}
1417
1418int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001419 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1420
sprang3958ed82017-08-17 08:12:10 -07001421 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001422 if (inited_) {
1423 // When a codec is destroyed libvpx will release any buffers of
1424 // |frame_buffer_pool_| it is currently using.
1425 if (vpx_codec_destroy(decoder_)) {
1426 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1427 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001428 }
1429 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001430 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001431 }
Henrik Boström9695d852015-05-06 10:42:15 +02001432 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1433 // still referenced externally are deleted once fully released, not returning
1434 // to the pool.
1435 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001436 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001437 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001438}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001439
1440const char* VP9DecoderImpl::ImplementationName() const {
1441 return "libvpx";
1442}
1443
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001444} // namespace webrtc