blob: 50aea4831aa8d895d178bdbf2bde0823c35e0264 [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 Nikolaevskiy5546aef2018-12-04 15:54:52 +010050// Maximum allowed PID difference for variable frame-rate mode.
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),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200176 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000177 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -0800178 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000179}
180
181VP9EncoderImpl::~VP9EncoderImpl() {
182 Release();
183}
184
185int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100186 int ret_val = WEBRTC_VIDEO_CODEC_OK;
187
Niels Möllerdd1cc982019-02-07 18:52:50 +0100188 encoded_image_.Allocate(0);
sprang3958ed82017-08-17 08:12:10 -0700189 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100190 if (inited_) {
191 if (vpx_codec_destroy(encoder_)) {
192 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
193 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000194 }
195 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700196 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000197 }
sprang3958ed82017-08-17 08:12:10 -0700198 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000199 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700200 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000201 }
sprang3958ed82017-08-17 08:12:10 -0700202 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000203 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700204 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000205 }
206 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100207 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000208}
209
sprangce4aef12015-11-02 07:23:20 -0800210bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
211 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
212 // (i.e. bitrates) were explicitly configured.
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200213 return codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800214}
215
Erik Språng566124a2018-04-23 12:32:22 +0200216bool VP9EncoderImpl::SetSvcRates(
217 const VideoBitrateAllocation& bitrate_allocation) {
Sergey Silkin86684962018-03-28 19:32:37 +0200218 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200219
sprangce4aef12015-11-02 07:23:20 -0800220 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200221 const bool layer_activation_requires_key_frame =
222 inter_layer_pred_ == InterLayerPredMode::kOff ||
223 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic;
224
Sergey Silkin86684962018-03-28 19:32:37 +0200225 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200226 const bool was_layer_active = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200227 config_->ss_target_bitrate[sl_idx] =
228 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
229
230 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
231 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
232 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
233 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200234
Sergey Silkine7ce8882018-10-03 18:04:57 +0200235 const bool is_active_layer = (config_->ss_target_bitrate[sl_idx] > 0);
236 if (!was_layer_active && is_active_layer &&
237 layer_activation_requires_key_frame) {
238 force_key_frame_ = true;
239 } else if (was_layer_active && !is_active_layer &&
240 layer_deactivation_requires_key_frame_) {
241 force_key_frame_ = true;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200242 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200243
Sergey Silkine7ce8882018-10-03 18:04:57 +0200244 if (!was_layer_active) {
Sergey Silkin96f2c972018-09-05 21:07:17 +0200245 // Reset frame rate controller if layer is resumed after pause.
246 framerate_controller_[sl_idx].Reset();
247 }
248
249 framerate_controller_[sl_idx].SetTargetRate(
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200250 std::min(static_cast<float>(codec_.maxFramerate),
251 codec_.spatialLayers[sl_idx].maxFramerate));
sprangce4aef12015-11-02 07:23:20 -0800252 }
253 } else {
254 float rate_ratio[VPX_MAX_LAYERS] = {0};
255 float total = 0;
Sergey Silkin908689d2018-08-20 09:28:45 +0200256 for (int i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800257 if (svc_params_.scaling_factor_num[i] <= 0 ||
258 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100259 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800260 return false;
261 }
Yves Gerey665174f2018-06-19 15:03:05 +0200262 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
263 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800264 total += rate_ratio[i];
265 }
266
Sergey Silkin908689d2018-08-20 09:28:45 +0200267 for (int i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200268 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800269 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
270 config_->rc_target_bitrate * rate_ratio[i] / total);
271 if (num_temporal_layers_ == 1) {
272 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
273 } else if (num_temporal_layers_ == 2) {
274 config_->layer_target_bitrate[i * num_temporal_layers_] =
275 config_->ss_target_bitrate[i] * 2 / 3;
276 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
277 config_->ss_target_bitrate[i];
278 } else if (num_temporal_layers_ == 3) {
279 config_->layer_target_bitrate[i * num_temporal_layers_] =
280 config_->ss_target_bitrate[i] / 2;
281 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
282 config_->layer_target_bitrate[i * num_temporal_layers_] +
283 (config_->ss_target_bitrate[i] / 4);
284 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
285 config_->ss_target_bitrate[i];
286 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100287 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
288 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800289 return false;
290 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200291
292 framerate_controller_[i].SetTargetRate(codec_.maxFramerate);
asaperssona9455ab2015-07-31 06:10:09 -0700293 }
294 }
Sergey Silkin908689d2018-08-20 09:28:45 +0200295
296 num_active_spatial_layers_ = 0;
297 for (int i = 0; i < num_spatial_layers_; ++i) {
298 if (config_->ss_target_bitrate[i] > 0) {
299 ++num_active_spatial_layers_;
300 }
301 }
302 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
303
asaperssona9455ab2015-07-31 06:10:09 -0700304 return true;
305}
306
Erik Språng08127a92016-11-16 16:41:30 +0100307int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200308 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100309 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000310 if (!inited_) {
311 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
312 }
313 if (encoder_->err) {
314 return WEBRTC_VIDEO_CODEC_ERROR;
315 }
Erik Språng08127a92016-11-16 16:41:30 +0100316 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000317 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
318 }
319 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100320 if (codec_.maxBitrate > 0 &&
321 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
322 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000323 }
Erik Språng08127a92016-11-16 16:41:30 +0100324
Erik Språng08127a92016-11-16 16:41:30 +0100325 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700326
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100327 requested_bitrate_allocation_ = bitrate_allocation;
asaperssona9455ab2015-07-31 06:10:09 -0700328
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000329 return WEBRTC_VIDEO_CODEC_OK;
330}
331
332int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
333 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000334 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700335 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000336 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
337 }
338 if (inst->maxFramerate < 1) {
339 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
340 }
341 // Allow zero to represent an unspecified maxBitRate
342 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
343 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
344 }
345 if (inst->width < 1 || inst->height < 1) {
346 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
347 }
348 if (number_of_cores < 1) {
349 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
350 }
hta257dc392016-10-25 09:05:06 -0700351 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700352 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
353 }
ilnik2a8c2f52017-02-15 02:23:28 -0800354 // libvpx probably does not support more than 3 spatial layers.
355 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700356 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
357 }
philipelcfc319b2015-11-10 07:17:23 -0800358
asapersson86956de2016-01-26 01:05:20 -0800359 int ret_val = Release();
360 if (ret_val < 0) {
361 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000362 }
sprang3958ed82017-08-17 08:12:10 -0700363 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000364 encoder_ = new vpx_codec_ctx_t;
365 }
sprang3958ed82017-08-17 08:12:10 -0700366 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000367 config_ = new vpx_codec_enc_cfg_t;
368 }
369 timestamp_ = 0;
370 if (&codec_ != inst) {
371 codec_ = *inst;
372 }
asaperssona9455ab2015-07-31 06:10:09 -0700373
Sergey Silkinb0bd03b2018-09-28 14:56:39 +0200374 force_key_frame_ = true;
375 pics_since_key_ = 0;
376
hta257dc392016-10-25 09:05:06 -0700377 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200378 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700379 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200380 if (num_temporal_layers_ == 0) {
asaperssona9455ab2015-07-31 06:10:09 -0700381 num_temporal_layers_ = 1;
Sergey Silkin042661b2018-09-10 10:39:35 +0000382 }
Sergey Silkinae9e1882018-09-05 21:07:17 +0200383
Sergey Silkin96f2c972018-09-05 21:07:17 +0200384 framerate_controller_ = std::vector<FramerateController>(
385 num_spatial_layers_, FramerateController(codec_.maxFramerate));
386
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200387 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200388
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000389 // Allocate memory for encoded image
Niels Möller48a79462018-12-07 16:21:18 +0100390 size_t frame_capacity =
nisseeb44b392017-04-28 07:18:05 -0700391 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
Niels Möllerdd1cc982019-02-07 18:52:50 +0100392 encoded_image_.Allocate(frame_capacity);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000393 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000394 // Populate encoder configuration with default values.
395 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
396 return WEBRTC_VIDEO_CODEC_ERROR;
397 }
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700398
399 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
400 unsigned int bits_for_storage = 8;
401 switch (profile_) {
402 case VP9Profile::kProfile0:
403 img_fmt = VPX_IMG_FMT_I420;
404 bits_for_storage = 8;
405 config_->g_bit_depth = VPX_BITS_8;
406 config_->g_profile = 0;
407 config_->g_input_bit_depth = 8;
408 break;
409 case VP9Profile::kProfile2:
410 img_fmt = VPX_IMG_FMT_I42016;
411 bits_for_storage = 16;
412 config_->g_bit_depth = VPX_BITS_10;
413 config_->g_profile = 2;
414 config_->g_input_bit_depth = 10;
415 break;
416 }
417
418 // Creating a wrapper to the image - setting image data to nullptr. Actual
419 // pointer will be set in encode. Setting align to 1, as it is meaningless
420 // (actual memory is not allocated).
421 raw_ =
422 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
423 raw_->bit_depth = bits_for_storage;
424
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000425 config_->g_w = codec_.width;
426 config_->g_h = codec_.height;
427 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200428 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000429 // Setting the time base of the codec.
430 config_->g_timebase.num = 1;
431 config_->g_timebase.den = 90000;
432 config_->g_lag_in_frames = 0; // 0- no frame lagging
433 config_->g_threads = 1;
434 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700435 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000436 config_->rc_end_usage = VPX_CBR;
437 config_->g_pass = VPX_RC_ONE_PASS;
Ilya Nikolaevskiy3a656d12019-02-14 14:44:22 +0100438 config_->rc_min_quantizer =
439 codec_.mode == VideoCodecMode::kScreensharing ? 8 : 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000440 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000441 config_->rc_undershoot_pct = 50;
442 config_->rc_overshoot_pct = 50;
443 config_->rc_buf_initial_sz = 500;
444 config_->rc_buf_optimal_sz = 600;
445 config_->rc_buf_sz = 1000;
446 // Set the maximum target size of any key-frame.
447 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100448 // Key-frame interval is enforced manually by this wrapper.
449 config_->kf_mode = VPX_KF_DISABLED;
450 // TODO(webm:1592): work-around for libvpx issue, as it can still
451 // put some key-frames at will even in VPX_KF_DISABLED kf_mode.
452 config_->kf_max_dist = inst->VP9().keyFrameInterval;
453 config_->kf_min_dist = config_->kf_max_dist;
hta257dc392016-10-25 09:05:06 -0700454 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000455 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800456 config_->g_threads =
457 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700458
Marco6e89b252015-07-07 14:40:38 -0700459 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700460
hta257dc392016-10-25 09:05:06 -0700461 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200462
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100463 inter_layer_pred_ = inst->VP9().interLayerPred;
464
465 different_framerates_used_ = false;
466 for (size_t sl_idx = 1; sl_idx < num_spatial_layers_; ++sl_idx) {
467 if (std::abs(codec_.spatialLayers[sl_idx].maxFramerate -
468 codec_.spatialLayers[0].maxFramerate) > 1e-9) {
469 different_framerates_used_ = true;
470 }
471 }
472
473 if (different_framerates_used_ && !is_flexible_mode_) {
474 RTC_LOG(LS_ERROR) << "Flexible mode required for different framerates on "
475 "different spatial layers";
476 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
477 }
478
479 // External reference control is required for different frame rate on spatial
480 // layers because libvpx generates rtp incompatible references in this case.
481 external_ref_control_ = field_trial::IsEnabled("WebRTC-Vp9ExternalRefCtrl") ||
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100482 different_framerates_used_ ||
483 inter_layer_pred_ == InterLayerPredMode::kOn;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100484
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200485 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700486 gof_.SetGofInfoVP9(kTemporalStructureMode1);
487 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
488 config_->ts_number_layers = 1;
489 config_->ts_rate_decimator[0] = 1;
490 config_->ts_periodicity = 1;
491 config_->ts_layer_id[0] = 0;
492 } else if (num_temporal_layers_ == 2) {
493 gof_.SetGofInfoVP9(kTemporalStructureMode2);
494 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
495 config_->ts_number_layers = 2;
496 config_->ts_rate_decimator[0] = 2;
497 config_->ts_rate_decimator[1] = 1;
498 config_->ts_periodicity = 2;
499 config_->ts_layer_id[0] = 0;
500 config_->ts_layer_id[1] = 1;
501 } else if (num_temporal_layers_ == 3) {
502 gof_.SetGofInfoVP9(kTemporalStructureMode3);
503 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
504 config_->ts_number_layers = 3;
505 config_->ts_rate_decimator[0] = 4;
506 config_->ts_rate_decimator[1] = 2;
507 config_->ts_rate_decimator[2] = 1;
508 config_->ts_periodicity = 4;
509 config_->ts_layer_id[0] = 0;
510 config_->ts_layer_id[1] = 2;
511 config_->ts_layer_id[2] = 1;
512 config_->ts_layer_id[3] = 2;
513 } else {
514 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
515 }
516
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100517 if (external_ref_control_) {
518 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
519 if (num_temporal_layers_ > 1 && different_framerates_used_) {
520 // External reference control for several temporal layers with different
521 // frame rates on spatial layers is not implemented yet.
522 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
523 }
524 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200525 ref_buf_.clear();
526
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000527 return InitAndSetControlSettings(inst);
528}
529
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000530int VP9EncoderImpl::NumberOfThreads(int width,
531 int height,
532 int number_of_cores) {
533 // Keep the number of encoder threads equal to the possible number of column
534 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
535 if (width * height >= 1280 * 720 && number_of_cores > 4) {
536 return 4;
jianj23173a32017-07-12 16:11:09 -0700537 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000538 return 2;
539 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200540// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800541#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
542 defined(WEBRTC_ANDROID)
543 if (width * height >= 320 * 180 && number_of_cores > 2) {
544 return 2;
545 }
546#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000547 // 1 thread less than VGA.
548 return 1;
549 }
550}
551
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000552int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100553 // Set QP-min/max per spatial and temporal layer.
554 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
555 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800556 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
557 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100558 }
asaperssona9455ab2015-07-31 06:10:09 -0700559 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800560 if (ExplicitlyConfiguredSpatialLayers()) {
561 for (int i = 0; i < num_spatial_layers_; ++i) {
562 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200563 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100564 const int scale_factor = codec_.width / layer.width;
565 RTC_DCHECK_GT(scale_factor, 0);
566
567 // Ensure scaler factor is integer.
568 if (scale_factor * layer.width != codec_.width) {
569 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
570 }
571
572 // Ensure scale factor is the same in both dimensions.
573 if (scale_factor * layer.height != codec_.height) {
574 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
575 }
576
577 // Ensure scale factor is power of two.
578 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
579 if (!is_pow_of_two) {
580 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
581 }
582
583 svc_params_.scaling_factor_num[i] = 1;
584 svc_params_.scaling_factor_den[i] = scale_factor;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200585
586 RTC_DCHECK_GT(codec_.spatialLayers[i].maxFramerate, 0);
587 RTC_DCHECK_LE(codec_.spatialLayers[i].maxFramerate, codec_.maxFramerate);
588 if (i > 0) {
589 // Frame rate of high spatial layer is supposed to be equal or higher
590 // than frame rate of low spatial layer.
591 RTC_DCHECK_GE(codec_.spatialLayers[i].maxFramerate,
592 codec_.spatialLayers[i - 1].maxFramerate);
593 }
sprangce4aef12015-11-02 07:23:20 -0800594 }
595 } else {
596 int scaling_factor_num = 256;
597 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800598 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800599 svc_params_.scaling_factor_num[i] = scaling_factor_num;
600 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800601 }
asaperssona9455ab2015-07-31 06:10:09 -0700602 }
603
Sergey Silkin86684962018-03-28 19:32:37 +0200604 SvcRateAllocator init_allocator(codec_);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100605 current_bitrate_allocation_ = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200606 inst->startBitrate * 1000, inst->maxFramerate);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100607 if (!SetSvcRates(current_bitrate_allocation_)) {
asaperssona9455ab2015-07-31 06:10:09 -0700608 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
609 }
610
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700611 const vpx_codec_err_t rv = vpx_codec_enc_init(
612 encoder_, vpx_codec_vp9_cx(), config_,
613 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
614 if (rv != VPX_CODEC_OK) {
615 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000616 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
617 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000618 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
619 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
620 rc_max_intra_target_);
621 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700622 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700623
jianj822e5932017-07-12 16:09:58 -0700624 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100625 vpx_codec_control(encoder_, VP9E_SET_SVC_GF_TEMPORAL_REF, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200626
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200627 if (is_svc_) {
628 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
629 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700630 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200631
632 if (num_spatial_layers_ > 1) {
633 switch (inter_layer_pred_) {
634 case InterLayerPredMode::kOn:
635 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
636 break;
637 case InterLayerPredMode::kOff:
638 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
639 break;
640 case InterLayerPredMode::kOnKeyPic:
641 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
642 break;
643 default:
644 RTC_NOTREACHED();
645 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200646
Sergey Silkinee203362018-05-30 11:34:08 +0200647 // Configure encoder to drop entire superframe whenever it needs to drop
648 // a layer. This mode is prefered over per-layer dropping which causes
649 // quality flickering and is not compatible with RTP non-flexible mode.
650 vpx_svc_frame_drop_t svc_drop_frame;
651 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100652 svc_drop_frame.framedrop_mode =
653 full_superframe_drop_ ? FULL_SUPERFRAME_DROP : CONSTRAINED_LAYER_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200654 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200655 for (size_t i = 0; i < num_spatial_layers_; ++i) {
656 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200657 }
Sergey Silkinee203362018-05-30 11:34:08 +0200658 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200659 }
660
asaperssona9455ab2015-07-31 06:10:09 -0700661 // Register callback for getting each spatial layer.
662 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800663 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
664 reinterpret_cast<void*>(this)};
665 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
666 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700667
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000668 // Control function to set the number of column tiles in encoding a frame, in
669 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
670 // The number tile columns will be capped by the encoder based on image size
671 // (minimum width of tile column is 256 pixels, maximum is 4096).
672 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700673
674 // Turn on row-based multithreading.
675 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700676
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700677#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200678 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700679 // Do not enable the denoiser on ARM since optimization is pending.
680 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000681 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700682 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000683#endif
jianj6bf57e32017-06-05 13:43:49 -0700684
Niels Möllere3cf3d02018-06-13 11:52:16 +0200685 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700686 // Adjust internal parameters to screen content.
687 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700688 }
Marco2520e722015-09-16 14:05:00 -0700689 // Enable encoder skip of static/low content blocks.
690 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000691 inited_ = true;
692 return WEBRTC_VIDEO_CODEC_OK;
693}
694
695uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
696 // Set max to the optimal buffer level (normalized by target BR),
697 // and scaled by a scale_par.
698 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
699 // This value is presented in percentage of perFrameBw:
700 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
701 // The target in % is as follows:
702 float scale_par = 0.5;
703 uint32_t target_pct =
704 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
705 // Don't go below 3 times the per frame bandwidth.
706 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800707 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000708}
709
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700710int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000711 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700712 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000713 if (!inited_) {
714 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
715 }
sprang3958ed82017-08-17 08:12:10 -0700716 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000717 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
718 }
Erik Språngbfa5d5d2019-02-04 16:40:19 +0100719 if (num_active_spatial_layers_ == 0) {
720 // All spatial layers are disabled, return without encoding anything.
721 return WEBRTC_VIDEO_CODEC_OK;
722 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200723
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000724 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200725 if (frame_types && !frame_types->empty()) {
726 if ((*frame_types)[0] == kVideoFrameKey) {
727 force_key_frame_ = true;
728 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000729 }
Sergey Silkind902d582018-05-18 17:31:19 +0200730
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100731 if (pics_since_key_ + 1 ==
732 static_cast<size_t>(codec_.VP9()->keyFrameInterval)) {
733 force_key_frame_ = true;
734 }
735
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100736 vpx_svc_layer_id_t layer_id = {0};
737 if (!force_key_frame_) {
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000738 const size_t gof_idx = (pics_since_key_ + 1) % gof_.num_frames_in_gof;
739 layer_id.temporal_layer_id = gof_.temporal_idx[gof_idx];
Sergey Silkin96f2c972018-09-05 21:07:17 +0200740
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100741 if (VideoCodecMode::kScreensharing == codec_.mode) {
742 const uint32_t frame_timestamp_ms =
743 1000 * input_image.timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200744
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100745 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
746 if (framerate_controller_[sl_idx].DropFrame(frame_timestamp_ms)) {
747 ++layer_id.spatial_layer_id;
748 } else {
749 break;
750 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200751 }
752 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000753
754 RTC_DCHECK_LE(layer_id.spatial_layer_id, num_active_spatial_layers_);
755 if (layer_id.spatial_layer_id >= num_active_spatial_layers_) {
756 // Drop entire picture.
757 return WEBRTC_VIDEO_CODEC_OK;
758 }
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100759 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000760
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100761 for (int sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
762 layer_id.temporal_layer_id_per_spatial[sl_idx] = layer_id.temporal_layer_id;
763 }
764
765 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
766
767 if (requested_bitrate_allocation_) {
768 bool more_layers_requested = MoreLayersEnabled(
769 *requested_bitrate_allocation_, current_bitrate_allocation_);
770 bool less_layers_requested = MoreLayersEnabled(
771 current_bitrate_allocation_, *requested_bitrate_allocation_);
772 // In SVC can enable new layers only if all lower layers are encoded and at
773 // the base temporal layer.
774 // This will delay rate allocation change until the next frame on the base
775 // spatial layer.
776 // In KSVC or simulcast modes KF will be generated for a new layer, so can
777 // update allocation any time.
778 bool can_upswitch =
779 inter_layer_pred_ != InterLayerPredMode::kOn ||
780 (layer_id.spatial_layer_id == 0 && layer_id.temporal_layer_id == 0);
781 if (!more_layers_requested || can_upswitch) {
782 current_bitrate_allocation_ = *requested_bitrate_allocation_;
783 requested_bitrate_allocation_ = absl::nullopt;
784 if (!SetSvcRates(current_bitrate_allocation_)) {
785 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
786 }
787 if (less_layers_requested || more_layers_requested) {
788 ss_info_needed_ = true;
789 }
790 }
791 }
792
793 if (vpx_codec_enc_config_set(encoder_, config_)) {
794 return WEBRTC_VIDEO_CODEC_ERROR;
Sergey Silkind902d582018-05-18 17:31:19 +0200795 }
796
kwiberg352444f2016-11-28 15:58:53 -0800797 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
798 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700799
800 // Set input image for use in the callback.
801 // This was necessary since you need some information from input_image.
802 // You can save only the necessary information (such as timestamp) instead of
803 // doing this.
804 input_image_ = &input_image;
805
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700806 // Keep reference to buffer until encode completes.
807 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
808 rtc::scoped_refptr<I010BufferInterface> i010_buffer;
809 switch (profile_) {
810 case VP9Profile::kProfile0: {
811 i420_buffer = input_image.video_frame_buffer()->ToI420();
812 // Image in vpx_image_t format.
813 // Input image is const. VPX's raw image is not defined as const.
814 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
815 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
816 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
817 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
818 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
819 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
820 break;
821 }
822 case VP9Profile::kProfile2: {
823 // We can inject kI010 frames directly for encode. All other formats
824 // should be converted to it.
825 switch (input_image.video_frame_buffer()->type()) {
826 case VideoFrameBuffer::Type::kI010: {
827 i010_buffer = input_image.video_frame_buffer()->GetI010();
828 break;
829 }
830 default: {
831 i010_buffer =
832 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
833 }
834 }
835 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
836 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
837 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
838 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
839 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
840 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
841 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
842 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
843 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
844 break;
845 }
846 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000847
philipelcfc319b2015-11-10 07:17:23 -0800848 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200849 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000850 flags = VPX_EFLAG_FORCE_KF;
851 }
philipelcfc319b2015-11-10 07:17:23 -0800852
Sergey Silkin390f3582018-10-01 17:13:50 +0200853 if (external_ref_control_) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100854 vpx_svc_ref_frame_config_t ref_config =
855 SetReferences(force_key_frame_, layer_id.spatial_layer_id);
Sergey Silkina85995a2018-10-02 10:28:10 +0200856
857 if (VideoCodecMode::kScreensharing == codec_.mode) {
858 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
859 ref_config.duration[sl_idx] = static_cast<int64_t>(
860 90000 / framerate_controller_[sl_idx].GetTargetRate());
861 }
862 }
863
Sergey Silkin390f3582018-10-01 17:13:50 +0200864 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &ref_config);
865 }
866
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100867 first_frame_in_picture_ = true;
868
Sergey Silkin96f2c972018-09-05 21:07:17 +0200869 // TODO(ssilkin): Frame duration should be specified per spatial layer
870 // since their frame rate can be different. For now calculate frame duration
871 // based on target frame rate of the highest spatial layer, which frame rate
872 // is supposed to be equal or higher than frame rate of low spatial layers.
873 // Also, timestamp should represent actual time passed since previous frame
874 // (not 'expected' time). Then rate controller can drain buffer more
875 // accurately.
876 RTC_DCHECK_GE(framerate_controller_.size(), num_active_spatial_layers_);
Sergey Silkinf87bb462018-09-17 09:37:37 +0200877 float target_framerate_fps =
878 (codec_.mode == VideoCodecMode::kScreensharing)
879 ? framerate_controller_[num_active_spatial_layers_ - 1]
880 .GetTargetRate()
881 : codec_.maxFramerate;
882 uint32_t duration = static_cast<uint32_t>(90000 / target_framerate_fps);
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700883 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
884 duration, flags, VPX_DL_REALTIME);
885 if (rv != VPX_CODEC_OK) {
886 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
887 << "\n"
888 << "Details: " << vpx_codec_error(encoder_) << "\n"
889 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000890 return WEBRTC_VIDEO_CODEC_ERROR;
891 }
892 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700893
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100894 if (!full_superframe_drop_) {
895 const bool end_of_picture = true;
896 DeliverBufferedFrame(end_of_picture);
897 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200898
asaperssona9455ab2015-07-31 06:10:09 -0700899 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000900}
901
902void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
Niels Möllerd3b8c632018-08-27 15:33:42 +0200903 absl::optional<int>* spatial_idx,
philipelcce46fc2015-12-21 03:04:49 -0800904 const vpx_codec_cx_pkt& pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100905 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -0700906 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000907 codec_specific->codecType = kVideoCodecVP9;
philipelcce46fc2015-12-21 03:04:49 -0800908 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200909
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100910 vp9_info->first_frame_in_picture = first_frame_in_picture_;
Sergey Silkin738b7e92018-08-23 16:37:27 +0200911 vp9_info->flexible_mode = is_flexible_mode_;
hta257dc392016-10-25 09:05:06 -0700912 vp9_info->ss_data_available =
Sergey Silkin738b7e92018-08-23 16:37:27 +0200913 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
asaperssona9455ab2015-07-31 06:10:09 -0700914
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100915 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
916 pics_since_key_ = 0;
917 } else if (first_frame_in_picture_) {
918 ++pics_since_key_;
919 }
920
asaperssona9455ab2015-07-31 06:10:09 -0700921 vpx_svc_layer_id_t layer_id = {0};
922 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
923
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100924 // Can't have keyframe with non-zero temporal layer.
925 RTC_DCHECK(pics_since_key_ != 0 || layer_id.temporal_layer_id == 0);
926
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100927 if (ss_info_needed_ && layer_id.temporal_layer_id == 0 &&
928 layer_id.spatial_layer_id == 0) {
929 // Force SS info after the layers configuration has changed.
930 vp9_info->ss_data_available = true;
931 ss_info_needed_ = false;
932 }
933
sprang3958ed82017-08-17 08:12:10 -0700934 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -0500935 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700936 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700937 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700938 vp9_info->temporal_idx = kNoTemporalIdx;
939 } else {
940 vp9_info->temporal_idx = layer_id.temporal_layer_id;
941 }
“Michael23c5a992018-06-21 11:07:21 -0500942 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700943 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
Niels Möllerd3b8c632018-08-27 15:33:42 +0200944 *spatial_idx = absl::nullopt;
asaperssona9455ab2015-07-31 06:10:09 -0700945 } else {
Niels Möllerd3b8c632018-08-27 15:33:42 +0200946 *spatial_idx = layer_id.spatial_layer_id;
asaperssona9455ab2015-07-31 06:10:09 -0700947 }
948 if (layer_id.spatial_layer_id != 0) {
949 vp9_info->ss_data_available = false;
950 }
951
asaperssona9455ab2015-07-31 06:10:09 -0700952 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800953 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700954
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200955 const bool is_key_pic = (pics_since_key_ == 0);
956 const bool is_inter_layer_pred_allowed =
957 (inter_layer_pred_ == InterLayerPredMode::kOn ||
958 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
959
960 // Always set inter_layer_predicted to true on high layer frame if inter-layer
961 // prediction (ILP) is allowed even if encoder didn't actually use it.
962 // Setting inter_layer_predicted to false would allow receiver to decode high
963 // layer frame without decoding low layer frame. If that would happen (e.g.
964 // if low layer frame is lost) then receiver won't be able to decode next high
965 // layer frame which uses ILP.
966 vp9_info->inter_layer_predicted =
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100967 first_frame_in_picture_ ? false : is_inter_layer_pred_allowed;
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200968
Sergey Silkinc5f152d2018-09-26 13:28:50 +0200969 // Mark all low spatial layer frames as references (not just frames of
970 // active low spatial layers) if inter-layer prediction is enabled since
971 // these frames are indirect references of high spatial layer, which can
972 // later be enabled without key frame.
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200973 vp9_info->non_ref_for_inter_layer_pred =
Sergey Silkinc5f152d2018-09-26 13:28:50 +0200974 !is_inter_layer_pred_allowed ||
975 layer_id.spatial_layer_id + 1 == num_spatial_layers_;
asapersson00ac85e2015-11-11 05:30:48 -0800976
ivica7f6a6fc2015-09-08 02:40:29 -0700977 // Always populate this, so that the packetizer can properly set the marker
978 // bit.
“Michael23c5a992018-06-21 11:07:21 -0500979 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800980
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200981 vp9_info->num_ref_pics = 0;
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100982 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
983 vp9_info);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200984 if (vp9_info->flexible_mode) {
985 vp9_info->gof_idx = kNoGofIdx;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200986 } else {
987 vp9_info->gof_idx =
988 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
989 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100990 RTC_DCHECK(vp9_info->num_ref_pics == gof_.num_ref_pics[vp9_info->gof_idx] ||
991 vp9_info->num_ref_pics == 0);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200992 }
993
994 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
995
asaperssona9455ab2015-07-31 06:10:09 -0700996 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700997 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -0500998 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +0200999 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -08001000 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +02001001 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -08001002 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -07001003 }
Sergey Silkin738b7e92018-08-23 16:37:27 +02001004 if (vp9_info->flexible_mode) {
1005 vp9_info->gof.num_frames_in_gof = 0;
1006 } else {
asaperssona9455ab2015-07-31 06:10:09 -07001007 vp9_info->gof.CopyGofInfoVP9(gof_);
1008 }
1009 }
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001010
1011 first_frame_in_picture_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001012}
1013
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001014void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
1015 const size_t pic_num,
1016 const bool inter_layer_predicted,
1017 CodecSpecificInfoVP9* vp9_info) {
1018 vpx_svc_layer_id_t layer_id = {0};
1019 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1020
Sergey Silkin76be2952018-08-21 12:30:33 +02001021 const bool is_key_frame =
1022 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001023
1024 std::vector<RefFrameBuffer> ref_buf_list;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001025
Sergey Silkin76be2952018-08-21 12:30:33 +02001026 if (is_svc_) {
1027 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1028 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001029
Sergey Silkin76be2952018-08-21 12:30:33 +02001030 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
1031 const size_t fb_idx =
1032 enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
1033 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001034 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1035 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1036 ref_buf_list.push_back(ref_buf_.at(fb_idx));
1037 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001038 }
1039
1040 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
1041 const size_t fb_idx =
1042 enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
1043 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001044 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1045 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1046 ref_buf_list.push_back(ref_buf_.at(fb_idx));
1047 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001048 }
1049
1050 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
1051 const size_t fb_idx =
1052 enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
1053 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001054 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1055 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1056 ref_buf_list.push_back(ref_buf_.at(fb_idx));
1057 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001058 }
1059 } else if (!is_key_frame) {
1060 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1061 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1062 // In non-SVC mode encoder doesn't provide reference list. Assume each frame
1063 // refers previous one, which is stored in buffer 0.
1064 ref_buf_list.push_back(ref_buf_.at(0));
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001065 }
1066
1067 size_t max_ref_temporal_layer_id = 0;
1068
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001069 std::vector<size_t> ref_pid_list;
1070
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001071 vp9_info->num_ref_pics = 0;
1072 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
1073 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
1074 if (ref_buf.pic_num < pic_num) {
1075 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
1076 // RTP spec limits temporal prediction to the same spatial layer.
1077 // It is safe to ignore this requirement if inter-layer prediction is
1078 // enabled for all frames when all base frames are relayed to receiver.
1079 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
1080 }
1081 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
1082
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001083 // Encoder may reference several spatial layers on the same previous
1084 // frame in case if some spatial layers are skipped on the current frame.
1085 // We shouldn't put duplicate references as it may break some old
1086 // clients and isn't RTP compatible.
1087 if (std::find(ref_pid_list.begin(), ref_pid_list.end(),
1088 ref_buf.pic_num) != ref_pid_list.end()) {
1089 continue;
1090 }
1091 ref_pid_list.push_back(ref_buf.pic_num);
1092
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001093 const size_t p_diff = pic_num - ref_buf.pic_num;
1094 RTC_DCHECK_LE(p_diff, 127UL);
1095
1096 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
1097 ++vp9_info->num_ref_pics;
1098
1099 max_ref_temporal_layer_id =
1100 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
1101 } else {
1102 RTC_DCHECK(inter_layer_predicted);
1103 // RTP spec only allows to use previous spatial layer for inter-layer
1104 // prediction.
1105 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
1106 }
1107 }
1108
1109 vp9_info->temporal_up_switch =
1110 (max_ref_temporal_layer_id <
1111 static_cast<size_t>(layer_id.temporal_layer_id));
1112}
1113
1114void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
1115 const size_t pic_num) {
1116 vpx_svc_layer_id_t layer_id = {0};
1117 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1118
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001119 const bool is_key_frame =
1120 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1121
1122 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
1123 layer_id.temporal_layer_id);
1124
1125 if (is_key_frame && layer_id.spatial_layer_id == 0) {
1126 // Key frame updates all ref buffers.
1127 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
1128 ref_buf_[i] = frame_buf;
1129 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001130 } else if (is_svc_) {
1131 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1132 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
1133
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001134 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
1135 if (enc_layer_conf.update_buffer_slot[layer_id.spatial_layer_id] &
1136 (1 << i)) {
1137 ref_buf_[i] = frame_buf;
1138 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001139 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001140 } else {
1141 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1142 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1143 // In non-svc mode encoder doesn't provide reference list. Assume each frame
1144 // is reference and stored in buffer 0.
1145 ref_buf_[0] = frame_buf;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001146 }
1147}
1148
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001149vpx_svc_ref_frame_config_t VP9EncoderImpl::SetReferences(
1150 bool is_key_pic,
1151 size_t first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001152 // kRefBufIdx, kUpdBufIdx need to be updated to support longer GOFs.
1153 RTC_DCHECK_LE(gof_.num_frames_in_gof, 4);
1154
1155 vpx_svc_ref_frame_config_t ref_config;
1156 memset(&ref_config, 0, sizeof(ref_config));
1157
1158 const size_t num_temporal_refs = std::max(1, num_temporal_layers_ - 1);
1159 const bool is_inter_layer_pred_allowed =
1160 inter_layer_pred_ == InterLayerPredMode::kOn ||
1161 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic);
1162 absl::optional<int> last_updated_buf_idx;
1163
1164 // Put temporal reference to LAST and spatial reference to GOLDEN. Update
1165 // frame buffer (i.e. store encoded frame) if current frame is a temporal
1166 // reference (i.e. it belongs to a low temporal layer) or it is a spatial
1167 // reference. In later case, always store spatial reference in the last
1168 // reference frame buffer.
1169 // For the case of 3 temporal and 3 spatial layers we need 6 frame buffers
1170 // for temporal references plus 1 buffer for spatial reference. 7 buffers
1171 // in total.
1172
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001173 for (size_t sl_idx = first_active_spatial_layer_id;
1174 sl_idx < num_active_spatial_layers_; ++sl_idx) {
1175 const size_t curr_pic_num = is_key_pic ? 0 : pics_since_key_ + 1;
1176 const size_t gof_idx = curr_pic_num % gof_.num_frames_in_gof;
Sergey Silkin390f3582018-10-01 17:13:50 +02001177
1178 if (!is_key_pic) {
1179 // Set up temporal reference.
1180 const int buf_idx = sl_idx * num_temporal_refs + kRefBufIdx[gof_idx];
1181
1182 // Last reference frame buffer is reserved for spatial reference. It is
1183 // not supposed to be used for temporal prediction.
1184 RTC_DCHECK_LT(buf_idx, kNumVp9Buffers - 1);
1185
1186 // Sanity check that reference picture number is smaller than current
1187 // picture number.
Sergey Silkin390f3582018-10-01 17:13:50 +02001188 RTC_DCHECK_LT(ref_buf_[buf_idx].pic_num, curr_pic_num);
1189 const size_t pid_diff = curr_pic_num - ref_buf_[buf_idx].pic_num;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001190 // Incorrect spatial layer may be in the buffer due to a key-frame.
1191 const bool same_spatial_layer =
1192 ref_buf_[buf_idx].spatial_layer_id == sl_idx;
1193 bool correct_pid = false;
1194 if (different_framerates_used_) {
1195 correct_pid = pid_diff < kMaxAllowedPidDIff;
1196 } else {
1197 // Below code assumes single temporal referecence.
1198 RTC_DCHECK_EQ(gof_.num_ref_pics[gof_idx], 1);
1199 correct_pid = pid_diff == gof_.pid_diff[gof_idx][0];
1200 }
Sergey Silkin390f3582018-10-01 17:13:50 +02001201
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001202 if (same_spatial_layer && correct_pid) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001203 ref_config.lst_fb_idx[sl_idx] = buf_idx;
1204 ref_config.reference_last[sl_idx] = 1;
1205 } else {
1206 // This reference doesn't match with one specified by GOF. This can
1207 // only happen if spatial layer is enabled dynamically without key
1208 // frame. Spatial prediction is supposed to be enabled in this case.
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001209 RTC_DCHECK(is_inter_layer_pred_allowed &&
1210 sl_idx > first_active_spatial_layer_id);
Sergey Silkin390f3582018-10-01 17:13:50 +02001211 }
1212 }
1213
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001214 if (is_inter_layer_pred_allowed && sl_idx > first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001215 // Set up spatial reference.
1216 RTC_DCHECK(last_updated_buf_idx);
1217 ref_config.gld_fb_idx[sl_idx] = *last_updated_buf_idx;
1218 ref_config.reference_golden[sl_idx] = 1;
1219 } else {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001220 RTC_DCHECK(ref_config.reference_last[sl_idx] != 0 ||
1221 sl_idx == first_active_spatial_layer_id ||
Sergey Silkin390f3582018-10-01 17:13:50 +02001222 inter_layer_pred_ == InterLayerPredMode::kOff);
1223 }
1224
1225 last_updated_buf_idx.reset();
1226
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001227 if (gof_.temporal_idx[gof_idx] < num_temporal_layers_ - 1 ||
1228 num_temporal_layers_ == 1) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001229 last_updated_buf_idx = sl_idx * num_temporal_refs + kUpdBufIdx[gof_idx];
1230
1231 // Ensure last frame buffer is not used for temporal prediction (it is
1232 // reserved for spatial reference).
1233 RTC_DCHECK_LT(*last_updated_buf_idx, kNumVp9Buffers - 1);
1234 } else if (is_inter_layer_pred_allowed) {
1235 last_updated_buf_idx = kNumVp9Buffers - 1;
1236 }
1237
1238 if (last_updated_buf_idx) {
1239 ref_config.update_buffer_slot[sl_idx] = 1 << *last_updated_buf_idx;
1240 }
1241 }
1242
1243 return ref_config;
1244}
1245
asaperssona9455ab2015-07-31 06:10:09 -07001246int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -08001247 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -07001248
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001249 if (pkt->data.frame.sz == 0) {
1250 // Ignore dropped frame.
1251 return WEBRTC_VIDEO_CODEC_OK;
1252 }
1253
Sergey Silkin07f80cc2018-04-09 13:11:59 +02001254 vpx_svc_layer_id_t layer_id = {0};
1255 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1256
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001257 if (!full_superframe_drop_) {
1258 // Deliver buffered low spatial layer frame.
1259 const bool end_of_picture = false;
1260 DeliverBufferedFrame(end_of_picture);
1261 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001262
Niels Möller48a79462018-12-07 16:21:18 +01001263 if (pkt->data.frame.sz > encoded_image_.capacity()) {
Niels Möllerdd1cc982019-02-07 18:52:50 +01001264 encoded_image_.Allocate(pkt->data.frame.sz);
asaperssond9f641e2016-01-21 01:11:35 -08001265 }
Niels Möller24871e42019-01-17 11:31:13 +01001266 memcpy(encoded_image_.data(), pkt->data.frame.buf, pkt->data.frame.sz);
Niels Möller77536a22019-01-15 08:50:01 +01001267 encoded_image_.set_size(pkt->data.frame.sz);
asaperssond9f641e2016-01-21 01:11:35 -08001268
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001269 const bool is_key_frame =
1270 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1271 // Ensure encoder issued key frame on request.
1272 RTC_DCHECK(is_key_frame || !force_key_frame_);
1273
asaperssona9455ab2015-07-31 06:10:09 -07001274 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -08001275 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001276 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +02001277 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001278 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001279 }
Niels Möller77536a22019-01-15 08:50:01 +01001280 RTC_DCHECK_LE(encoded_image_.size(), encoded_image_.capacity());
asapersson86956de2016-01-26 01:05:20 -08001281
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001282 memset(&codec_specific_, 0, sizeof(codec_specific_));
Niels Möllerd3b8c632018-08-27 15:33:42 +02001283 absl::optional<int> spatial_index;
1284 PopulateCodecSpecific(&codec_specific_, &spatial_index, *pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001285 input_image_->timestamp());
Niels Möllerd3b8c632018-08-27 15:33:42 +02001286 encoded_image_.SetSpatialIndex(spatial_index);
asaperssona9455ab2015-07-31 06:10:09 -07001287
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001288 UpdateReferenceBuffers(*pkt, pics_since_key_);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001289
Niels Möller77536a22019-01-15 08:50:01 +01001290 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_.size());
Niels Möller23775882018-08-16 10:24:12 +02001291 encoded_image_.SetTimestamp(input_image_->timestamp());
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001292 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
1293 encoded_image_.rotation_ = input_image_->rotation();
Niels Möllere3cf3d02018-06-13 11:52:16 +02001294 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001295 ? VideoContentType::SCREENSHARE
1296 : VideoContentType::UNSPECIFIED;
1297 encoded_image_._encodedHeight =
1298 pkt->data.frame.height[layer_id.spatial_layer_id];
1299 encoded_image_._encodedWidth =
1300 pkt->data.frame.width[layer_id.spatial_layer_id];
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +02001301 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001302 int qp = -1;
1303 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
1304 encoded_image_.qp_ = qp;
Johannes Kron4749e4e2018-11-21 10:18:18 +01001305 encoded_image_.SetColorSpace(input_image_->color_space());
ilnik04f4d122017-06-19 07:18:55 -07001306
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001307 if (full_superframe_drop_) {
1308 const bool end_of_picture = encoded_image_.SpatialIndex().value_or(0) + 1 ==
1309 num_active_spatial_layers_;
1310 DeliverBufferedFrame(end_of_picture);
1311 }
1312
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001313 return WEBRTC_VIDEO_CODEC_OK;
1314}
1315
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001316void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Niels Möller77536a22019-01-15 08:50:01 +01001317 if (encoded_image_.size() > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001318 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001319
1320 // No data partitioning in VP9, so 1 partition only.
1321 int part_idx = 0;
1322 RTPFragmentationHeader frag_info;
1323 frag_info.VerifyAndAllocateFragmentationHeader(1);
1324 frag_info.fragmentationOffset[part_idx] = 0;
Niels Möller77536a22019-01-15 08:50:01 +01001325 frag_info.fragmentationLength[part_idx] = encoded_image_.size();
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001326 frag_info.fragmentationPlType[part_idx] = 0;
1327 frag_info.fragmentationTimeDiff[part_idx] = 0;
1328
1329 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
1330 &frag_info);
Niels Möller77536a22019-01-15 08:50:01 +01001331 encoded_image_.set_size(0);
Sergey Silkind902d582018-05-18 17:31:19 +02001332
Sergey Silkin96f2c972018-09-05 21:07:17 +02001333 if (codec_.mode == VideoCodecMode::kScreensharing) {
1334 const uint8_t spatial_idx = encoded_image_.SpatialIndex().value_or(0);
1335 const uint32_t frame_timestamp_ms =
Niels Möller23775882018-08-16 10:24:12 +02001336 1000 * encoded_image_.Timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +02001337 framerate_controller_[spatial_idx].AddFrame(frame_timestamp_ms);
Sergey Silkind902d582018-05-18 17:31:19 +02001338 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001339 }
1340}
1341
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001342int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1343 EncodedImageCallback* callback) {
1344 encoded_complete_callback_ = callback;
1345 return WEBRTC_VIDEO_CODEC_OK;
1346}
1347
Erik Språng727d1642018-11-07 16:54:15 +01001348VideoEncoder::EncoderInfo VP9EncoderImpl::GetEncoderInfo() const {
1349 EncoderInfo info;
1350 info.supports_native_handle = false;
1351 info.implementation_name = "libvpx";
1352 info.scaling_settings = VideoEncoder::ScalingSettings::kOff;
Erik Språngd3438aa2018-11-08 16:56:43 +01001353 info.has_trusted_rate_controller = trusted_rate_controller_;
Mirta Dvornicic897a9912018-11-30 13:12:21 +01001354 info.is_hardware_accelerated = false;
1355 info.has_internal_source = false;
Erik Språngdbdd8392019-01-17 15:27:50 +01001356 for (size_t si = 0; si < num_spatial_layers_; ++si) {
1357 info.fps_allocation[si].clear();
1358 if (!codec_.spatialLayers[si].active) {
1359 continue;
1360 }
1361 // This spatial layer may already use a fraction of the total frame rate.
1362 const float sl_fps_fraction =
1363 codec_.spatialLayers[si].maxFramerate / codec_.maxFramerate;
1364 for (size_t ti = 0; ti < num_temporal_layers_; ++ti) {
1365 const uint32_t decimator =
1366 num_temporal_layers_ <= 1 ? 1 : config_->ts_rate_decimator[ti];
1367 RTC_DCHECK_GT(decimator, 0);
1368 info.fps_allocation[si].push_back(rtc::saturated_cast<uint8_t>(
1369 EncoderInfo::kMaxFramerateFraction * (sl_fps_fraction / decimator)));
1370 }
1371 }
Erik Språng727d1642018-11-07 16:54:15 +01001372 return info;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001373}
1374
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001375VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001376 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001377 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001378 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001379 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001380
1381VP9DecoderImpl::~VP9DecoderImpl() {
1382 inited_ = true; // in order to do the actual release
1383 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001384 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1385 if (num_buffers_in_use > 0) {
1386 // The frame buffers are reference counted and frames are exposed after
1387 // decoding. There may be valid usage cases where previous frames are still
1388 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001389 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1390 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001391 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001392}
1393
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001394int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001395 int ret_val = Release();
1396 if (ret_val < 0) {
1397 return ret_val;
1398 }
Sergey Silkinb674cd12018-10-09 10:59:06 +02001399
sprang3958ed82017-08-17 08:12:10 -07001400 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001401 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001402 }
philipelcce46fc2015-12-21 03:04:49 -08001403 vpx_codec_dec_cfg_t cfg;
Sergey Silkinb674cd12018-10-09 10:59:06 +02001404 memset(&cfg, 0, sizeof(cfg));
1405
1406 // We want to use multithreading when decoding high resolution videos. But,
1407 // since we don't know resolution of input stream at this stage, we always
1408 // enable it.
1409 cfg.threads = std::min(number_of_cores, kMaxNumTiles4kVideo);
1410
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001411 vpx_codec_flags_t flags = 0;
1412 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1413 return WEBRTC_VIDEO_CODEC_MEMORY;
1414 }
Henrik Boström9695d852015-05-06 10:42:15 +02001415
1416 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1417 return WEBRTC_VIDEO_CODEC_MEMORY;
1418 }
1419
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001420 inited_ = true;
1421 // Always start with a complete key frame.
1422 key_frame_required_ = true;
1423 return WEBRTC_VIDEO_CODEC_OK;
1424}
1425
1426int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1427 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001428 const CodecSpecificInfo* codec_specific_info,
1429 int64_t /*render_time_ms*/) {
1430 if (!inited_) {
1431 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1432 }
sprang3958ed82017-08-17 08:12:10 -07001433 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001434 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1435 }
1436 // Always start with a complete key frame.
1437 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +02001438 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001439 return WEBRTC_VIDEO_CODEC_ERROR;
1440 // We have a key frame - is it complete?
1441 if (input_image._completeFrame) {
1442 key_frame_required_ = false;
1443 } else {
1444 return WEBRTC_VIDEO_CODEC_ERROR;
1445 }
1446 }
sprang3958ed82017-08-17 08:12:10 -07001447 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001448 vpx_image_t* img;
Niels Möller24871e42019-01-17 11:31:13 +01001449 const uint8_t* buffer = input_image.data();
Niels Möller77536a22019-01-15 08:50:01 +01001450 if (input_image.size() == 0) {
sprang3958ed82017-08-17 08:12:10 -07001451 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001452 }
Henrik Boström9695d852015-05-06 10:42:15 +02001453 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1454 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001455 if (vpx_codec_decode(decoder_, buffer,
Niels Möller77536a22019-01-15 08:50:01 +01001456 static_cast<unsigned int>(input_image.size()), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001457 VPX_DL_REALTIME)) {
1458 return WEBRTC_VIDEO_CODEC_ERROR;
1459 }
Henrik Boström9695d852015-05-06 10:42:15 +02001460 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1461 // It may be released by libvpx during future vpx_codec_decode or
1462 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001463 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001464 int qp;
1465 vpx_codec_err_t vpx_ret =
1466 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1467 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
Johannes Kron9973fa82018-11-07 14:39:26 +01001468 int ret = ReturnFrame(img, input_image.Timestamp(), input_image.ntp_time_ms_,
Johannes Kron4749e4e2018-11-21 10:18:18 +01001469 qp, input_image.ColorSpace());
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001470 if (ret != 0) {
1471 return ret;
1472 }
1473 return WEBRTC_VIDEO_CODEC_OK;
1474}
1475
Danil Chapovalovb7698942019-02-05 11:32:19 +01001476int VP9DecoderImpl::ReturnFrame(
1477 const vpx_image_t* img,
1478 uint32_t timestamp,
1479 int64_t ntp_time_ms,
1480 int qp,
1481 const webrtc::ColorSpace* explicit_color_space) {
sprang3958ed82017-08-17 08:12:10 -07001482 if (img == nullptr) {
1483 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001484 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1485 }
Henrik Boström9695d852015-05-06 10:42:15 +02001486
1487 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001488 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001489 // vpx_codec_decode calls or vpx_codec_destroy).
1490 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1491 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001492
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001493 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001494 // using a Wrapped*Buffer.
1495 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1496 switch (img->bit_depth) {
1497 case 8:
1498 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001499 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1500 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1501 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1502 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001503 // WrappedI420Buffer's mechanism for allowing the release of its frame
1504 // buffer is through a callback function. This is where we should
1505 // release |img_buffer|.
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001506 rtc::KeepRefUntilDone(img_buffer));
1507 break;
1508 case 10:
1509 img_wrapped_buffer = WrapI010Buffer(
1510 img->d_w, img->d_h,
1511 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1512 img->stride[VPX_PLANE_Y] / 2,
1513 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1514 img->stride[VPX_PLANE_U] / 2,
1515 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1516 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1517 break;
1518 default:
1519 RTC_NOTREACHED();
1520 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1521 }
nisseca6d5d12016-06-17 05:03:04 -07001522
Johannes Kron4749e4e2018-11-21 10:18:18 +01001523 auto builder = VideoFrame::Builder()
1524 .set_video_frame_buffer(img_wrapped_buffer)
1525 .set_timestamp_ms(0)
1526 .set_timestamp_rtp(timestamp)
1527 .set_ntp_time_ms(ntp_time_ms)
1528 .set_rotation(webrtc::kVideoRotation_0);
1529 if (explicit_color_space) {
Danil Chapovalovb7698942019-02-05 11:32:19 +01001530 builder.set_color_space(*explicit_color_space);
Johannes Kron4749e4e2018-11-21 10:18:18 +01001531 } else {
1532 builder.set_color_space(
1533 ExtractVP9ColorSpace(img->cs, img->range, img->bit_depth));
1534 }
1535
1536 VideoFrame decoded_image = builder.build();
1537
Danil Chapovalov0040b662018-06-18 10:48:16 +02001538 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001539 return WEBRTC_VIDEO_CODEC_OK;
1540}
1541
1542int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1543 DecodedImageCallback* callback) {
1544 decode_complete_callback_ = callback;
1545 return WEBRTC_VIDEO_CODEC_OK;
1546}
1547
1548int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001549 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1550
sprang3958ed82017-08-17 08:12:10 -07001551 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001552 if (inited_) {
1553 // When a codec is destroyed libvpx will release any buffers of
1554 // |frame_buffer_pool_| it is currently using.
1555 if (vpx_codec_destroy(decoder_)) {
1556 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1557 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001558 }
1559 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001560 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001561 }
Henrik Boström9695d852015-05-06 10:42:15 +02001562 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1563 // still referenced externally are deleted once fully released, not returning
1564 // to the pool.
1565 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001566 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001567 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001568}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001569
1570const char* VP9DecoderImpl::ImplementationName() const {
1571 return "libvpx";
1572}
1573
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001574} // namespace webrtc
Mirko Bonadei95adedb2018-11-19 09:52:37 +01001575
1576#endif // RTC_ENABLE_VP9