blob: bbc1f715b3d219abd59ed0251a429e762e2ddd6b [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>
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +000018#include <utility>
marpan@webrtc.org5b883172014-11-01 06:10:48 +000019#include <vector>
20
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Emircan Uysaler800787f2018-07-16 10:01:49 -070022#include "api/video/color_space.h"
Emircan Uysaler0823eec2018-07-13 17:10:00 -070023#include "api/video/i010_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "common_video/include/video_frame_buffer.h"
25#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkind902d582018-05-18 17:31:19 +020026#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020027#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/checks.h"
Erik Språng4b4266f2019-01-23 12:48:13 +010029#include "rtc_base/experiments/rate_control_settings.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/keep_ref_until_done.h"
31#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/trace_event.h"
Sergey Silkin390f3582018-10-01 17:13:50 +020034#include "system_wrappers/include/field_trial.h"
Jonas Olssona4d87372019-07-05 19:08:33 +020035#include "vpx/vp8cx.h"
36#include "vpx/vp8dx.h"
37#include "vpx/vpx_decoder.h"
38#include "vpx/vpx_encoder.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000039
40namespace webrtc {
41
Sergey Silkind902d582018-05-18 17:31:19 +020042namespace {
Sergey Silkin390f3582018-10-01 17:13:50 +020043// Maps from gof_idx to encoder internal reference frame buffer index. These
44// maps work for 1,2 and 3 temporal layers with GOF length of 1,2 and 4 frames.
45uint8_t kRefBufIdx[4] = {0, 0, 0, 1};
46uint8_t kUpdBufIdx[4] = {0, 0, 1, 0};
47
Sergey Silkinb674cd12018-10-09 10:59:06 +020048int kMaxNumTiles4kVideo = 8;
49
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +010050// Maximum allowed PID difference for differnet per-layer frame-rate case.
Ilya Nikolaevskiy30323e22019-09-06 13:12:52 +020051const int kMaxAllowedPidDiff = 30;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +010052
Erik Språng7a3fe892019-04-15 12:22:55 +020053constexpr double kLowRateFactor = 1.0;
54constexpr double kHighRateFactor = 2.0;
55
56// These settings correspond to the settings in vpx_codec_enc_cfg.
Erik Språngeb180f82019-05-23 13:55:24 +020057struct Vp9RateSettings {
Erik Språng7a3fe892019-04-15 12:22:55 +020058 uint32_t rc_undershoot_pct;
59 uint32_t rc_overshoot_pct;
60 uint32_t rc_buf_sz;
61 uint32_t rc_buf_optimal_sz;
62 uint32_t rc_dropframe_thresh;
63};
64
Marco6e89b252015-07-07 14:40:38 -070065// Only positive speeds, range for real-time coding currently is: 5 - 8.
66// Lower means slower/better quality, higher means fastest/lower quality.
67int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070068#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080069 return 8;
70#else
Marco6e89b252015-07-07 14:40:38 -070071 // For smaller resolutions, use lower speed setting (get some coding gain at
72 // the cost of increased encoding complexity).
73 if (width * height <= 352 * 288)
74 return 5;
75 else
76 return 7;
Marco002f0d02015-12-17 09:49:31 -080077#endif
Marco6e89b252015-07-07 14:40:38 -070078}
Emircan Uysaler715cc232018-07-23 17:50:43 -070079// Helper class for extracting VP9 colorspace.
80ColorSpace ExtractVP9ColorSpace(vpx_color_space_t space_t,
81 vpx_color_range_t range_t,
82 unsigned int bit_depth) {
Johannes Kronb47ccc32018-12-07 11:12:44 +010083 ColorSpace::PrimaryID primaries = ColorSpace::PrimaryID::kUnspecified;
84 ColorSpace::TransferID transfer = ColorSpace::TransferID::kUnspecified;
85 ColorSpace::MatrixID matrix = ColorSpace::MatrixID::kUnspecified;
Emircan Uysaler715cc232018-07-23 17:50:43 -070086 switch (space_t) {
87 case VPX_CS_BT_601:
88 case VPX_CS_SMPTE_170:
89 primaries = ColorSpace::PrimaryID::kSMPTE170M;
90 transfer = ColorSpace::TransferID::kSMPTE170M;
91 matrix = ColorSpace::MatrixID::kSMPTE170M;
92 break;
93 case VPX_CS_SMPTE_240:
94 primaries = ColorSpace::PrimaryID::kSMPTE240M;
95 transfer = ColorSpace::TransferID::kSMPTE240M;
96 matrix = ColorSpace::MatrixID::kSMPTE240M;
97 break;
98 case VPX_CS_BT_709:
99 primaries = ColorSpace::PrimaryID::kBT709;
100 transfer = ColorSpace::TransferID::kBT709;
101 matrix = ColorSpace::MatrixID::kBT709;
102 break;
103 case VPX_CS_BT_2020:
104 primaries = ColorSpace::PrimaryID::kBT2020;
105 switch (bit_depth) {
106 case 8:
107 transfer = ColorSpace::TransferID::kBT709;
108 break;
109 case 10:
110 transfer = ColorSpace::TransferID::kBT2020_10;
111 break;
112 default:
113 RTC_NOTREACHED();
114 break;
115 }
116 matrix = ColorSpace::MatrixID::kBT2020_NCL;
117 break;
118 case VPX_CS_SRGB:
119 primaries = ColorSpace::PrimaryID::kBT709;
120 transfer = ColorSpace::TransferID::kIEC61966_2_1;
121 matrix = ColorSpace::MatrixID::kBT709;
122 break;
123 default:
124 break;
125 }
126
127 ColorSpace::RangeID range = ColorSpace::RangeID::kInvalid;
128 switch (range_t) {
129 case VPX_CR_STUDIO_RANGE:
130 range = ColorSpace::RangeID::kLimited;
131 break;
132 case VPX_CR_FULL_RANGE:
133 range = ColorSpace::RangeID::kFull;
134 break;
135 default:
136 break;
137 }
138 return ColorSpace(primaries, transfer, matrix, range);
139}
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100140
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000141std::pair<size_t, size_t> GetActiveLayers(
142 const VideoBitrateAllocation& allocation) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100143 for (size_t sl_idx = 0; sl_idx < kMaxSpatialLayers; ++sl_idx) {
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000144 if (allocation.GetSpatialLayerSum(sl_idx) > 0) {
145 size_t last_layer = sl_idx + 1;
146 while (last_layer < kMaxSpatialLayers &&
147 allocation.GetSpatialLayerSum(last_layer) > 0) {
148 ++last_layer;
149 }
150 return std::make_pair(sl_idx, last_layer);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100151 }
152 }
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000153 return {0, 0};
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100154}
155
Erik Språng7a3fe892019-04-15 12:22:55 +0200156uint32_t Interpolate(uint32_t low,
157 uint32_t high,
158 double bandwidth_headroom_factor) {
159 RTC_DCHECK_GE(bandwidth_headroom_factor, kLowRateFactor);
160 RTC_DCHECK_LE(bandwidth_headroom_factor, kHighRateFactor);
161
162 // |factor| is between 0.0 and 1.0.
163 const double factor = bandwidth_headroom_factor - kLowRateFactor;
164
165 return static_cast<uint32_t>(((1.0 - factor) * low) + (factor * high) + 0.5);
166}
167
Erik Språngeb180f82019-05-23 13:55:24 +0200168Vp9RateSettings GetRateSettings(double bandwidth_headroom_factor) {
169 static const Vp9RateSettings low_settings{100u, 0u, 100u, 33u, 40u};
170 static const Vp9RateSettings high_settings{50u, 50u, 1000u, 700u, 5u};
Erik Språng7a3fe892019-04-15 12:22:55 +0200171
172 if (bandwidth_headroom_factor <= kLowRateFactor) {
173 return low_settings;
174 } else if (bandwidth_headroom_factor >= kHighRateFactor) {
175 return high_settings;
176 }
177
Erik Språngeb180f82019-05-23 13:55:24 +0200178 Vp9RateSettings settings;
Erik Språng7a3fe892019-04-15 12:22:55 +0200179 settings.rc_undershoot_pct =
180 Interpolate(low_settings.rc_undershoot_pct,
181 high_settings.rc_undershoot_pct, bandwidth_headroom_factor);
182 settings.rc_overshoot_pct =
183 Interpolate(low_settings.rc_overshoot_pct, high_settings.rc_overshoot_pct,
184 bandwidth_headroom_factor);
185 settings.rc_buf_sz =
186 Interpolate(low_settings.rc_buf_sz, high_settings.rc_buf_sz,
187 bandwidth_headroom_factor);
188 settings.rc_buf_optimal_sz =
189 Interpolate(low_settings.rc_buf_optimal_sz,
190 high_settings.rc_buf_optimal_sz, bandwidth_headroom_factor);
191 settings.rc_dropframe_thresh =
192 Interpolate(low_settings.rc_dropframe_thresh,
193 high_settings.rc_dropframe_thresh, bandwidth_headroom_factor);
194 return settings;
195}
196
197void UpdateRateSettings(vpx_codec_enc_cfg_t* config,
Erik Språngeb180f82019-05-23 13:55:24 +0200198 const Vp9RateSettings& new_settings) {
Erik Språng7a3fe892019-04-15 12:22:55 +0200199 config->rc_undershoot_pct = new_settings.rc_undershoot_pct;
200 config->rc_overshoot_pct = new_settings.rc_overshoot_pct;
201 config->rc_buf_sz = new_settings.rc_buf_sz;
202 config->rc_buf_optimal_sz = new_settings.rc_buf_optimal_sz;
203 config->rc_dropframe_thresh = new_settings.rc_dropframe_thresh;
204}
205
Emircan Uysaler715cc232018-07-23 17:50:43 -0700206} // namespace
Marco6e89b252015-07-07 14:40:38 -0700207
asaperssona9455ab2015-07-31 06:10:09 -0700208void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
209 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -0800210 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -0700211 enc->GetEncodedLayerFrame(pkt);
212}
213
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700214VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000215 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -0700216 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700217 profile_(
218 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000219 inited_(false),
220 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000221 cpu_speed_(3),
222 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -0700223 encoder_(nullptr),
224 config_(nullptr),
225 raw_(nullptr),
226 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200227 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200228 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -0700229 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -0800230 num_spatial_layers_(0),
Sergey Silkin390f3582018-10-01 17:13:50 +0200231 num_active_spatial_layers_(0),
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000232 first_active_layer_(0),
Erik Språngd3438aa2018-11-08 16:56:43 +0100233 layer_deactivation_requires_key_frame_(
234 field_trial::IsEnabled("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation")),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200235 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200236 inter_layer_pred_(InterLayerPredMode::kOn),
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100237 external_ref_control_(false), // Set in InitEncode because of tests.
Erik Språng4b4266f2019-01-23 12:48:13 +0100238 trusted_rate_controller_(RateControlSettings::ParseFromFieldTrials()
239 .LibvpxVp9TrustedRateController()),
Erik Språng7a3fe892019-04-15 12:22:55 +0200240 dynamic_rate_settings_(
241 RateControlSettings::ParseFromFieldTrials().Vp9DynamicRateSettings()),
Ilya Nikolaevskiy1af0f902019-09-09 10:16:18 +0200242 layer_buffering_(false),
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100243 full_superframe_drop_(true),
244 first_frame_in_picture_(true),
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100245 ss_info_needed_(false),
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000246 force_all_active_layers_(false),
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100247 is_flexible_mode_(false),
248 variable_framerate_experiment_(ParseVariableFramerateConfig(
249 "WebRTC-VP9VariableFramerateScreenshare")),
250 variable_framerate_controller_(
251 variable_framerate_experiment_.framerate_limit),
252 num_steady_state_frames_(0) {
philipeld1d03592019-03-01 13:53:55 +0100253 codec_ = {};
johannkoenig8225c402017-01-26 13:23:44 -0800254 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000255}
256
257VP9EncoderImpl::~VP9EncoderImpl() {
258 Release();
259}
260
Elad Alon8f01c4e2019-06-28 15:19:43 +0200261void VP9EncoderImpl::SetFecControllerOverride(
262 FecControllerOverride* fec_controller_override) {
263 // Ignored.
264}
265
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000266int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100267 int ret_val = WEBRTC_VIDEO_CODEC_OK;
268
sprang3958ed82017-08-17 08:12:10 -0700269 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100270 if (inited_) {
271 if (vpx_codec_destroy(encoder_)) {
272 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
273 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000274 }
275 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700276 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000277 }
sprang3958ed82017-08-17 08:12:10 -0700278 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000279 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700280 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000281 }
sprang3958ed82017-08-17 08:12:10 -0700282 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000283 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700284 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000285 }
286 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100287 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000288}
289
sprangce4aef12015-11-02 07:23:20 -0800290bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
291 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
292 // (i.e. bitrates) were explicitly configured.
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200293 return codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800294}
295
Erik Språng566124a2018-04-23 12:32:22 +0200296bool VP9EncoderImpl::SetSvcRates(
297 const VideoBitrateAllocation& bitrate_allocation) {
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000298 std::pair<size_t, size_t> current_layers =
299 GetActiveLayers(current_bitrate_allocation_);
300 std::pair<size_t, size_t> new_layers = GetActiveLayers(bitrate_allocation);
301
302 const bool layer_activation_requires_key_frame =
303 inter_layer_pred_ == InterLayerPredMode::kOff ||
304 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic;
305 const bool lower_layers_enabled = new_layers.first < current_layers.first;
306 const bool higher_layers_enabled = new_layers.second > current_layers.second;
307 const bool disabled_layers = new_layers.first > current_layers.first ||
308 new_layers.second < current_layers.second;
309
310 if (lower_layers_enabled ||
311 (higher_layers_enabled && layer_activation_requires_key_frame) ||
312 (disabled_layers && layer_deactivation_requires_key_frame_)) {
313 force_key_frame_ = true;
314 }
315
316 if (current_layers != new_layers) {
317 ss_info_needed_ = true;
318 }
319
Sergey Silkin86684962018-03-28 19:32:37 +0200320 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200321
sprangce4aef12015-11-02 07:23:20 -0800322 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200323 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200324 const bool was_layer_active = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200325 config_->ss_target_bitrate[sl_idx] =
326 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
327
328 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
329 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
330 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
331 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200332
Sergey Silkine7ce8882018-10-03 18:04:57 +0200333 if (!was_layer_active) {
Sergey Silkin96f2c972018-09-05 21:07:17 +0200334 // Reset frame rate controller if layer is resumed after pause.
335 framerate_controller_[sl_idx].Reset();
336 }
337
338 framerate_controller_[sl_idx].SetTargetRate(
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200339 codec_.spatialLayers[sl_idx].maxFramerate);
sprangce4aef12015-11-02 07:23:20 -0800340 }
341 } else {
342 float rate_ratio[VPX_MAX_LAYERS] = {0};
343 float total = 0;
Sergey Silkin908689d2018-08-20 09:28:45 +0200344 for (int i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800345 if (svc_params_.scaling_factor_num[i] <= 0 ||
346 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100347 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800348 return false;
349 }
Yves Gerey665174f2018-06-19 15:03:05 +0200350 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
351 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800352 total += rate_ratio[i];
353 }
354
Sergey Silkin908689d2018-08-20 09:28:45 +0200355 for (int i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200356 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800357 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
358 config_->rc_target_bitrate * rate_ratio[i] / total);
359 if (num_temporal_layers_ == 1) {
360 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
361 } else if (num_temporal_layers_ == 2) {
362 config_->layer_target_bitrate[i * num_temporal_layers_] =
363 config_->ss_target_bitrate[i] * 2 / 3;
364 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
365 config_->ss_target_bitrate[i];
366 } else if (num_temporal_layers_ == 3) {
367 config_->layer_target_bitrate[i * num_temporal_layers_] =
368 config_->ss_target_bitrate[i] / 2;
369 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
370 config_->layer_target_bitrate[i * num_temporal_layers_] +
371 (config_->ss_target_bitrate[i] / 4);
372 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
373 config_->ss_target_bitrate[i];
374 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100375 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
376 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800377 return false;
378 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200379
380 framerate_controller_[i].SetTargetRate(codec_.maxFramerate);
asaperssona9455ab2015-07-31 06:10:09 -0700381 }
382 }
Sergey Silkin908689d2018-08-20 09:28:45 +0200383
384 num_active_spatial_layers_ = 0;
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000385 first_active_layer_ = 0;
386 bool seen_active_layer = false;
387 bool expect_no_more_active_layers = false;
Sergey Silkin908689d2018-08-20 09:28:45 +0200388 for (int i = 0; i < num_spatial_layers_; ++i) {
389 if (config_->ss_target_bitrate[i] > 0) {
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000390 RTC_DCHECK(!expect_no_more_active_layers) << "Only middle layer is "
391 "deactivated.";
392 if (!seen_active_layer) {
393 first_active_layer_ = i;
394 }
395 num_active_spatial_layers_ = i + 1;
396 seen_active_layer = true;
397 } else {
398 expect_no_more_active_layers = seen_active_layer;
Sergey Silkin908689d2018-08-20 09:28:45 +0200399 }
400 }
401 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
402
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000403 if (higher_layers_enabled && !force_key_frame_) {
404 // Prohibit drop of all layers for the next frame, so newly enabled
405 // layer would have a valid spatial reference.
406 for (size_t i = 0; i < num_spatial_layers_; ++i) {
407 svc_drop_frame_.framedrop_thresh[i] = 0;
408 }
409 force_all_active_layers_ = true;
410 }
411
412 current_bitrate_allocation_ = bitrate_allocation;
asaperssona9455ab2015-07-31 06:10:09 -0700413 return true;
414}
415
Erik Språng16cb8f52019-04-12 13:59:09 +0200416void VP9EncoderImpl::SetRates(const RateControlParameters& parameters) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000417 if (!inited_) {
Erik Språng16cb8f52019-04-12 13:59:09 +0200418 RTC_LOG(LS_WARNING) << "SetRates() calll while uninitialzied.";
419 return;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000420 }
421 if (encoder_->err) {
Erik Språng16cb8f52019-04-12 13:59:09 +0200422 RTC_LOG(LS_WARNING) << "Encoder in error state: " << encoder_->err;
423 return;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000424 }
Erik Språng16cb8f52019-04-12 13:59:09 +0200425 if (parameters.framerate_fps < 1.0) {
426 RTC_LOG(LS_WARNING) << "Unsupported framerate: "
427 << parameters.framerate_fps;
428 return;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000429 }
Erik Språng08127a92016-11-16 16:41:30 +0100430
Erik Språng16cb8f52019-04-12 13:59:09 +0200431 codec_.maxFramerate = static_cast<uint32_t>(parameters.framerate_fps + 0.5);
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000432
433 if (dynamic_rate_settings_) {
434 // Tweak rate control settings based on available network headroom.
435 UpdateRateSettings(
436 config_, GetRateSettings(parameters.bandwidth_allocation.bps<double>() /
437 parameters.bitrate.get_sum_bps()));
438 }
439
440 bool res = SetSvcRates(parameters.bitrate);
441 RTC_DCHECK(res) << "Failed to set new bitrate allocation";
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000442}
443
Elad Alon370f93a2019-06-11 14:57:57 +0200444// TODO(eladalon): s/inst/codec_settings/g.
Elad Alon11dfff02019-06-10 19:10:29 +0200445int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
Elad Alon370f93a2019-06-11 14:57:57 +0200446 const Settings& settings) {
sprang3958ed82017-08-17 08:12:10 -0700447 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000448 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
449 }
450 if (inst->maxFramerate < 1) {
451 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
452 }
453 // Allow zero to represent an unspecified maxBitRate
454 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
455 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
456 }
457 if (inst->width < 1 || inst->height < 1) {
458 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
459 }
Elad Alon370f93a2019-06-11 14:57:57 +0200460 if (settings.number_of_cores < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000461 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
462 }
hta257dc392016-10-25 09:05:06 -0700463 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700464 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
465 }
ilnik2a8c2f52017-02-15 02:23:28 -0800466 // libvpx probably does not support more than 3 spatial layers.
467 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700468 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
469 }
philipelcfc319b2015-11-10 07:17:23 -0800470
asapersson86956de2016-01-26 01:05:20 -0800471 int ret_val = Release();
472 if (ret_val < 0) {
473 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000474 }
sprang3958ed82017-08-17 08:12:10 -0700475 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000476 encoder_ = new vpx_codec_ctx_t;
477 }
sprang3958ed82017-08-17 08:12:10 -0700478 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000479 config_ = new vpx_codec_enc_cfg_t;
480 }
481 timestamp_ = 0;
482 if (&codec_ != inst) {
483 codec_ = *inst;
484 }
asaperssona9455ab2015-07-31 06:10:09 -0700485
Sergey Silkinb0bd03b2018-09-28 14:56:39 +0200486 force_key_frame_ = true;
487 pics_since_key_ = 0;
488
hta257dc392016-10-25 09:05:06 -0700489 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200490 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700491 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200492 if (num_temporal_layers_ == 0) {
asaperssona9455ab2015-07-31 06:10:09 -0700493 num_temporal_layers_ = 1;
Sergey Silkin042661b2018-09-10 10:39:35 +0000494 }
Sergey Silkinae9e1882018-09-05 21:07:17 +0200495
Sergey Silkin96f2c972018-09-05 21:07:17 +0200496 framerate_controller_ = std::vector<FramerateController>(
497 num_spatial_layers_, FramerateController(codec_.maxFramerate));
498
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200499 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200500
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000501 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000502 // Populate encoder configuration with default values.
503 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
504 return WEBRTC_VIDEO_CODEC_ERROR;
505 }
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700506
507 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
508 unsigned int bits_for_storage = 8;
509 switch (profile_) {
510 case VP9Profile::kProfile0:
511 img_fmt = VPX_IMG_FMT_I420;
512 bits_for_storage = 8;
513 config_->g_bit_depth = VPX_BITS_8;
514 config_->g_profile = 0;
515 config_->g_input_bit_depth = 8;
516 break;
517 case VP9Profile::kProfile2:
518 img_fmt = VPX_IMG_FMT_I42016;
519 bits_for_storage = 16;
520 config_->g_bit_depth = VPX_BITS_10;
521 config_->g_profile = 2;
522 config_->g_input_bit_depth = 10;
523 break;
524 }
525
526 // Creating a wrapper to the image - setting image data to nullptr. Actual
527 // pointer will be set in encode. Setting align to 1, as it is meaningless
528 // (actual memory is not allocated).
529 raw_ =
530 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
531 raw_->bit_depth = bits_for_storage;
532
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000533 config_->g_w = codec_.width;
534 config_->g_h = codec_.height;
535 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200536 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000537 // Setting the time base of the codec.
538 config_->g_timebase.num = 1;
539 config_->g_timebase.den = 90000;
540 config_->g_lag_in_frames = 0; // 0- no frame lagging
541 config_->g_threads = 1;
542 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700543 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000544 config_->rc_end_usage = VPX_CBR;
545 config_->g_pass = VPX_RC_ONE_PASS;
Ilya Nikolaevskiy3a656d12019-02-14 14:44:22 +0100546 config_->rc_min_quantizer =
547 codec_.mode == VideoCodecMode::kScreensharing ? 8 : 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000548 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000549 config_->rc_undershoot_pct = 50;
550 config_->rc_overshoot_pct = 50;
551 config_->rc_buf_initial_sz = 500;
552 config_->rc_buf_optimal_sz = 600;
553 config_->rc_buf_sz = 1000;
554 // Set the maximum target size of any key-frame.
555 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100556 // Key-frame interval is enforced manually by this wrapper.
557 config_->kf_mode = VPX_KF_DISABLED;
558 // TODO(webm:1592): work-around for libvpx issue, as it can still
559 // put some key-frames at will even in VPX_KF_DISABLED kf_mode.
560 config_->kf_max_dist = inst->VP9().keyFrameInterval;
561 config_->kf_min_dist = config_->kf_max_dist;
hta257dc392016-10-25 09:05:06 -0700562 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000563 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800564 config_->g_threads =
Elad Alon370f93a2019-06-11 14:57:57 +0200565 NumberOfThreads(config_->g_w, config_->g_h, settings.number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700566
Marco6e89b252015-07-07 14:40:38 -0700567 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700568
hta257dc392016-10-25 09:05:06 -0700569 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200570
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100571 inter_layer_pred_ = inst->VP9().interLayerPred;
572
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200573 if (num_spatial_layers_ > 1 &&
574 codec_.mode == VideoCodecMode::kScreensharing && !is_flexible_mode_) {
575 RTC_LOG(LS_ERROR) << "Flexible mode is required for screenshare with "
576 "several spatial layers";
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100577 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
578 }
579
580 // External reference control is required for different frame rate on spatial
581 // layers because libvpx generates rtp incompatible references in this case.
582 external_ref_control_ = field_trial::IsEnabled("WebRTC-Vp9ExternalRefCtrl") ||
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200583 (num_spatial_layers_ > 1 &&
584 codec_.mode == VideoCodecMode::kScreensharing) ||
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100585 inter_layer_pred_ == InterLayerPredMode::kOn;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100586
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200587 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700588 gof_.SetGofInfoVP9(kTemporalStructureMode1);
589 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
590 config_->ts_number_layers = 1;
591 config_->ts_rate_decimator[0] = 1;
592 config_->ts_periodicity = 1;
593 config_->ts_layer_id[0] = 0;
594 } else if (num_temporal_layers_ == 2) {
595 gof_.SetGofInfoVP9(kTemporalStructureMode2);
596 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
597 config_->ts_number_layers = 2;
598 config_->ts_rate_decimator[0] = 2;
599 config_->ts_rate_decimator[1] = 1;
600 config_->ts_periodicity = 2;
601 config_->ts_layer_id[0] = 0;
602 config_->ts_layer_id[1] = 1;
603 } else if (num_temporal_layers_ == 3) {
604 gof_.SetGofInfoVP9(kTemporalStructureMode3);
605 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
606 config_->ts_number_layers = 3;
607 config_->ts_rate_decimator[0] = 4;
608 config_->ts_rate_decimator[1] = 2;
609 config_->ts_rate_decimator[2] = 1;
610 config_->ts_periodicity = 4;
611 config_->ts_layer_id[0] = 0;
612 config_->ts_layer_id[1] = 2;
613 config_->ts_layer_id[2] = 1;
614 config_->ts_layer_id[3] = 2;
615 } else {
616 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
617 }
618
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100619 if (external_ref_control_) {
620 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +0200621 if (num_temporal_layers_ > 1 && num_spatial_layers_ > 1 &&
622 codec_.mode == VideoCodecMode::kScreensharing) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100623 // External reference control for several temporal layers with different
624 // frame rates on spatial layers is not implemented yet.
625 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
626 }
627 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200628 ref_buf_.clear();
629
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000630 return InitAndSetControlSettings(inst);
631}
632
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000633int VP9EncoderImpl::NumberOfThreads(int width,
634 int height,
635 int number_of_cores) {
636 // Keep the number of encoder threads equal to the possible number of column
637 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
638 if (width * height >= 1280 * 720 && number_of_cores > 4) {
639 return 4;
jianj23173a32017-07-12 16:11:09 -0700640 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000641 return 2;
642 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200643// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800644#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
645 defined(WEBRTC_ANDROID)
646 if (width * height >= 320 * 180 && number_of_cores > 2) {
647 return 2;
648 }
649#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000650 // 1 thread less than VGA.
651 return 1;
652 }
653}
654
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000655int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100656 // Set QP-min/max per spatial and temporal layer.
657 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
658 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800659 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
660 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100661 }
asaperssona9455ab2015-07-31 06:10:09 -0700662 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800663 if (ExplicitlyConfiguredSpatialLayers()) {
664 for (int i = 0; i < num_spatial_layers_; ++i) {
665 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200666 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100667 const int scale_factor = codec_.width / layer.width;
668 RTC_DCHECK_GT(scale_factor, 0);
669
670 // Ensure scaler factor is integer.
671 if (scale_factor * layer.width != codec_.width) {
672 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
673 }
674
675 // Ensure scale factor is the same in both dimensions.
676 if (scale_factor * layer.height != codec_.height) {
677 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
678 }
679
680 // Ensure scale factor is power of two.
681 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
682 if (!is_pow_of_two) {
683 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
684 }
685
686 svc_params_.scaling_factor_num[i] = 1;
687 svc_params_.scaling_factor_den[i] = scale_factor;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200688
689 RTC_DCHECK_GT(codec_.spatialLayers[i].maxFramerate, 0);
690 RTC_DCHECK_LE(codec_.spatialLayers[i].maxFramerate, codec_.maxFramerate);
691 if (i > 0) {
692 // Frame rate of high spatial layer is supposed to be equal or higher
693 // than frame rate of low spatial layer.
694 RTC_DCHECK_GE(codec_.spatialLayers[i].maxFramerate,
695 codec_.spatialLayers[i - 1].maxFramerate);
696 }
sprangce4aef12015-11-02 07:23:20 -0800697 }
698 } else {
699 int scaling_factor_num = 256;
700 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800701 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800702 svc_params_.scaling_factor_num[i] = scaling_factor_num;
703 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800704 }
asaperssona9455ab2015-07-31 06:10:09 -0700705 }
706
Sergey Silkin86684962018-03-28 19:32:37 +0200707 SvcRateAllocator init_allocator(codec_);
Florent Castelli8bbdb5b2019-08-02 15:16:28 +0200708 current_bitrate_allocation_ =
709 init_allocator.Allocate(VideoBitrateAllocationParameters(
710 inst->startBitrate * 1000, inst->maxFramerate));
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100711 if (!SetSvcRates(current_bitrate_allocation_)) {
asaperssona9455ab2015-07-31 06:10:09 -0700712 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
713 }
714
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700715 const vpx_codec_err_t rv = vpx_codec_enc_init(
716 encoder_, vpx_codec_vp9_cx(), config_,
717 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
718 if (rv != VPX_CODEC_OK) {
719 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000720 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
721 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000722 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
723 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
724 rc_max_intra_target_);
725 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700726 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700727
jianj822e5932017-07-12 16:09:58 -0700728 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100729 vpx_codec_control(encoder_, VP9E_SET_SVC_GF_TEMPORAL_REF, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200730
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200731 if (is_svc_) {
732 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
733 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700734 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200735
736 if (num_spatial_layers_ > 1) {
737 switch (inter_layer_pred_) {
738 case InterLayerPredMode::kOn:
739 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
740 break;
741 case InterLayerPredMode::kOff:
742 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
743 break;
744 case InterLayerPredMode::kOnKeyPic:
745 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
746 break;
747 default:
748 RTC_NOTREACHED();
749 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200750
Ilya Nikolaevskiy039a7142019-05-24 16:50:00 +0200751 memset(&svc_drop_frame_, 0, sizeof(svc_drop_frame_));
Ilya Nikolaevskiy1af0f902019-09-09 10:16:18 +0200752 const bool reverse_constrained_drop_mode =
753 inter_layer_pred_ == InterLayerPredMode::kOn &&
754 codec_.mode == VideoCodecMode::kScreensharing &&
755 num_spatial_layers_ > 1;
756 if (reverse_constrained_drop_mode) {
757 // Screenshare dropping mode: drop a layer only together with all lower
758 // layers. This ensures that drops on lower layers won't reduce frame-rate
759 // for higher layers and reference structure is RTP-compatible.
760 svc_drop_frame_.framedrop_mode = CONSTRAINED_FROM_ABOVE_DROP;
Ilya Nikolaevskiy039a7142019-05-24 16:50:00 +0200761 svc_drop_frame_.max_consec_drop = 5;
Ilya Nikolaevskiy1af0f902019-09-09 10:16:18 +0200762 for (size_t i = 0; i < num_spatial_layers_; ++i) {
763 svc_drop_frame_.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Ilya Nikolaevskiy039a7142019-05-24 16:50:00 +0200764 }
Ilya Nikolaevskiy1af0f902019-09-09 10:16:18 +0200765 // No buffering is needed because the highest layer is always present in
766 // all frames in CONSTRAINED_FROM_ABOVE drop mode.
767 layer_buffering_ = false;
Ilya Nikolaevskiy039a7142019-05-24 16:50:00 +0200768 } else {
769 // Configure encoder to drop entire superframe whenever it needs to drop
770 // a layer. This mode is preferred over per-layer dropping which causes
771 // quality flickering and is not compatible with RTP non-flexible mode.
772 svc_drop_frame_.framedrop_mode =
773 full_superframe_drop_ ? FULL_SUPERFRAME_DROP : CONSTRAINED_LAYER_DROP;
Ilya Nikolaevskiy1af0f902019-09-09 10:16:18 +0200774 // Buffering is needed only for constrained layer drop, as it's not clear
775 // which frame is the last.
776 layer_buffering_ = !full_superframe_drop_;
Ilya Nikolaevskiy039a7142019-05-24 16:50:00 +0200777 svc_drop_frame_.max_consec_drop = std::numeric_limits<int>::max();
778 for (size_t i = 0; i < num_spatial_layers_; ++i) {
779 svc_drop_frame_.framedrop_thresh[i] = config_->rc_dropframe_thresh;
780 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200781 }
Ilya Nikolaevskiy039a7142019-05-24 16:50:00 +0200782 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER,
783 &svc_drop_frame_);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200784 }
785
asaperssona9455ab2015-07-31 06:10:09 -0700786 // Register callback for getting each spatial layer.
787 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800788 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
789 reinterpret_cast<void*>(this)};
790 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
791 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700792
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000793 // Control function to set the number of column tiles in encoding a frame, in
794 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
795 // The number tile columns will be capped by the encoder based on image size
796 // (minimum width of tile column is 256 pixels, maximum is 4096).
797 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700798
799 // Turn on row-based multithreading.
800 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700801
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700802#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200803 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700804 // Do not enable the denoiser on ARM since optimization is pending.
805 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000806 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700807 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000808#endif
jianj6bf57e32017-06-05 13:43:49 -0700809
Niels Möllere3cf3d02018-06-13 11:52:16 +0200810 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700811 // Adjust internal parameters to screen content.
812 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700813 }
Marco2520e722015-09-16 14:05:00 -0700814 // Enable encoder skip of static/low content blocks.
815 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000816 inited_ = true;
817 return WEBRTC_VIDEO_CODEC_OK;
818}
819
820uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
821 // Set max to the optimal buffer level (normalized by target BR),
822 // and scaled by a scale_par.
823 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
824 // This value is presented in percentage of perFrameBw:
825 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
826 // The target in % is as follows:
827 float scale_par = 0.5;
828 uint32_t target_pct =
829 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
830 // Don't go below 3 times the per frame bandwidth.
831 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800832 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000833}
834
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700835int VP9EncoderImpl::Encode(const VideoFrame& input_image,
Niels Möller87e2d782019-03-07 10:18:23 +0100836 const std::vector<VideoFrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000837 if (!inited_) {
838 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
839 }
sprang3958ed82017-08-17 08:12:10 -0700840 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000841 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
842 }
Erik Språngbfa5d5d2019-02-04 16:40:19 +0100843 if (num_active_spatial_layers_ == 0) {
844 // All spatial layers are disabled, return without encoding anything.
845 return WEBRTC_VIDEO_CODEC_OK;
846 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200847
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000848 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200849 if (frame_types && !frame_types->empty()) {
Niels Möller8f7ce222019-03-21 15:43:58 +0100850 if ((*frame_types)[0] == VideoFrameType::kVideoFrameKey) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200851 force_key_frame_ = true;
852 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000853 }
Sergey Silkind902d582018-05-18 17:31:19 +0200854
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +0100855 if (pics_since_key_ + 1 ==
856 static_cast<size_t>(codec_.VP9()->keyFrameInterval)) {
857 force_key_frame_ = true;
858 }
859
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100860 vpx_svc_layer_id_t layer_id = {0};
861 if (!force_key_frame_) {
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000862 const size_t gof_idx = (pics_since_key_ + 1) % gof_.num_frames_in_gof;
863 layer_id.temporal_layer_id = gof_.temporal_idx[gof_idx];
Sergey Silkin96f2c972018-09-05 21:07:17 +0200864
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100865 if (VideoCodecMode::kScreensharing == codec_.mode) {
866 const uint32_t frame_timestamp_ms =
867 1000 * input_image.timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200868
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100869 // To ensure that several rate-limiters with different limits don't
870 // interfere, they must be queried in order of increasing limit.
871
872 bool use_steady_state_limiter =
873 variable_framerate_experiment_.enabled &&
874 input_image.update_rect().IsEmpty() &&
875 num_steady_state_frames_ >=
876 variable_framerate_experiment_.frames_before_steady_state;
877
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000878 // Need to check all frame limiters, even if lower layers are disabled,
879 // because variable frame-rate limiter should be checked after the first
880 // layer. It's easier to overwrite active layers after, then check all
881 // cases.
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100882 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100883 const float layer_fps =
884 framerate_controller_[layer_id.spatial_layer_id].GetTargetRate();
885 // Use steady state rate-limiter at the correct place.
886 if (use_steady_state_limiter &&
887 layer_fps > variable_framerate_experiment_.framerate_limit - 1e-9) {
888 if (variable_framerate_controller_.DropFrame(frame_timestamp_ms)) {
889 layer_id.spatial_layer_id = num_active_spatial_layers_;
890 }
891 // Break always: if rate limiter triggered frame drop, no need to
892 // continue; otherwise, the rate is less than the next limiters.
893 break;
894 }
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100895 if (framerate_controller_[sl_idx].DropFrame(frame_timestamp_ms)) {
896 ++layer_id.spatial_layer_id;
897 } else {
898 break;
899 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200900 }
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +0100901
902 if (use_steady_state_limiter &&
903 layer_id.spatial_layer_id < num_active_spatial_layers_) {
904 variable_framerate_controller_.AddFrame(frame_timestamp_ms);
905 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200906 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000907
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000908 if (force_all_active_layers_) {
909 layer_id.spatial_layer_id = first_active_layer_;
910 force_all_active_layers_ = false;
911 }
912
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000913 RTC_DCHECK_LE(layer_id.spatial_layer_id, num_active_spatial_layers_);
914 if (layer_id.spatial_layer_id >= num_active_spatial_layers_) {
915 // Drop entire picture.
916 return WEBRTC_VIDEO_CODEC_OK;
917 }
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100918 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000919
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100920 for (int sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
921 layer_id.temporal_layer_id_per_spatial[sl_idx] = layer_id.temporal_layer_id;
922 }
923
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000924 if (layer_id.spatial_layer_id < first_active_layer_) {
925 layer_id.spatial_layer_id = first_active_layer_;
Ilya Nikolaevskiy90d6efb2019-09-25 09:06:50 +0000926 }
927
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +0000928 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
929
Ilya Nikolaevskiy039a7142019-05-24 16:50:00 +0200930 if (num_spatial_layers_ > 1) {
931 // Update frame dropping settings as they may change on per-frame basis.
932 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER,
933 &svc_drop_frame_);
934 }
935
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100936 if (vpx_codec_enc_config_set(encoder_, config_)) {
937 return WEBRTC_VIDEO_CODEC_ERROR;
Sergey Silkind902d582018-05-18 17:31:19 +0200938 }
939
kwiberg352444f2016-11-28 15:58:53 -0800940 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
941 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700942
943 // Set input image for use in the callback.
944 // This was necessary since you need some information from input_image.
945 // You can save only the necessary information (such as timestamp) instead of
946 // doing this.
947 input_image_ = &input_image;
948
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700949 // Keep reference to buffer until encode completes.
950 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
Ilya Nikolaevskiya8507e32019-05-03 11:39:26 +0200951 const I010BufferInterface* i010_buffer;
952 rtc::scoped_refptr<const I010BufferInterface> i010_copy;
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700953 switch (profile_) {
954 case VP9Profile::kProfile0: {
955 i420_buffer = input_image.video_frame_buffer()->ToI420();
956 // Image in vpx_image_t format.
957 // Input image is const. VPX's raw image is not defined as const.
958 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
959 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
960 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
961 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
962 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
963 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
964 break;
965 }
966 case VP9Profile::kProfile2: {
967 // We can inject kI010 frames directly for encode. All other formats
968 // should be converted to it.
969 switch (input_image.video_frame_buffer()->type()) {
970 case VideoFrameBuffer::Type::kI010: {
971 i010_buffer = input_image.video_frame_buffer()->GetI010();
972 break;
973 }
974 default: {
Ilya Nikolaevskiya8507e32019-05-03 11:39:26 +0200975 i010_copy =
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700976 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
Ilya Nikolaevskiya8507e32019-05-03 11:39:26 +0200977 i010_buffer = i010_copy.get();
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700978 }
979 }
980 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
981 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
982 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
983 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
984 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
985 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
986 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
987 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
988 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
989 break;
990 }
991 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000992
philipelcfc319b2015-11-10 07:17:23 -0800993 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200994 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000995 flags = VPX_EFLAG_FORCE_KF;
996 }
philipelcfc319b2015-11-10 07:17:23 -0800997
Sergey Silkin390f3582018-10-01 17:13:50 +0200998 if (external_ref_control_) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100999 vpx_svc_ref_frame_config_t ref_config =
1000 SetReferences(force_key_frame_, layer_id.spatial_layer_id);
Sergey Silkina85995a2018-10-02 10:28:10 +02001001
1002 if (VideoCodecMode::kScreensharing == codec_.mode) {
1003 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
1004 ref_config.duration[sl_idx] = static_cast<int64_t>(
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +02001005 90000 / (std::min(static_cast<float>(codec_.maxFramerate),
1006 framerate_controller_[sl_idx].GetTargetRate())));
Sergey Silkina85995a2018-10-02 10:28:10 +02001007 }
1008 }
1009
Sergey Silkin390f3582018-10-01 17:13:50 +02001010 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &ref_config);
1011 }
1012
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001013 first_frame_in_picture_ = true;
1014
Sergey Silkin96f2c972018-09-05 21:07:17 +02001015 // TODO(ssilkin): Frame duration should be specified per spatial layer
1016 // since their frame rate can be different. For now calculate frame duration
1017 // based on target frame rate of the highest spatial layer, which frame rate
1018 // is supposed to be equal or higher than frame rate of low spatial layers.
1019 // Also, timestamp should represent actual time passed since previous frame
1020 // (not 'expected' time). Then rate controller can drain buffer more
1021 // accurately.
1022 RTC_DCHECK_GE(framerate_controller_.size(), num_active_spatial_layers_);
Sergey Silkinf87bb462018-09-17 09:37:37 +02001023 float target_framerate_fps =
1024 (codec_.mode == VideoCodecMode::kScreensharing)
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +02001025 ? std::min(static_cast<float>(codec_.maxFramerate),
1026 framerate_controller_[num_active_spatial_layers_ - 1]
1027 .GetTargetRate())
Sergey Silkinf87bb462018-09-17 09:37:37 +02001028 : codec_.maxFramerate;
1029 uint32_t duration = static_cast<uint32_t>(90000 / target_framerate_fps);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001030 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
1031 duration, flags, VPX_DL_REALTIME);
1032 if (rv != VPX_CODEC_OK) {
1033 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
1034 << "\n"
1035 << "Details: " << vpx_codec_error(encoder_) << "\n"
1036 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001037 return WEBRTC_VIDEO_CODEC_ERROR;
1038 }
1039 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -07001040
Ilya Nikolaevskiy1af0f902019-09-09 10:16:18 +02001041 if (layer_buffering_) {
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001042 const bool end_of_picture = true;
1043 DeliverBufferedFrame(end_of_picture);
1044 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001045
asaperssona9455ab2015-07-31 06:10:09 -07001046 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001047}
1048
1049void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
Niels Möllerd3b8c632018-08-27 15:33:42 +02001050 absl::optional<int>* spatial_idx,
philipelcce46fc2015-12-21 03:04:49 -08001051 const vpx_codec_cx_pkt& pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001052 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -07001053 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001054 codec_specific->codecType = kVideoCodecVP9;
philipelcce46fc2015-12-21 03:04:49 -08001055 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +02001056
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001057 vp9_info->first_frame_in_picture = first_frame_in_picture_;
Sergey Silkin738b7e92018-08-23 16:37:27 +02001058 vp9_info->flexible_mode = is_flexible_mode_;
asaperssona9455ab2015-07-31 06:10:09 -07001059
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001060 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
1061 pics_since_key_ = 0;
1062 } else if (first_frame_in_picture_) {
1063 ++pics_since_key_;
1064 }
1065
asaperssona9455ab2015-07-31 06:10:09 -07001066 vpx_svc_layer_id_t layer_id = {0};
1067 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1068
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001069 // Can't have keyframe with non-zero temporal layer.
1070 RTC_DCHECK(pics_since_key_ != 0 || layer_id.temporal_layer_id == 0);
1071
sprang3958ed82017-08-17 08:12:10 -07001072 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -05001073 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -07001074 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -07001075 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -07001076 vp9_info->temporal_idx = kNoTemporalIdx;
1077 } else {
1078 vp9_info->temporal_idx = layer_id.temporal_layer_id;
1079 }
“Michael23c5a992018-06-21 11:07:21 -05001080 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -07001081 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
Niels Möllerd3b8c632018-08-27 15:33:42 +02001082 *spatial_idx = absl::nullopt;
asaperssona9455ab2015-07-31 06:10:09 -07001083 } else {
Niels Möllerd3b8c632018-08-27 15:33:42 +02001084 *spatial_idx = layer_id.spatial_layer_id;
asaperssona9455ab2015-07-31 06:10:09 -07001085 }
asaperssona9455ab2015-07-31 06:10:09 -07001086
asaperssona9455ab2015-07-31 06:10:09 -07001087 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -08001088 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -07001089
Sergey Silkin6a8f30e2018-04-26 11:03:49 +02001090 const bool is_key_pic = (pics_since_key_ == 0);
1091 const bool is_inter_layer_pred_allowed =
1092 (inter_layer_pred_ == InterLayerPredMode::kOn ||
1093 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
1094
1095 // Always set inter_layer_predicted to true on high layer frame if inter-layer
1096 // prediction (ILP) is allowed even if encoder didn't actually use it.
1097 // Setting inter_layer_predicted to false would allow receiver to decode high
1098 // layer frame without decoding low layer frame. If that would happen (e.g.
1099 // if low layer frame is lost) then receiver won't be able to decode next high
1100 // layer frame which uses ILP.
1101 vp9_info->inter_layer_predicted =
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001102 first_frame_in_picture_ ? false : is_inter_layer_pred_allowed;
Sergey Silkin6a8f30e2018-04-26 11:03:49 +02001103
Sergey Silkinc5f152d2018-09-26 13:28:50 +02001104 // Mark all low spatial layer frames as references (not just frames of
1105 // active low spatial layers) if inter-layer prediction is enabled since
1106 // these frames are indirect references of high spatial layer, which can
1107 // later be enabled without key frame.
Sergey Silkin6a8f30e2018-04-26 11:03:49 +02001108 vp9_info->non_ref_for_inter_layer_pred =
Sergey Silkinc5f152d2018-09-26 13:28:50 +02001109 !is_inter_layer_pred_allowed ||
1110 layer_id.spatial_layer_id + 1 == num_spatial_layers_;
asapersson00ac85e2015-11-11 05:30:48 -08001111
ivica7f6a6fc2015-09-08 02:40:29 -07001112 // Always populate this, so that the packetizer can properly set the marker
1113 // bit.
“Michael23c5a992018-06-21 11:07:21 -05001114 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -08001115
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001116 vp9_info->num_ref_pics = 0;
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001117 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
1118 vp9_info);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001119 if (vp9_info->flexible_mode) {
1120 vp9_info->gof_idx = kNoGofIdx;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001121 } else {
1122 vp9_info->gof_idx =
1123 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
1124 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001125 RTC_DCHECK(vp9_info->num_ref_pics == gof_.num_ref_pics[vp9_info->gof_idx] ||
1126 vp9_info->num_ref_pics == 0);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001127 }
1128
1129 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
1130
Sergey Silkina323cc02019-04-23 10:09:28 +02001131 // Write SS on key frame of independently coded spatial layers and on base
1132 // temporal/spatial layer frame if number of layers changed without issuing
1133 // of key picture (inter-layer prediction is enabled).
1134 const bool is_key_frame = is_key_pic && !vp9_info->inter_layer_predicted;
1135 if (is_key_frame || (ss_info_needed_ && layer_id.temporal_layer_id == 0 &&
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +00001136 layer_id.spatial_layer_id == first_active_layer_)) {
Sergey Silkina323cc02019-04-23 10:09:28 +02001137 vp9_info->ss_data_available = true;
asaperssona9455ab2015-07-31 06:10:09 -07001138 vp9_info->spatial_layer_resolution_present = true;
Ilya Nikolaevskiybc8049e2019-09-25 09:10:33 +00001139 // Signal disabled layers.
1140 for (size_t i = 0; i < first_active_layer_; ++i) {
1141 vp9_info->width[i] = 0;
1142 vp9_info->height[i] = 0;
1143 }
1144 for (size_t i = first_active_layer_; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001145 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -08001146 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +02001147 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -08001148 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -07001149 }
Sergey Silkin738b7e92018-08-23 16:37:27 +02001150 if (vp9_info->flexible_mode) {
1151 vp9_info->gof.num_frames_in_gof = 0;
1152 } else {
asaperssona9455ab2015-07-31 06:10:09 -07001153 vp9_info->gof.CopyGofInfoVP9(gof_);
1154 }
Sergey Silkina323cc02019-04-23 10:09:28 +02001155
1156 ss_info_needed_ = false;
1157 } else {
1158 vp9_info->ss_data_available = false;
asaperssona9455ab2015-07-31 06:10:09 -07001159 }
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001160
1161 first_frame_in_picture_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001162}
1163
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001164void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
1165 const size_t pic_num,
1166 const bool inter_layer_predicted,
1167 CodecSpecificInfoVP9* vp9_info) {
1168 vpx_svc_layer_id_t layer_id = {0};
1169 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1170
Sergey Silkin76be2952018-08-21 12:30:33 +02001171 const bool is_key_frame =
1172 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001173
1174 std::vector<RefFrameBuffer> ref_buf_list;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001175
Sergey Silkin76be2952018-08-21 12:30:33 +02001176 if (is_svc_) {
1177 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1178 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
Sergey Silkin38fabff2019-03-21 10:08:40 +01001179 int ref_buf_flags = 0;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001180
Sergey Silkin76be2952018-08-21 12:30:33 +02001181 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
1182 const size_t fb_idx =
1183 enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
1184 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001185 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1186 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1187 ref_buf_list.push_back(ref_buf_.at(fb_idx));
Sergey Silkin38fabff2019-03-21 10:08:40 +01001188 ref_buf_flags |= 1 << fb_idx;
Sergey Silkin82276592018-08-27 14:54:20 +02001189 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001190 }
1191
1192 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
1193 const size_t fb_idx =
1194 enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
1195 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001196 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1197 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1198 ref_buf_list.push_back(ref_buf_.at(fb_idx));
Sergey Silkin38fabff2019-03-21 10:08:40 +01001199 ref_buf_flags |= 1 << fb_idx;
Sergey Silkin82276592018-08-27 14:54:20 +02001200 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001201 }
1202
1203 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
1204 const size_t fb_idx =
1205 enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
1206 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001207 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1208 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1209 ref_buf_list.push_back(ref_buf_.at(fb_idx));
Sergey Silkin38fabff2019-03-21 10:08:40 +01001210 ref_buf_flags |= 1 << fb_idx;
Sergey Silkin82276592018-08-27 14:54:20 +02001211 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001212 }
Sergey Silkin38fabff2019-03-21 10:08:40 +01001213
1214 RTC_LOG(LS_VERBOSE) << "Frame " << pic_num << " sl "
1215 << layer_id.spatial_layer_id << " tl "
1216 << layer_id.temporal_layer_id << " refered buffers "
1217 << (ref_buf_flags & (1 << 0) ? 1 : 0)
1218 << (ref_buf_flags & (1 << 1) ? 1 : 0)
1219 << (ref_buf_flags & (1 << 2) ? 1 : 0)
1220 << (ref_buf_flags & (1 << 3) ? 1 : 0)
1221 << (ref_buf_flags & (1 << 4) ? 1 : 0)
1222 << (ref_buf_flags & (1 << 5) ? 1 : 0)
1223 << (ref_buf_flags & (1 << 6) ? 1 : 0)
1224 << (ref_buf_flags & (1 << 7) ? 1 : 0);
1225
Sergey Silkin76be2952018-08-21 12:30:33 +02001226 } else if (!is_key_frame) {
1227 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1228 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1229 // In non-SVC mode encoder doesn't provide reference list. Assume each frame
1230 // refers previous one, which is stored in buffer 0.
1231 ref_buf_list.push_back(ref_buf_.at(0));
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001232 }
1233
1234 size_t max_ref_temporal_layer_id = 0;
1235
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001236 std::vector<size_t> ref_pid_list;
1237
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001238 vp9_info->num_ref_pics = 0;
1239 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
1240 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
1241 if (ref_buf.pic_num < pic_num) {
1242 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
1243 // RTP spec limits temporal prediction to the same spatial layer.
1244 // It is safe to ignore this requirement if inter-layer prediction is
1245 // enabled for all frames when all base frames are relayed to receiver.
1246 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +02001247 } else {
1248 RTC_DCHECK_LE(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001249 }
1250 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
1251
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001252 // Encoder may reference several spatial layers on the same previous
1253 // frame in case if some spatial layers are skipped on the current frame.
1254 // We shouldn't put duplicate references as it may break some old
1255 // clients and isn't RTP compatible.
1256 if (std::find(ref_pid_list.begin(), ref_pid_list.end(),
1257 ref_buf.pic_num) != ref_pid_list.end()) {
1258 continue;
1259 }
1260 ref_pid_list.push_back(ref_buf.pic_num);
1261
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001262 const size_t p_diff = pic_num - ref_buf.pic_num;
1263 RTC_DCHECK_LE(p_diff, 127UL);
1264
1265 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
1266 ++vp9_info->num_ref_pics;
1267
1268 max_ref_temporal_layer_id =
1269 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
1270 } else {
1271 RTC_DCHECK(inter_layer_predicted);
1272 // RTP spec only allows to use previous spatial layer for inter-layer
1273 // prediction.
1274 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
1275 }
1276 }
1277
1278 vp9_info->temporal_up_switch =
1279 (max_ref_temporal_layer_id <
1280 static_cast<size_t>(layer_id.temporal_layer_id));
1281}
1282
1283void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
1284 const size_t pic_num) {
1285 vpx_svc_layer_id_t layer_id = {0};
1286 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1287
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001288 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
1289 layer_id.temporal_layer_id);
1290
Sergey Silkin38fabff2019-03-21 10:08:40 +01001291 if (is_svc_) {
Sergey Silkin76be2952018-08-21 12:30:33 +02001292 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1293 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
Sergey Silkin38fabff2019-03-21 10:08:40 +01001294 const int update_buffer_slot =
1295 enc_layer_conf.update_buffer_slot[layer_id.spatial_layer_id];
Sergey Silkin76be2952018-08-21 12:30:33 +02001296
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001297 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
Sergey Silkin38fabff2019-03-21 10:08:40 +01001298 if (update_buffer_slot & (1 << i)) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001299 ref_buf_[i] = frame_buf;
1300 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001301 }
Sergey Silkin38fabff2019-03-21 10:08:40 +01001302
1303 RTC_LOG(LS_VERBOSE) << "Frame " << pic_num << " sl "
1304 << layer_id.spatial_layer_id << " tl "
1305 << layer_id.temporal_layer_id << " updated buffers "
1306 << (update_buffer_slot & (1 << 0) ? 1 : 0)
1307 << (update_buffer_slot & (1 << 1) ? 1 : 0)
1308 << (update_buffer_slot & (1 << 2) ? 1 : 0)
1309 << (update_buffer_slot & (1 << 3) ? 1 : 0)
1310 << (update_buffer_slot & (1 << 4) ? 1 : 0)
1311 << (update_buffer_slot & (1 << 5) ? 1 : 0)
1312 << (update_buffer_slot & (1 << 6) ? 1 : 0)
1313 << (update_buffer_slot & (1 << 7) ? 1 : 0);
Sergey Silkin76be2952018-08-21 12:30:33 +02001314 } else {
1315 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1316 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1317 // In non-svc mode encoder doesn't provide reference list. Assume each frame
1318 // is reference and stored in buffer 0.
1319 ref_buf_[0] = frame_buf;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001320 }
1321}
1322
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001323vpx_svc_ref_frame_config_t VP9EncoderImpl::SetReferences(
1324 bool is_key_pic,
1325 size_t first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001326 // kRefBufIdx, kUpdBufIdx need to be updated to support longer GOFs.
1327 RTC_DCHECK_LE(gof_.num_frames_in_gof, 4);
1328
1329 vpx_svc_ref_frame_config_t ref_config;
1330 memset(&ref_config, 0, sizeof(ref_config));
1331
1332 const size_t num_temporal_refs = std::max(1, num_temporal_layers_ - 1);
1333 const bool is_inter_layer_pred_allowed =
1334 inter_layer_pred_ == InterLayerPredMode::kOn ||
1335 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic);
1336 absl::optional<int> last_updated_buf_idx;
1337
1338 // Put temporal reference to LAST and spatial reference to GOLDEN. Update
1339 // frame buffer (i.e. store encoded frame) if current frame is a temporal
1340 // reference (i.e. it belongs to a low temporal layer) or it is a spatial
1341 // reference. In later case, always store spatial reference in the last
1342 // reference frame buffer.
1343 // For the case of 3 temporal and 3 spatial layers we need 6 frame buffers
1344 // for temporal references plus 1 buffer for spatial reference. 7 buffers
1345 // in total.
1346
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001347 for (size_t sl_idx = first_active_spatial_layer_id;
1348 sl_idx < num_active_spatial_layers_; ++sl_idx) {
1349 const size_t curr_pic_num = is_key_pic ? 0 : pics_since_key_ + 1;
1350 const size_t gof_idx = curr_pic_num % gof_.num_frames_in_gof;
Sergey Silkin390f3582018-10-01 17:13:50 +02001351
1352 if (!is_key_pic) {
1353 // Set up temporal reference.
1354 const int buf_idx = sl_idx * num_temporal_refs + kRefBufIdx[gof_idx];
1355
1356 // Last reference frame buffer is reserved for spatial reference. It is
1357 // not supposed to be used for temporal prediction.
1358 RTC_DCHECK_LT(buf_idx, kNumVp9Buffers - 1);
1359
Ilya Nikolaevskiy30323e22019-09-06 13:12:52 +02001360 const int pid_diff = curr_pic_num - ref_buf_[buf_idx].pic_num;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001361 // Incorrect spatial layer may be in the buffer due to a key-frame.
1362 const bool same_spatial_layer =
1363 ref_buf_[buf_idx].spatial_layer_id == sl_idx;
1364 bool correct_pid = false;
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +02001365 if (is_flexible_mode_) {
Ilya Nikolaevskiy30323e22019-09-06 13:12:52 +02001366 correct_pid = pid_diff > 0 && pid_diff < kMaxAllowedPidDiff;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001367 } else {
1368 // Below code assumes single temporal referecence.
1369 RTC_DCHECK_EQ(gof_.num_ref_pics[gof_idx], 1);
1370 correct_pid = pid_diff == gof_.pid_diff[gof_idx][0];
1371 }
Sergey Silkin390f3582018-10-01 17:13:50 +02001372
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001373 if (same_spatial_layer && correct_pid) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001374 ref_config.lst_fb_idx[sl_idx] = buf_idx;
1375 ref_config.reference_last[sl_idx] = 1;
1376 } else {
1377 // This reference doesn't match with one specified by GOF. This can
1378 // only happen if spatial layer is enabled dynamically without key
1379 // frame. Spatial prediction is supposed to be enabled in this case.
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001380 RTC_DCHECK(is_inter_layer_pred_allowed &&
1381 sl_idx > first_active_spatial_layer_id);
Sergey Silkin390f3582018-10-01 17:13:50 +02001382 }
1383 }
1384
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001385 if (is_inter_layer_pred_allowed && sl_idx > first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001386 // Set up spatial reference.
1387 RTC_DCHECK(last_updated_buf_idx);
1388 ref_config.gld_fb_idx[sl_idx] = *last_updated_buf_idx;
1389 ref_config.reference_golden[sl_idx] = 1;
1390 } else {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001391 RTC_DCHECK(ref_config.reference_last[sl_idx] != 0 ||
1392 sl_idx == first_active_spatial_layer_id ||
Sergey Silkin390f3582018-10-01 17:13:50 +02001393 inter_layer_pred_ == InterLayerPredMode::kOff);
1394 }
1395
1396 last_updated_buf_idx.reset();
1397
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001398 if (gof_.temporal_idx[gof_idx] < num_temporal_layers_ - 1 ||
1399 num_temporal_layers_ == 1) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001400 last_updated_buf_idx = sl_idx * num_temporal_refs + kUpdBufIdx[gof_idx];
1401
1402 // Ensure last frame buffer is not used for temporal prediction (it is
1403 // reserved for spatial reference).
1404 RTC_DCHECK_LT(*last_updated_buf_idx, kNumVp9Buffers - 1);
1405 } else if (is_inter_layer_pred_allowed) {
1406 last_updated_buf_idx = kNumVp9Buffers - 1;
1407 }
1408
1409 if (last_updated_buf_idx) {
1410 ref_config.update_buffer_slot[sl_idx] = 1 << *last_updated_buf_idx;
1411 }
1412 }
1413
1414 return ref_config;
1415}
1416
asaperssona9455ab2015-07-31 06:10:09 -07001417int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -08001418 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -07001419
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001420 if (pkt->data.frame.sz == 0) {
1421 // Ignore dropped frame.
1422 return WEBRTC_VIDEO_CODEC_OK;
1423 }
1424
Sergey Silkin07f80cc2018-04-09 13:11:59 +02001425 vpx_svc_layer_id_t layer_id = {0};
1426 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1427
Ilya Nikolaevskiy1af0f902019-09-09 10:16:18 +02001428 if (layer_buffering_) {
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001429 // Deliver buffered low spatial layer frame.
1430 const bool end_of_picture = false;
1431 DeliverBufferedFrame(end_of_picture);
1432 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001433
Niels Möller4d504c72019-06-18 15:56:56 +02001434 // TODO(nisse): Introduce some buffer cache or buffer pool, to reduce
1435 // allocations and/or copy operations.
1436 encoded_image_.SetEncodedData(EncodedImageBuffer::Create(
1437 static_cast<const uint8_t*>(pkt->data.frame.buf), pkt->data.frame.sz));
asaperssond9f641e2016-01-21 01:11:35 -08001438
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001439 const bool is_key_frame =
1440 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1441 // Ensure encoder issued key frame on request.
1442 RTC_DCHECK(is_key_frame || !force_key_frame_);
1443
asaperssona9455ab2015-07-31 06:10:09 -07001444 // Check if encoded frame is a key frame.
Niels Möller8f7ce222019-03-21 15:43:58 +01001445 encoded_image_._frameType = VideoFrameType::kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001446 if (is_key_frame) {
Niels Möller8f7ce222019-03-21 15:43:58 +01001447 encoded_image_._frameType = VideoFrameType::kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001448 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001449 }
Niels Möller77536a22019-01-15 08:50:01 +01001450 RTC_DCHECK_LE(encoded_image_.size(), encoded_image_.capacity());
asapersson86956de2016-01-26 01:05:20 -08001451
philipeld1d03592019-03-01 13:53:55 +01001452 codec_specific_ = {};
Niels Möllerd3b8c632018-08-27 15:33:42 +02001453 absl::optional<int> spatial_index;
1454 PopulateCodecSpecific(&codec_specific_, &spatial_index, *pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001455 input_image_->timestamp());
Niels Möllerd3b8c632018-08-27 15:33:42 +02001456 encoded_image_.SetSpatialIndex(spatial_index);
asaperssona9455ab2015-07-31 06:10:09 -07001457
Ilya Nikolaevskiy2ec0c652019-01-18 11:56:48 +01001458 UpdateReferenceBuffers(*pkt, pics_since_key_);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001459
Niels Möller77536a22019-01-15 08:50:01 +01001460 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_.size());
Niels Möller23775882018-08-16 10:24:12 +02001461 encoded_image_.SetTimestamp(input_image_->timestamp());
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001462 encoded_image_._encodedHeight =
1463 pkt->data.frame.height[layer_id.spatial_layer_id];
1464 encoded_image_._encodedWidth =
1465 pkt->data.frame.width[layer_id.spatial_layer_id];
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001466 int qp = -1;
1467 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
1468 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -07001469
Ilya Nikolaevskiy1af0f902019-09-09 10:16:18 +02001470 if (!layer_buffering_) {
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001471 const bool end_of_picture = encoded_image_.SpatialIndex().value_or(0) + 1 ==
1472 num_active_spatial_layers_;
1473 DeliverBufferedFrame(end_of_picture);
1474 }
1475
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001476 return WEBRTC_VIDEO_CODEC_OK;
1477}
1478
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001479void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Niels Möller77536a22019-01-15 08:50:01 +01001480 if (encoded_image_.size() > 0) {
Ilya Nikolaevskiy039a7142019-05-24 16:50:00 +02001481 if (num_spatial_layers_ > 1) {
1482 // Restore frame dropping settings, as dropping may be temporary forbidden
1483 // due to dynamically enabled layers.
Ilya Nikolaevskiy1af0f902019-09-09 10:16:18 +02001484 for (size_t i = 0; i < num_spatial_layers_; ++i) {
1485 svc_drop_frame_.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Ilya Nikolaevskiy039a7142019-05-24 16:50:00 +02001486 }
1487 }
1488
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001489 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001490
1491 // No data partitioning in VP9, so 1 partition only.
1492 int part_idx = 0;
1493 RTPFragmentationHeader frag_info;
1494 frag_info.VerifyAndAllocateFragmentationHeader(1);
1495 frag_info.fragmentationOffset[part_idx] = 0;
Niels Möller77536a22019-01-15 08:50:01 +01001496 frag_info.fragmentationLength[part_idx] = encoded_image_.size();
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001497
1498 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
1499 &frag_info);
Sergey Silkind902d582018-05-18 17:31:19 +02001500
Sergey Silkin96f2c972018-09-05 21:07:17 +02001501 if (codec_.mode == VideoCodecMode::kScreensharing) {
1502 const uint8_t spatial_idx = encoded_image_.SpatialIndex().value_or(0);
1503 const uint32_t frame_timestamp_ms =
Niels Möller23775882018-08-16 10:24:12 +02001504 1000 * encoded_image_.Timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +02001505 framerate_controller_[spatial_idx].AddFrame(frame_timestamp_ms);
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001506
1507 const size_t steady_state_size = SteadyStateSize(
1508 spatial_idx, codec_specific_.codecSpecific.VP9.temporal_idx);
1509
1510 // Only frames on spatial layers, which may be limited in a steady state
1511 // are considered for steady state detection.
1512 if (framerate_controller_[spatial_idx].GetTargetRate() >
1513 variable_framerate_experiment_.framerate_limit + 1e-9) {
1514 if (encoded_image_.qp_ <=
1515 variable_framerate_experiment_.steady_state_qp &&
1516 encoded_image_.size() <= steady_state_size) {
1517 ++num_steady_state_frames_;
1518 } else {
1519 num_steady_state_frames_ = 0;
1520 }
1521 }
Sergey Silkind902d582018-05-18 17:31:19 +02001522 }
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001523 encoded_image_.set_size(0);
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001524 }
1525}
1526
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001527int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1528 EncodedImageCallback* callback) {
1529 encoded_complete_callback_ = callback;
1530 return WEBRTC_VIDEO_CODEC_OK;
1531}
1532
Erik Språng727d1642018-11-07 16:54:15 +01001533VideoEncoder::EncoderInfo VP9EncoderImpl::GetEncoderInfo() const {
1534 EncoderInfo info;
1535 info.supports_native_handle = false;
1536 info.implementation_name = "libvpx";
1537 info.scaling_settings = VideoEncoder::ScalingSettings::kOff;
Erik Språngd3438aa2018-11-08 16:56:43 +01001538 info.has_trusted_rate_controller = trusted_rate_controller_;
Mirta Dvornicic897a9912018-11-30 13:12:21 +01001539 info.is_hardware_accelerated = false;
1540 info.has_internal_source = false;
Erik Språngdbdd8392019-01-17 15:27:50 +01001541 for (size_t si = 0; si < num_spatial_layers_; ++si) {
1542 info.fps_allocation[si].clear();
1543 if (!codec_.spatialLayers[si].active) {
1544 continue;
1545 }
1546 // This spatial layer may already use a fraction of the total frame rate.
1547 const float sl_fps_fraction =
1548 codec_.spatialLayers[si].maxFramerate / codec_.maxFramerate;
1549 for (size_t ti = 0; ti < num_temporal_layers_; ++ti) {
1550 const uint32_t decimator =
1551 num_temporal_layers_ <= 1 ? 1 : config_->ts_rate_decimator[ti];
1552 RTC_DCHECK_GT(decimator, 0);
1553 info.fps_allocation[si].push_back(rtc::saturated_cast<uint8_t>(
1554 EncoderInfo::kMaxFramerateFraction * (sl_fps_fraction / decimator)));
1555 }
1556 }
Erik Språng727d1642018-11-07 16:54:15 +01001557 return info;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001558}
1559
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001560size_t VP9EncoderImpl::SteadyStateSize(int sid, int tid) {
1561 const size_t bitrate_bps = current_bitrate_allocation_.GetBitrate(
1562 sid, tid == kNoTemporalIdx ? 0 : tid);
1563 const float fps = (codec_.mode == VideoCodecMode::kScreensharing)
Ilya Nikolaevskiy5c18a5f2019-05-24 11:51:31 +02001564 ? std::min(static_cast<float>(codec_.maxFramerate),
1565 framerate_controller_[sid].GetTargetRate())
Ilya Nikolaevskiy61170682019-03-06 16:04:32 +01001566 : codec_.maxFramerate;
1567 return static_cast<size_t>(
1568 bitrate_bps / (8 * fps) *
1569 (100 -
1570 variable_framerate_experiment_.steady_state_undershoot_percentage) /
1571 100 +
1572 0.5);
1573}
1574
1575// static
1576VP9EncoderImpl::VariableFramerateExperiment
1577VP9EncoderImpl::ParseVariableFramerateConfig(std::string group_name) {
1578 FieldTrialFlag enabled = FieldTrialFlag("Enabled");
1579 FieldTrialParameter<double> framerate_limit("min_fps", 5.0);
1580 FieldTrialParameter<int> qp("min_qp", 32);
1581 FieldTrialParameter<int> undershoot_percentage("undershoot", 30);
1582 FieldTrialParameter<int> frames_before_steady_state(
1583 "frames_before_steady_state", 5);
1584 ParseFieldTrial({&enabled, &framerate_limit, &qp, &undershoot_percentage,
1585 &frames_before_steady_state},
1586 field_trial::FindFullName(group_name));
1587 VariableFramerateExperiment config;
1588 config.enabled = enabled.Get();
1589 config.framerate_limit = framerate_limit.Get();
1590 config.steady_state_qp = qp.Get();
1591 config.steady_state_undershoot_percentage = undershoot_percentage.Get();
1592 config.frames_before_steady_state = frames_before_steady_state.Get();
1593
1594 return config;
1595}
1596
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001597VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001598 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001599 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001600 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001601 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001602
1603VP9DecoderImpl::~VP9DecoderImpl() {
1604 inited_ = true; // in order to do the actual release
1605 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001606 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1607 if (num_buffers_in_use > 0) {
1608 // The frame buffers are reference counted and frames are exposed after
1609 // decoding. There may be valid usage cases where previous frames are still
1610 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001611 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1612 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001613 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001614}
1615
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001616int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001617 int ret_val = Release();
1618 if (ret_val < 0) {
1619 return ret_val;
1620 }
Sergey Silkinb674cd12018-10-09 10:59:06 +02001621
sprang3958ed82017-08-17 08:12:10 -07001622 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001623 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001624 }
philipelcce46fc2015-12-21 03:04:49 -08001625 vpx_codec_dec_cfg_t cfg;
Sergey Silkinb674cd12018-10-09 10:59:06 +02001626 memset(&cfg, 0, sizeof(cfg));
1627
1628 // We want to use multithreading when decoding high resolution videos. But,
1629 // since we don't know resolution of input stream at this stage, we always
1630 // enable it.
1631 cfg.threads = std::min(number_of_cores, kMaxNumTiles4kVideo);
1632
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001633 vpx_codec_flags_t flags = 0;
1634 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1635 return WEBRTC_VIDEO_CODEC_MEMORY;
1636 }
Henrik Boström9695d852015-05-06 10:42:15 +02001637
1638 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1639 return WEBRTC_VIDEO_CODEC_MEMORY;
1640 }
1641
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001642 inited_ = true;
1643 // Always start with a complete key frame.
1644 key_frame_required_ = true;
1645 return WEBRTC_VIDEO_CODEC_OK;
1646}
1647
1648int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1649 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001650 int64_t /*render_time_ms*/) {
1651 if (!inited_) {
1652 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1653 }
sprang3958ed82017-08-17 08:12:10 -07001654 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001655 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1656 }
1657 // Always start with a complete key frame.
1658 if (key_frame_required_) {
Niels Möller8f7ce222019-03-21 15:43:58 +01001659 if (input_image._frameType != VideoFrameType::kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001660 return WEBRTC_VIDEO_CODEC_ERROR;
1661 // We have a key frame - is it complete?
1662 if (input_image._completeFrame) {
1663 key_frame_required_ = false;
1664 } else {
1665 return WEBRTC_VIDEO_CODEC_ERROR;
1666 }
1667 }
sprang3958ed82017-08-17 08:12:10 -07001668 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001669 vpx_image_t* img;
Niels Möller24871e42019-01-17 11:31:13 +01001670 const uint8_t* buffer = input_image.data();
Niels Möller77536a22019-01-15 08:50:01 +01001671 if (input_image.size() == 0) {
sprang3958ed82017-08-17 08:12:10 -07001672 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001673 }
Henrik Boström9695d852015-05-06 10:42:15 +02001674 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1675 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001676 if (vpx_codec_decode(decoder_, buffer,
Niels Möller77536a22019-01-15 08:50:01 +01001677 static_cast<unsigned int>(input_image.size()), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001678 VPX_DL_REALTIME)) {
1679 return WEBRTC_VIDEO_CODEC_ERROR;
1680 }
Henrik Boström9695d852015-05-06 10:42:15 +02001681 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1682 // It may be released by libvpx during future vpx_codec_decode or
1683 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001684 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001685 int qp;
1686 vpx_codec_err_t vpx_ret =
1687 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1688 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
Ilya Nikolaevskiya0e26092019-07-12 11:20:47 +02001689 int ret =
1690 ReturnFrame(img, input_image.Timestamp(), qp, input_image.ColorSpace());
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001691 if (ret != 0) {
1692 return ret;
1693 }
1694 return WEBRTC_VIDEO_CODEC_OK;
1695}
1696
Ilya Nikolaevskiya0e26092019-07-12 11:20:47 +02001697int VP9DecoderImpl::ReturnFrame(
1698 const vpx_image_t* img,
1699 uint32_t timestamp,
1700 int qp,
1701 const webrtc::ColorSpace* explicit_color_space) {
sprang3958ed82017-08-17 08:12:10 -07001702 if (img == nullptr) {
1703 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001704 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1705 }
Henrik Boström9695d852015-05-06 10:42:15 +02001706
1707 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001708 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001709 // vpx_codec_decode calls or vpx_codec_destroy).
1710 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1711 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001712
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001713 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001714 // using a Wrapped*Buffer.
1715 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1716 switch (img->bit_depth) {
1717 case 8:
1718 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001719 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1720 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1721 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1722 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001723 // WrappedI420Buffer's mechanism for allowing the release of its frame
1724 // buffer is through a callback function. This is where we should
1725 // release |img_buffer|.
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001726 rtc::KeepRefUntilDone(img_buffer));
1727 break;
1728 case 10:
1729 img_wrapped_buffer = WrapI010Buffer(
1730 img->d_w, img->d_h,
1731 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1732 img->stride[VPX_PLANE_Y] / 2,
1733 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1734 img->stride[VPX_PLANE_U] / 2,
1735 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1736 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1737 break;
1738 default:
1739 RTC_NOTREACHED();
1740 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1741 }
nisseca6d5d12016-06-17 05:03:04 -07001742
Johannes Kron4749e4e2018-11-21 10:18:18 +01001743 auto builder = VideoFrame::Builder()
1744 .set_video_frame_buffer(img_wrapped_buffer)
Ilya Nikolaevskiya0e26092019-07-12 11:20:47 +02001745 .set_timestamp_rtp(timestamp);
1746 if (explicit_color_space) {
1747 builder.set_color_space(*explicit_color_space);
1748 } else {
1749 builder.set_color_space(
1750 ExtractVP9ColorSpace(img->cs, img->range, img->bit_depth));
1751 }
Johannes Kron4749e4e2018-11-21 10:18:18 +01001752 VideoFrame decoded_image = builder.build();
1753
Danil Chapovalov0040b662018-06-18 10:48:16 +02001754 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001755 return WEBRTC_VIDEO_CODEC_OK;
1756}
1757
1758int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1759 DecodedImageCallback* callback) {
1760 decode_complete_callback_ = callback;
1761 return WEBRTC_VIDEO_CODEC_OK;
1762}
1763
1764int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001765 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1766
sprang3958ed82017-08-17 08:12:10 -07001767 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001768 if (inited_) {
1769 // When a codec is destroyed libvpx will release any buffers of
1770 // |frame_buffer_pool_| it is currently using.
1771 if (vpx_codec_destroy(decoder_)) {
1772 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1773 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001774 }
1775 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001776 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001777 }
Henrik Boström9695d852015-05-06 10:42:15 +02001778 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1779 // still referenced externally are deleted once fully released, not returning
1780 // to the pool.
1781 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001782 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001783 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001784}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001785
1786const char* VP9DecoderImpl::ImplementationName() const {
1787 return "libvpx";
1788}
1789
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001790} // namespace webrtc
Mirko Bonadei95adedb2018-11-19 09:52:37 +01001791
1792#endif // RTC_ENABLE_VP9