blob: 7bb2ea27d0ba8a7142689ef13959cfe8944ed245 [file] [log] [blame]
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001/*
2 * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 *
10 */
11
Mirko Bonadei95adedb2018-11-19 09:52:37 +010012#ifdef RTC_ENABLE_VP9
13
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020014#include "modules/video_coding/codecs/vp9/vp9_impl.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000015
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +020016#include <algorithm>
Sergey Silkind45b3452018-05-31 16:00:24 +020017#include <limits>
marpan@webrtc.org5b883172014-11-01 06:10:48 +000018#include <vector>
19
marpan@webrtc.org5b883172014-11-01 06:10:48 +000020#include "vpx/vp8cx.h"
21#include "vpx/vp8dx.h"
Yves Gerey665174f2018-06-19 15:03:05 +020022#include "vpx/vpx_decoder.h"
23#include "vpx/vpx_encoder.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000024
Karl Wiberg918f50c2018-07-05 11:40:33 +020025#include "absl/memory/memory.h"
Emircan Uysaler800787f2018-07-16 10:01:49 -070026#include "api/video/color_space.h"
Emircan Uysaler0823eec2018-07-13 17:10:00 -070027#include "api/video/i010_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "common_video/include/video_frame_buffer.h"
29#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkind902d582018-05-18 17:31:19 +020030#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020031#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/checks.h"
33#include "rtc_base/keep_ref_until_done.h"
34#include "rtc_base/logging.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/timeutils.h"
36#include "rtc_base/trace_event.h"
Sergey Silkin390f3582018-10-01 17:13:50 +020037#include "system_wrappers/include/field_trial.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000038
39namespace webrtc {
40
Sergey Silkind902d582018-05-18 17:31:19 +020041namespace {
Erik Språngd3438aa2018-11-08 16:56:43 +010042const char kVp9TrustedRateControllerFieldTrial[] =
43 "WebRTC-LibvpxVp9TrustedRateController";
44
Sergey Silkin390f3582018-10-01 17:13:50 +020045// Maps from gof_idx to encoder internal reference frame buffer index. These
46// maps work for 1,2 and 3 temporal layers with GOF length of 1,2 and 4 frames.
47uint8_t kRefBufIdx[4] = {0, 0, 0, 1};
48uint8_t kUpdBufIdx[4] = {0, 0, 1, 0};
49
Sergey Silkinb674cd12018-10-09 10:59:06 +020050int kMaxNumTiles4kVideo = 8;
51
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +010052// Maximum allowed PID difference for variable frame-rate mode.
53const int kMaxAllowedPidDIff = 8;
54
Marco6e89b252015-07-07 14:40:38 -070055// Only positive speeds, range for real-time coding currently is: 5 - 8.
56// Lower means slower/better quality, higher means fastest/lower quality.
57int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070058#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080059 return 8;
60#else
Marco6e89b252015-07-07 14:40:38 -070061 // For smaller resolutions, use lower speed setting (get some coding gain at
62 // the cost of increased encoding complexity).
63 if (width * height <= 352 * 288)
64 return 5;
65 else
66 return 7;
Marco002f0d02015-12-17 09:49:31 -080067#endif
Marco6e89b252015-07-07 14:40:38 -070068}
Emircan Uysaler715cc232018-07-23 17:50:43 -070069// Helper class for extracting VP9 colorspace.
70ColorSpace ExtractVP9ColorSpace(vpx_color_space_t space_t,
71 vpx_color_range_t range_t,
72 unsigned int bit_depth) {
Johannes Kron3b923d92018-11-30 10:51:20 +010073 ColorSpace::PrimaryID primaries = ColorSpace::PrimaryID::kUNSPECIFIED;
74 ColorSpace::TransferID transfer = ColorSpace::TransferID::kUNSPECIFIED;
75 ColorSpace::MatrixID matrix = ColorSpace::MatrixID::kUNSPECIFIED;
Emircan Uysaler715cc232018-07-23 17:50:43 -070076 switch (space_t) {
77 case VPX_CS_BT_601:
78 case VPX_CS_SMPTE_170:
79 primaries = ColorSpace::PrimaryID::kSMPTE170M;
80 transfer = ColorSpace::TransferID::kSMPTE170M;
81 matrix = ColorSpace::MatrixID::kSMPTE170M;
82 break;
83 case VPX_CS_SMPTE_240:
84 primaries = ColorSpace::PrimaryID::kSMPTE240M;
85 transfer = ColorSpace::TransferID::kSMPTE240M;
86 matrix = ColorSpace::MatrixID::kSMPTE240M;
87 break;
88 case VPX_CS_BT_709:
89 primaries = ColorSpace::PrimaryID::kBT709;
90 transfer = ColorSpace::TransferID::kBT709;
91 matrix = ColorSpace::MatrixID::kBT709;
92 break;
93 case VPX_CS_BT_2020:
94 primaries = ColorSpace::PrimaryID::kBT2020;
95 switch (bit_depth) {
96 case 8:
97 transfer = ColorSpace::TransferID::kBT709;
98 break;
99 case 10:
100 transfer = ColorSpace::TransferID::kBT2020_10;
101 break;
102 default:
103 RTC_NOTREACHED();
104 break;
105 }
106 matrix = ColorSpace::MatrixID::kBT2020_NCL;
107 break;
108 case VPX_CS_SRGB:
109 primaries = ColorSpace::PrimaryID::kBT709;
110 transfer = ColorSpace::TransferID::kIEC61966_2_1;
111 matrix = ColorSpace::MatrixID::kBT709;
112 break;
113 default:
114 break;
115 }
116
117 ColorSpace::RangeID range = ColorSpace::RangeID::kInvalid;
118 switch (range_t) {
119 case VPX_CR_STUDIO_RANGE:
120 range = ColorSpace::RangeID::kLimited;
121 break;
122 case VPX_CR_FULL_RANGE:
123 range = ColorSpace::RangeID::kFull;
124 break;
125 default:
126 break;
127 }
128 return ColorSpace(primaries, transfer, matrix, range);
129}
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100130
131bool MoreLayersEnabled(const VideoBitrateAllocation& first,
132 const VideoBitrateAllocation& second) {
133 for (size_t sl_idx = 0; sl_idx < kMaxSpatialLayers; ++sl_idx) {
134 if (first.GetSpatialLayerSum(sl_idx) > 0 &&
135 second.GetSpatialLayerSum(sl_idx) == 0) {
136 return true;
137 }
138 }
139 return false;
140}
141
Emircan Uysaler715cc232018-07-23 17:50:43 -0700142} // namespace
Marco6e89b252015-07-07 14:40:38 -0700143
asaperssona9455ab2015-07-31 06:10:09 -0700144void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
145 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -0800146 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -0700147 enc->GetEncodedLayerFrame(pkt);
148}
149
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700150VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000151 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -0700152 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700153 profile_(
154 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000155 inited_(false),
156 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000157 cpu_speed_(3),
158 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -0700159 encoder_(nullptr),
160 config_(nullptr),
161 raw_(nullptr),
162 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200163 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200164 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -0700165 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -0800166 num_spatial_layers_(0),
Sergey Silkin390f3582018-10-01 17:13:50 +0200167 num_active_spatial_layers_(0),
Erik Språngd3438aa2018-11-08 16:56:43 +0100168 layer_deactivation_requires_key_frame_(
169 field_trial::IsEnabled("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation")),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200170 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200171 inter_layer_pred_(InterLayerPredMode::kOn),
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100172 external_ref_control_(false), // Set in InitEncode because of tests.
Erik Språngd3438aa2018-11-08 16:56:43 +0100173 trusted_rate_controller_(
174 field_trial::IsEnabled(kVp9TrustedRateControllerFieldTrial)),
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100175 full_superframe_drop_(true),
176 first_frame_in_picture_(true),
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100177 ss_info_needed_(false),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200178 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000179 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -0800180 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000181}
182
183VP9EncoderImpl::~VP9EncoderImpl() {
184 Release();
185}
186
187int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100188 int ret_val = WEBRTC_VIDEO_CODEC_OK;
189
sprang3958ed82017-08-17 08:12:10 -0700190 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800191 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -0700192 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000193 }
sprang3958ed82017-08-17 08:12:10 -0700194 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100195 if (inited_) {
196 if (vpx_codec_destroy(encoder_)) {
197 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
198 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000199 }
200 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700201 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000202 }
sprang3958ed82017-08-17 08:12:10 -0700203 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000204 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700205 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000206 }
sprang3958ed82017-08-17 08:12:10 -0700207 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000208 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700209 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000210 }
211 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100212 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000213}
214
sprangce4aef12015-11-02 07:23:20 -0800215bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
216 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
217 // (i.e. bitrates) were explicitly configured.
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200218 return codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800219}
220
Erik Språng566124a2018-04-23 12:32:22 +0200221bool VP9EncoderImpl::SetSvcRates(
222 const VideoBitrateAllocation& bitrate_allocation) {
Sergey Silkin86684962018-03-28 19:32:37 +0200223 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200224
sprangce4aef12015-11-02 07:23:20 -0800225 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200226 const bool layer_activation_requires_key_frame =
227 inter_layer_pred_ == InterLayerPredMode::kOff ||
228 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic;
229
Sergey Silkin86684962018-03-28 19:32:37 +0200230 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkine7ce8882018-10-03 18:04:57 +0200231 const bool was_layer_active = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200232 config_->ss_target_bitrate[sl_idx] =
233 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
234
235 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
236 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
237 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
238 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200239
Sergey Silkine7ce8882018-10-03 18:04:57 +0200240 const bool is_active_layer = (config_->ss_target_bitrate[sl_idx] > 0);
241 if (!was_layer_active && is_active_layer &&
242 layer_activation_requires_key_frame) {
243 force_key_frame_ = true;
244 } else if (was_layer_active && !is_active_layer &&
245 layer_deactivation_requires_key_frame_) {
246 force_key_frame_ = true;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200247 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200248
Sergey Silkine7ce8882018-10-03 18:04:57 +0200249 if (!was_layer_active) {
Sergey Silkin96f2c972018-09-05 21:07:17 +0200250 // Reset frame rate controller if layer is resumed after pause.
251 framerate_controller_[sl_idx].Reset();
252 }
253
254 framerate_controller_[sl_idx].SetTargetRate(
Sergey Silkinbeba1b22018-09-11 11:40:25 +0200255 std::min(static_cast<float>(codec_.maxFramerate),
256 codec_.spatialLayers[sl_idx].maxFramerate));
sprangce4aef12015-11-02 07:23:20 -0800257 }
258 } else {
259 float rate_ratio[VPX_MAX_LAYERS] = {0};
260 float total = 0;
Sergey Silkin908689d2018-08-20 09:28:45 +0200261 for (int i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800262 if (svc_params_.scaling_factor_num[i] <= 0 ||
263 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100264 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800265 return false;
266 }
Yves Gerey665174f2018-06-19 15:03:05 +0200267 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
268 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800269 total += rate_ratio[i];
270 }
271
Sergey Silkin908689d2018-08-20 09:28:45 +0200272 for (int i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200273 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800274 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
275 config_->rc_target_bitrate * rate_ratio[i] / total);
276 if (num_temporal_layers_ == 1) {
277 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
278 } else if (num_temporal_layers_ == 2) {
279 config_->layer_target_bitrate[i * num_temporal_layers_] =
280 config_->ss_target_bitrate[i] * 2 / 3;
281 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
282 config_->ss_target_bitrate[i];
283 } else if (num_temporal_layers_ == 3) {
284 config_->layer_target_bitrate[i * num_temporal_layers_] =
285 config_->ss_target_bitrate[i] / 2;
286 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
287 config_->layer_target_bitrate[i * num_temporal_layers_] +
288 (config_->ss_target_bitrate[i] / 4);
289 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
290 config_->ss_target_bitrate[i];
291 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100292 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
293 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800294 return false;
295 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200296
297 framerate_controller_[i].SetTargetRate(codec_.maxFramerate);
asaperssona9455ab2015-07-31 06:10:09 -0700298 }
299 }
Sergey Silkin908689d2018-08-20 09:28:45 +0200300
301 num_active_spatial_layers_ = 0;
302 for (int i = 0; i < num_spatial_layers_; ++i) {
303 if (config_->ss_target_bitrate[i] > 0) {
304 ++num_active_spatial_layers_;
305 }
306 }
307 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
308
asaperssona9455ab2015-07-31 06:10:09 -0700309 return true;
310}
311
Erik Språng08127a92016-11-16 16:41:30 +0100312int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200313 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100314 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000315 if (!inited_) {
316 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
317 }
318 if (encoder_->err) {
319 return WEBRTC_VIDEO_CODEC_ERROR;
320 }
Erik Språng08127a92016-11-16 16:41:30 +0100321 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000322 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
323 }
324 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100325 if (codec_.maxBitrate > 0 &&
326 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
327 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000328 }
Erik Språng08127a92016-11-16 16:41:30 +0100329
Erik Språng08127a92016-11-16 16:41:30 +0100330 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700331
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100332 requested_bitrate_allocation_ = bitrate_allocation;
asaperssona9455ab2015-07-31 06:10:09 -0700333
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000334 return WEBRTC_VIDEO_CODEC_OK;
335}
336
337int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
338 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000339 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700340 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000341 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
342 }
343 if (inst->maxFramerate < 1) {
344 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
345 }
346 // Allow zero to represent an unspecified maxBitRate
347 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
348 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
349 }
350 if (inst->width < 1 || inst->height < 1) {
351 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
352 }
353 if (number_of_cores < 1) {
354 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
355 }
hta257dc392016-10-25 09:05:06 -0700356 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700357 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
358 }
ilnik2a8c2f52017-02-15 02:23:28 -0800359 // libvpx probably does not support more than 3 spatial layers.
360 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700361 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
362 }
philipelcfc319b2015-11-10 07:17:23 -0800363
asapersson86956de2016-01-26 01:05:20 -0800364 int ret_val = Release();
365 if (ret_val < 0) {
366 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000367 }
sprang3958ed82017-08-17 08:12:10 -0700368 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000369 encoder_ = new vpx_codec_ctx_t;
370 }
sprang3958ed82017-08-17 08:12:10 -0700371 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000372 config_ = new vpx_codec_enc_cfg_t;
373 }
374 timestamp_ = 0;
375 if (&codec_ != inst) {
376 codec_ = *inst;
377 }
asaperssona9455ab2015-07-31 06:10:09 -0700378
Sergey Silkinb0bd03b2018-09-28 14:56:39 +0200379 force_key_frame_ = true;
380 pics_since_key_ = 0;
381
hta257dc392016-10-25 09:05:06 -0700382 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200383 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700384 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200385 if (num_temporal_layers_ == 0) {
asaperssona9455ab2015-07-31 06:10:09 -0700386 num_temporal_layers_ = 1;
Sergey Silkin042661b2018-09-10 10:39:35 +0000387 }
Sergey Silkinae9e1882018-09-05 21:07:17 +0200388
Sergey Silkin96f2c972018-09-05 21:07:17 +0200389 framerate_controller_ = std::vector<FramerateController>(
390 num_spatial_layers_, FramerateController(codec_.maxFramerate));
391
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200392 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200393
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000394 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700395 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800396 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000397 }
nisseeb44b392017-04-28 07:18:05 -0700398 encoded_image_._size =
399 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000400 encoded_image_._buffer = new uint8_t[encoded_image_._size];
401 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000402 // Populate encoder configuration with default values.
403 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
404 return WEBRTC_VIDEO_CODEC_ERROR;
405 }
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700406
407 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
408 unsigned int bits_for_storage = 8;
409 switch (profile_) {
410 case VP9Profile::kProfile0:
411 img_fmt = VPX_IMG_FMT_I420;
412 bits_for_storage = 8;
413 config_->g_bit_depth = VPX_BITS_8;
414 config_->g_profile = 0;
415 config_->g_input_bit_depth = 8;
416 break;
417 case VP9Profile::kProfile2:
418 img_fmt = VPX_IMG_FMT_I42016;
419 bits_for_storage = 16;
420 config_->g_bit_depth = VPX_BITS_10;
421 config_->g_profile = 2;
422 config_->g_input_bit_depth = 10;
423 break;
424 }
425
426 // Creating a wrapper to the image - setting image data to nullptr. Actual
427 // pointer will be set in encode. Setting align to 1, as it is meaningless
428 // (actual memory is not allocated).
429 raw_ =
430 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
431 raw_->bit_depth = bits_for_storage;
432
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000433 config_->g_w = codec_.width;
434 config_->g_h = codec_.height;
435 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200436 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000437 // Setting the time base of the codec.
438 config_->g_timebase.num = 1;
439 config_->g_timebase.den = 90000;
440 config_->g_lag_in_frames = 0; // 0- no frame lagging
441 config_->g_threads = 1;
442 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700443 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000444 config_->rc_end_usage = VPX_CBR;
445 config_->g_pass = VPX_RC_ONE_PASS;
446 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000447 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000448 config_->rc_undershoot_pct = 50;
449 config_->rc_overshoot_pct = 50;
450 config_->rc_buf_initial_sz = 500;
451 config_->rc_buf_optimal_sz = 600;
452 config_->rc_buf_sz = 1000;
453 // Set the maximum target size of any key-frame.
454 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700455 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000456 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700457 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100458 // Needs to be set (in svc mode) to get correct periodic key frame interval
459 // (will have no effect in non-svc).
460 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000461 } else {
462 config_->kf_mode = VPX_KF_DISABLED;
463 }
hta257dc392016-10-25 09:05:06 -0700464 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000465 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800466 config_->g_threads =
467 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700468
Marco6e89b252015-07-07 14:40:38 -0700469 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700470
hta257dc392016-10-25 09:05:06 -0700471 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200472
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100473 inter_layer_pred_ = inst->VP9().interLayerPred;
474
475 different_framerates_used_ = false;
476 for (size_t sl_idx = 1; sl_idx < num_spatial_layers_; ++sl_idx) {
477 if (std::abs(codec_.spatialLayers[sl_idx].maxFramerate -
478 codec_.spatialLayers[0].maxFramerate) > 1e-9) {
479 different_framerates_used_ = true;
480 }
481 }
482
483 if (different_framerates_used_ && !is_flexible_mode_) {
484 RTC_LOG(LS_ERROR) << "Flexible mode required for different framerates on "
485 "different spatial layers";
486 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
487 }
488
489 // External reference control is required for different frame rate on spatial
490 // layers because libvpx generates rtp incompatible references in this case.
491 external_ref_control_ = field_trial::IsEnabled("WebRTC-Vp9ExternalRefCtrl") ||
492 different_framerates_used_;
493
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200494 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700495 gof_.SetGofInfoVP9(kTemporalStructureMode1);
496 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
497 config_->ts_number_layers = 1;
498 config_->ts_rate_decimator[0] = 1;
499 config_->ts_periodicity = 1;
500 config_->ts_layer_id[0] = 0;
501 } else if (num_temporal_layers_ == 2) {
502 gof_.SetGofInfoVP9(kTemporalStructureMode2);
503 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
504 config_->ts_number_layers = 2;
505 config_->ts_rate_decimator[0] = 2;
506 config_->ts_rate_decimator[1] = 1;
507 config_->ts_periodicity = 2;
508 config_->ts_layer_id[0] = 0;
509 config_->ts_layer_id[1] = 1;
510 } else if (num_temporal_layers_ == 3) {
511 gof_.SetGofInfoVP9(kTemporalStructureMode3);
512 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
513 config_->ts_number_layers = 3;
514 config_->ts_rate_decimator[0] = 4;
515 config_->ts_rate_decimator[1] = 2;
516 config_->ts_rate_decimator[2] = 1;
517 config_->ts_periodicity = 4;
518 config_->ts_layer_id[0] = 0;
519 config_->ts_layer_id[1] = 2;
520 config_->ts_layer_id[2] = 1;
521 config_->ts_layer_id[3] = 2;
522 } else {
523 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
524 }
525
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100526 if (external_ref_control_) {
527 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
528 if (num_temporal_layers_ > 1 && different_framerates_used_) {
529 // External reference control for several temporal layers with different
530 // frame rates on spatial layers is not implemented yet.
531 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
532 }
533 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200534 ref_buf_.clear();
535
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000536 return InitAndSetControlSettings(inst);
537}
538
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000539int VP9EncoderImpl::NumberOfThreads(int width,
540 int height,
541 int number_of_cores) {
542 // Keep the number of encoder threads equal to the possible number of column
543 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
544 if (width * height >= 1280 * 720 && number_of_cores > 4) {
545 return 4;
jianj23173a32017-07-12 16:11:09 -0700546 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000547 return 2;
548 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200549// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800550#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
551 defined(WEBRTC_ANDROID)
552 if (width * height >= 320 * 180 && number_of_cores > 2) {
553 return 2;
554 }
555#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000556 // 1 thread less than VGA.
557 return 1;
558 }
559}
560
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000561int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100562 // Set QP-min/max per spatial and temporal layer.
563 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
564 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800565 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
566 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100567 }
asaperssona9455ab2015-07-31 06:10:09 -0700568 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800569 if (ExplicitlyConfiguredSpatialLayers()) {
570 for (int i = 0; i < num_spatial_layers_; ++i) {
571 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200572 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100573 const int scale_factor = codec_.width / layer.width;
574 RTC_DCHECK_GT(scale_factor, 0);
575
576 // Ensure scaler factor is integer.
577 if (scale_factor * layer.width != codec_.width) {
578 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
579 }
580
581 // Ensure scale factor is the same in both dimensions.
582 if (scale_factor * layer.height != codec_.height) {
583 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
584 }
585
586 // Ensure scale factor is power of two.
587 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
588 if (!is_pow_of_two) {
589 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
590 }
591
592 svc_params_.scaling_factor_num[i] = 1;
593 svc_params_.scaling_factor_den[i] = scale_factor;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200594
595 RTC_DCHECK_GT(codec_.spatialLayers[i].maxFramerate, 0);
596 RTC_DCHECK_LE(codec_.spatialLayers[i].maxFramerate, codec_.maxFramerate);
597 if (i > 0) {
598 // Frame rate of high spatial layer is supposed to be equal or higher
599 // than frame rate of low spatial layer.
600 RTC_DCHECK_GE(codec_.spatialLayers[i].maxFramerate,
601 codec_.spatialLayers[i - 1].maxFramerate);
602 }
sprangce4aef12015-11-02 07:23:20 -0800603 }
604 } else {
605 int scaling_factor_num = 256;
606 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800607 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800608 svc_params_.scaling_factor_num[i] = scaling_factor_num;
609 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800610 }
asaperssona9455ab2015-07-31 06:10:09 -0700611 }
612
Sergey Silkin86684962018-03-28 19:32:37 +0200613 SvcRateAllocator init_allocator(codec_);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100614 current_bitrate_allocation_ = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200615 inst->startBitrate * 1000, inst->maxFramerate);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100616 if (!SetSvcRates(current_bitrate_allocation_)) {
asaperssona9455ab2015-07-31 06:10:09 -0700617 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
618 }
619
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700620 const vpx_codec_err_t rv = vpx_codec_enc_init(
621 encoder_, vpx_codec_vp9_cx(), config_,
622 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
623 if (rv != VPX_CODEC_OK) {
624 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000625 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
626 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000627 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
628 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
629 rc_max_intra_target_);
630 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700631 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700632
jianj822e5932017-07-12 16:09:58 -0700633 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100634 vpx_codec_control(encoder_, VP9E_SET_SVC_GF_TEMPORAL_REF, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200635
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200636 if (is_svc_) {
637 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
638 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700639 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200640
641 if (num_spatial_layers_ > 1) {
642 switch (inter_layer_pred_) {
643 case InterLayerPredMode::kOn:
644 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
645 break;
646 case InterLayerPredMode::kOff:
647 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
648 break;
649 case InterLayerPredMode::kOnKeyPic:
650 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
651 break;
652 default:
653 RTC_NOTREACHED();
654 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200655
Sergey Silkinee203362018-05-30 11:34:08 +0200656 // Configure encoder to drop entire superframe whenever it needs to drop
657 // a layer. This mode is prefered over per-layer dropping which causes
658 // quality flickering and is not compatible with RTP non-flexible mode.
659 vpx_svc_frame_drop_t svc_drop_frame;
660 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100661 svc_drop_frame.framedrop_mode =
662 full_superframe_drop_ ? FULL_SUPERFRAME_DROP : CONSTRAINED_LAYER_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200663 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200664 for (size_t i = 0; i < num_spatial_layers_; ++i) {
665 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200666 }
Sergey Silkinee203362018-05-30 11:34:08 +0200667 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200668 }
669
asaperssona9455ab2015-07-31 06:10:09 -0700670 // Register callback for getting each spatial layer.
671 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800672 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
673 reinterpret_cast<void*>(this)};
674 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
675 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700676
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000677 // Control function to set the number of column tiles in encoding a frame, in
678 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
679 // The number tile columns will be capped by the encoder based on image size
680 // (minimum width of tile column is 256 pixels, maximum is 4096).
681 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700682
683 // Turn on row-based multithreading.
684 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700685
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700686#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200687 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700688 // Do not enable the denoiser on ARM since optimization is pending.
689 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000690 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700691 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000692#endif
jianj6bf57e32017-06-05 13:43:49 -0700693
Niels Möllere3cf3d02018-06-13 11:52:16 +0200694 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700695 // Adjust internal parameters to screen content.
696 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700697 }
Marco2520e722015-09-16 14:05:00 -0700698 // Enable encoder skip of static/low content blocks.
699 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000700 inited_ = true;
701 return WEBRTC_VIDEO_CODEC_OK;
702}
703
704uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
705 // Set max to the optimal buffer level (normalized by target BR),
706 // and scaled by a scale_par.
707 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
708 // This value is presented in percentage of perFrameBw:
709 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
710 // The target in % is as follows:
711 float scale_par = 0.5;
712 uint32_t target_pct =
713 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
714 // Don't go below 3 times the per frame bandwidth.
715 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800716 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000717}
718
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700719int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000720 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700721 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000722 if (!inited_) {
723 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
724 }
sprang3958ed82017-08-17 08:12:10 -0700725 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000726 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
727 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200728
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000729 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200730 if (frame_types && !frame_types->empty()) {
731 if ((*frame_types)[0] == kVideoFrameKey) {
732 force_key_frame_ = true;
733 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000734 }
Sergey Silkind902d582018-05-18 17:31:19 +0200735
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100736 vpx_svc_layer_id_t layer_id = {0};
737 if (!force_key_frame_) {
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000738 const size_t gof_idx = (pics_since_key_ + 1) % gof_.num_frames_in_gof;
739 layer_id.temporal_layer_id = gof_.temporal_idx[gof_idx];
Sergey Silkin96f2c972018-09-05 21:07:17 +0200740
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100741 if (VideoCodecMode::kScreensharing == codec_.mode) {
742 const uint32_t frame_timestamp_ms =
743 1000 * input_image.timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +0200744
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100745 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
746 if (framerate_controller_[sl_idx].DropFrame(frame_timestamp_ms)) {
747 ++layer_id.spatial_layer_id;
748 } else {
749 break;
750 }
Sergey Silkin96f2c972018-09-05 21:07:17 +0200751 }
752 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000753
754 RTC_DCHECK_LE(layer_id.spatial_layer_id, num_active_spatial_layers_);
755 if (layer_id.spatial_layer_id >= num_active_spatial_layers_) {
756 // Drop entire picture.
757 return WEBRTC_VIDEO_CODEC_OK;
758 }
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100759 }
Patrik Höglundd4d254f2018-11-29 15:09:31 +0000760
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100761 for (int sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
762 layer_id.temporal_layer_id_per_spatial[sl_idx] = layer_id.temporal_layer_id;
763 }
764
765 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
766
767 if (requested_bitrate_allocation_) {
768 bool more_layers_requested = MoreLayersEnabled(
769 *requested_bitrate_allocation_, current_bitrate_allocation_);
770 bool less_layers_requested = MoreLayersEnabled(
771 current_bitrate_allocation_, *requested_bitrate_allocation_);
772 // In SVC can enable new layers only if all lower layers are encoded and at
773 // the base temporal layer.
774 // This will delay rate allocation change until the next frame on the base
775 // spatial layer.
776 // In KSVC or simulcast modes KF will be generated for a new layer, so can
777 // update allocation any time.
778 bool can_upswitch =
779 inter_layer_pred_ != InterLayerPredMode::kOn ||
780 (layer_id.spatial_layer_id == 0 && layer_id.temporal_layer_id == 0);
781 if (!more_layers_requested || can_upswitch) {
782 current_bitrate_allocation_ = *requested_bitrate_allocation_;
783 requested_bitrate_allocation_ = absl::nullopt;
784 if (!SetSvcRates(current_bitrate_allocation_)) {
785 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
786 }
787 if (less_layers_requested || more_layers_requested) {
788 ss_info_needed_ = true;
789 }
790 }
791 }
792
793 if (vpx_codec_enc_config_set(encoder_, config_)) {
794 return WEBRTC_VIDEO_CODEC_ERROR;
Sergey Silkind902d582018-05-18 17:31:19 +0200795 }
796
kwiberg352444f2016-11-28 15:58:53 -0800797 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
798 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700799
800 // Set input image for use in the callback.
801 // This was necessary since you need some information from input_image.
802 // You can save only the necessary information (such as timestamp) instead of
803 // doing this.
804 input_image_ = &input_image;
805
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700806 // Keep reference to buffer until encode completes.
807 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
808 rtc::scoped_refptr<I010BufferInterface> i010_buffer;
809 switch (profile_) {
810 case VP9Profile::kProfile0: {
811 i420_buffer = input_image.video_frame_buffer()->ToI420();
812 // Image in vpx_image_t format.
813 // Input image is const. VPX's raw image is not defined as const.
814 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
815 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
816 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
817 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
818 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
819 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
820 break;
821 }
822 case VP9Profile::kProfile2: {
823 // We can inject kI010 frames directly for encode. All other formats
824 // should be converted to it.
825 switch (input_image.video_frame_buffer()->type()) {
826 case VideoFrameBuffer::Type::kI010: {
827 i010_buffer = input_image.video_frame_buffer()->GetI010();
828 break;
829 }
830 default: {
831 i010_buffer =
832 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
833 }
834 }
835 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
836 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
837 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
838 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
839 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
840 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
841 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
842 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
843 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
844 break;
845 }
846 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000847
philipelcfc319b2015-11-10 07:17:23 -0800848 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200849 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000850 flags = VPX_EFLAG_FORCE_KF;
851 }
philipelcfc319b2015-11-10 07:17:23 -0800852
Sergey Silkin390f3582018-10-01 17:13:50 +0200853 if (external_ref_control_) {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100854 vpx_svc_ref_frame_config_t ref_config =
855 SetReferences(force_key_frame_, layer_id.spatial_layer_id);
Sergey Silkina85995a2018-10-02 10:28:10 +0200856
857 if (VideoCodecMode::kScreensharing == codec_.mode) {
858 for (uint8_t sl_idx = 0; sl_idx < num_active_spatial_layers_; ++sl_idx) {
859 ref_config.duration[sl_idx] = static_cast<int64_t>(
860 90000 / framerate_controller_[sl_idx].GetTargetRate());
861 }
862 }
863
Sergey Silkin390f3582018-10-01 17:13:50 +0200864 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &ref_config);
865 }
866
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100867 first_frame_in_picture_ = true;
868
Sergey Silkin96f2c972018-09-05 21:07:17 +0200869 // TODO(ssilkin): Frame duration should be specified per spatial layer
870 // since their frame rate can be different. For now calculate frame duration
871 // based on target frame rate of the highest spatial layer, which frame rate
872 // is supposed to be equal or higher than frame rate of low spatial layers.
873 // Also, timestamp should represent actual time passed since previous frame
874 // (not 'expected' time). Then rate controller can drain buffer more
875 // accurately.
876 RTC_DCHECK_GE(framerate_controller_.size(), num_active_spatial_layers_);
Sergey Silkinf87bb462018-09-17 09:37:37 +0200877 float target_framerate_fps =
878 (codec_.mode == VideoCodecMode::kScreensharing)
879 ? framerate_controller_[num_active_spatial_layers_ - 1]
880 .GetTargetRate()
881 : codec_.maxFramerate;
882 uint32_t duration = static_cast<uint32_t>(90000 / target_framerate_fps);
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700883 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
884 duration, flags, VPX_DL_REALTIME);
885 if (rv != VPX_CODEC_OK) {
886 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
887 << "\n"
888 << "Details: " << vpx_codec_error(encoder_) << "\n"
889 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000890 return WEBRTC_VIDEO_CODEC_ERROR;
891 }
892 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700893
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100894 if (!full_superframe_drop_) {
895 const bool end_of_picture = true;
896 DeliverBufferedFrame(end_of_picture);
897 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200898
asaperssona9455ab2015-07-31 06:10:09 -0700899 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000900}
901
902void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
Niels Möllerd3b8c632018-08-27 15:33:42 +0200903 absl::optional<int>* spatial_idx,
philipelcce46fc2015-12-21 03:04:49 -0800904 const vpx_codec_cx_pkt& pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100905 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -0700906 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000907 codec_specific->codecType = kVideoCodecVP9;
philipelcce46fc2015-12-21 03:04:49 -0800908 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200909
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100910 vp9_info->first_frame_in_picture = first_frame_in_picture_;
Sergey Silkin738b7e92018-08-23 16:37:27 +0200911 vp9_info->flexible_mode = is_flexible_mode_;
hta257dc392016-10-25 09:05:06 -0700912 vp9_info->ss_data_available =
Sergey Silkin738b7e92018-08-23 16:37:27 +0200913 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
asaperssona9455ab2015-07-31 06:10:09 -0700914
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100915 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
916 pics_since_key_ = 0;
917 } else if (first_frame_in_picture_) {
918 ++pics_since_key_;
919 }
920
asaperssona9455ab2015-07-31 06:10:09 -0700921 vpx_svc_layer_id_t layer_id = {0};
922 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
923
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100924 if (ss_info_needed_ && layer_id.temporal_layer_id == 0 &&
925 layer_id.spatial_layer_id == 0) {
926 // Force SS info after the layers configuration has changed.
927 vp9_info->ss_data_available = true;
928 ss_info_needed_ = false;
929 }
930
sprang3958ed82017-08-17 08:12:10 -0700931 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -0500932 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700933 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700934 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700935 vp9_info->temporal_idx = kNoTemporalIdx;
936 } else {
937 vp9_info->temporal_idx = layer_id.temporal_layer_id;
938 }
“Michael23c5a992018-06-21 11:07:21 -0500939 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700940 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
Niels Möllerd3b8c632018-08-27 15:33:42 +0200941 *spatial_idx = absl::nullopt;
asaperssona9455ab2015-07-31 06:10:09 -0700942 } else {
Niels Möllerd3b8c632018-08-27 15:33:42 +0200943 *spatial_idx = layer_id.spatial_layer_id;
asaperssona9455ab2015-07-31 06:10:09 -0700944 }
945 if (layer_id.spatial_layer_id != 0) {
946 vp9_info->ss_data_available = false;
947 }
948
asaperssona9455ab2015-07-31 06:10:09 -0700949 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800950 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700951
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200952 const bool is_key_pic = (pics_since_key_ == 0);
953 const bool is_inter_layer_pred_allowed =
954 (inter_layer_pred_ == InterLayerPredMode::kOn ||
955 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
956
957 // Always set inter_layer_predicted to true on high layer frame if inter-layer
958 // prediction (ILP) is allowed even if encoder didn't actually use it.
959 // Setting inter_layer_predicted to false would allow receiver to decode high
960 // layer frame without decoding low layer frame. If that would happen (e.g.
961 // if low layer frame is lost) then receiver won't be able to decode next high
962 // layer frame which uses ILP.
963 vp9_info->inter_layer_predicted =
Sergey Silkin88ce4ef2018-11-23 13:59:24 +0100964 first_frame_in_picture_ ? false : is_inter_layer_pred_allowed;
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200965
Sergey Silkinc5f152d2018-09-26 13:28:50 +0200966 // Mark all low spatial layer frames as references (not just frames of
967 // active low spatial layers) if inter-layer prediction is enabled since
968 // these frames are indirect references of high spatial layer, which can
969 // later be enabled without key frame.
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200970 vp9_info->non_ref_for_inter_layer_pred =
Sergey Silkinc5f152d2018-09-26 13:28:50 +0200971 !is_inter_layer_pred_allowed ||
972 layer_id.spatial_layer_id + 1 == num_spatial_layers_;
asapersson00ac85e2015-11-11 05:30:48 -0800973
ivica7f6a6fc2015-09-08 02:40:29 -0700974 // Always populate this, so that the packetizer can properly set the marker
975 // bit.
“Michael23c5a992018-06-21 11:07:21 -0500976 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800977
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200978 vp9_info->num_ref_pics = 0;
979 if (vp9_info->flexible_mode) {
980 vp9_info->gof_idx = kNoGofIdx;
981 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
982 vp9_info);
983 } else {
984 vp9_info->gof_idx =
985 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
986 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
987 vp9_info->num_ref_pics = gof_.num_ref_pics[vp9_info->gof_idx];
988 }
989
990 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
991
asaperssona9455ab2015-07-31 06:10:09 -0700992 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700993 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -0500994 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +0200995 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800996 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +0200997 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800998 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700999 }
Sergey Silkin738b7e92018-08-23 16:37:27 +02001000 if (vp9_info->flexible_mode) {
1001 vp9_info->gof.num_frames_in_gof = 0;
1002 } else {
asaperssona9455ab2015-07-31 06:10:09 -07001003 vp9_info->gof.CopyGofInfoVP9(gof_);
1004 }
1005 }
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001006
1007 first_frame_in_picture_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001008}
1009
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001010void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
1011 const size_t pic_num,
1012 const bool inter_layer_predicted,
1013 CodecSpecificInfoVP9* vp9_info) {
1014 vpx_svc_layer_id_t layer_id = {0};
1015 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1016
Sergey Silkin76be2952018-08-21 12:30:33 +02001017 const bool is_key_frame =
1018 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001019
1020 std::vector<RefFrameBuffer> ref_buf_list;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001021
Sergey Silkin76be2952018-08-21 12:30:33 +02001022 if (is_svc_) {
1023 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1024 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001025
Sergey Silkin76be2952018-08-21 12:30:33 +02001026 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
1027 const size_t fb_idx =
1028 enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
1029 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001030 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1031 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1032 ref_buf_list.push_back(ref_buf_.at(fb_idx));
1033 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001034 }
1035
1036 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
1037 const size_t fb_idx =
1038 enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
1039 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001040 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1041 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1042 ref_buf_list.push_back(ref_buf_.at(fb_idx));
1043 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001044 }
1045
1046 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
1047 const size_t fb_idx =
1048 enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
1049 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +02001050 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
1051 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
1052 ref_buf_list.push_back(ref_buf_.at(fb_idx));
1053 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001054 }
1055 } else if (!is_key_frame) {
1056 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1057 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1058 // In non-SVC mode encoder doesn't provide reference list. Assume each frame
1059 // refers previous one, which is stored in buffer 0.
1060 ref_buf_list.push_back(ref_buf_.at(0));
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001061 }
1062
1063 size_t max_ref_temporal_layer_id = 0;
1064
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001065 std::vector<size_t> ref_pid_list;
1066
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001067 vp9_info->num_ref_pics = 0;
1068 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
1069 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
1070 if (ref_buf.pic_num < pic_num) {
1071 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
1072 // RTP spec limits temporal prediction to the same spatial layer.
1073 // It is safe to ignore this requirement if inter-layer prediction is
1074 // enabled for all frames when all base frames are relayed to receiver.
1075 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
1076 }
1077 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
1078
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001079 // Encoder may reference several spatial layers on the same previous
1080 // frame in case if some spatial layers are skipped on the current frame.
1081 // We shouldn't put duplicate references as it may break some old
1082 // clients and isn't RTP compatible.
1083 if (std::find(ref_pid_list.begin(), ref_pid_list.end(),
1084 ref_buf.pic_num) != ref_pid_list.end()) {
1085 continue;
1086 }
1087 ref_pid_list.push_back(ref_buf.pic_num);
1088
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001089 const size_t p_diff = pic_num - ref_buf.pic_num;
1090 RTC_DCHECK_LE(p_diff, 127UL);
1091
1092 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
1093 ++vp9_info->num_ref_pics;
1094
1095 max_ref_temporal_layer_id =
1096 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
1097 } else {
1098 RTC_DCHECK(inter_layer_predicted);
1099 // RTP spec only allows to use previous spatial layer for inter-layer
1100 // prediction.
1101 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
1102 }
1103 }
1104
1105 vp9_info->temporal_up_switch =
1106 (max_ref_temporal_layer_id <
1107 static_cast<size_t>(layer_id.temporal_layer_id));
1108}
1109
1110void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
1111 const size_t pic_num) {
1112 vpx_svc_layer_id_t layer_id = {0};
1113 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1114
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001115 const bool is_key_frame =
1116 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1117
1118 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
1119 layer_id.temporal_layer_id);
1120
1121 if (is_key_frame && layer_id.spatial_layer_id == 0) {
1122 // Key frame updates all ref buffers.
1123 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
1124 ref_buf_[i] = frame_buf;
1125 }
Sergey Silkin76be2952018-08-21 12:30:33 +02001126 } else if (is_svc_) {
1127 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
1128 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
1129
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001130 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
1131 if (enc_layer_conf.update_buffer_slot[layer_id.spatial_layer_id] &
1132 (1 << i)) {
1133 ref_buf_[i] = frame_buf;
1134 }
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001135 }
1136
Sergey Silkin76be2952018-08-21 12:30:33 +02001137 } else {
1138 RTC_DCHECK_EQ(num_spatial_layers_, 1);
1139 RTC_DCHECK_EQ(num_temporal_layers_, 1);
1140 // In non-svc mode encoder doesn't provide reference list. Assume each frame
1141 // is reference and stored in buffer 0.
1142 ref_buf_[0] = frame_buf;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001143 }
1144}
1145
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001146vpx_svc_ref_frame_config_t VP9EncoderImpl::SetReferences(
1147 bool is_key_pic,
1148 size_t first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001149 // kRefBufIdx, kUpdBufIdx need to be updated to support longer GOFs.
1150 RTC_DCHECK_LE(gof_.num_frames_in_gof, 4);
1151
1152 vpx_svc_ref_frame_config_t ref_config;
1153 memset(&ref_config, 0, sizeof(ref_config));
1154
1155 const size_t num_temporal_refs = std::max(1, num_temporal_layers_ - 1);
1156 const bool is_inter_layer_pred_allowed =
1157 inter_layer_pred_ == InterLayerPredMode::kOn ||
1158 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic);
1159 absl::optional<int> last_updated_buf_idx;
1160
1161 // Put temporal reference to LAST and spatial reference to GOLDEN. Update
1162 // frame buffer (i.e. store encoded frame) if current frame is a temporal
1163 // reference (i.e. it belongs to a low temporal layer) or it is a spatial
1164 // reference. In later case, always store spatial reference in the last
1165 // reference frame buffer.
1166 // For the case of 3 temporal and 3 spatial layers we need 6 frame buffers
1167 // for temporal references plus 1 buffer for spatial reference. 7 buffers
1168 // in total.
1169
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001170 for (size_t sl_idx = first_active_spatial_layer_id;
1171 sl_idx < num_active_spatial_layers_; ++sl_idx) {
1172 const size_t curr_pic_num = is_key_pic ? 0 : pics_since_key_ + 1;
1173 const size_t gof_idx = curr_pic_num % gof_.num_frames_in_gof;
Sergey Silkin390f3582018-10-01 17:13:50 +02001174
1175 if (!is_key_pic) {
1176 // Set up temporal reference.
1177 const int buf_idx = sl_idx * num_temporal_refs + kRefBufIdx[gof_idx];
1178
1179 // Last reference frame buffer is reserved for spatial reference. It is
1180 // not supposed to be used for temporal prediction.
1181 RTC_DCHECK_LT(buf_idx, kNumVp9Buffers - 1);
1182
1183 // Sanity check that reference picture number is smaller than current
1184 // picture number.
Sergey Silkin390f3582018-10-01 17:13:50 +02001185 RTC_DCHECK_LT(ref_buf_[buf_idx].pic_num, curr_pic_num);
1186 const size_t pid_diff = curr_pic_num - ref_buf_[buf_idx].pic_num;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001187 // Incorrect spatial layer may be in the buffer due to a key-frame.
1188 const bool same_spatial_layer =
1189 ref_buf_[buf_idx].spatial_layer_id == sl_idx;
1190 bool correct_pid = false;
1191 if (different_framerates_used_) {
1192 correct_pid = pid_diff < kMaxAllowedPidDIff;
1193 } else {
1194 // Below code assumes single temporal referecence.
1195 RTC_DCHECK_EQ(gof_.num_ref_pics[gof_idx], 1);
1196 correct_pid = pid_diff == gof_.pid_diff[gof_idx][0];
1197 }
Sergey Silkin390f3582018-10-01 17:13:50 +02001198
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001199 if (same_spatial_layer && correct_pid) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001200 ref_config.lst_fb_idx[sl_idx] = buf_idx;
1201 ref_config.reference_last[sl_idx] = 1;
1202 } else {
1203 // This reference doesn't match with one specified by GOF. This can
1204 // only happen if spatial layer is enabled dynamically without key
1205 // frame. Spatial prediction is supposed to be enabled in this case.
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001206 RTC_DCHECK(is_inter_layer_pred_allowed &&
1207 sl_idx > first_active_spatial_layer_id);
Sergey Silkin390f3582018-10-01 17:13:50 +02001208 }
1209 }
1210
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001211 if (is_inter_layer_pred_allowed && sl_idx > first_active_spatial_layer_id) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001212 // Set up spatial reference.
1213 RTC_DCHECK(last_updated_buf_idx);
1214 ref_config.gld_fb_idx[sl_idx] = *last_updated_buf_idx;
1215 ref_config.reference_golden[sl_idx] = 1;
1216 } else {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001217 RTC_DCHECK(ref_config.reference_last[sl_idx] != 0 ||
1218 sl_idx == first_active_spatial_layer_id ||
Sergey Silkin390f3582018-10-01 17:13:50 +02001219 inter_layer_pred_ == InterLayerPredMode::kOff);
1220 }
1221
1222 last_updated_buf_idx.reset();
1223
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +01001224 if (gof_.temporal_idx[gof_idx] < num_temporal_layers_ - 1 ||
1225 num_temporal_layers_ == 1) {
Sergey Silkin390f3582018-10-01 17:13:50 +02001226 last_updated_buf_idx = sl_idx * num_temporal_refs + kUpdBufIdx[gof_idx];
1227
1228 // Ensure last frame buffer is not used for temporal prediction (it is
1229 // reserved for spatial reference).
1230 RTC_DCHECK_LT(*last_updated_buf_idx, kNumVp9Buffers - 1);
1231 } else if (is_inter_layer_pred_allowed) {
1232 last_updated_buf_idx = kNumVp9Buffers - 1;
1233 }
1234
1235 if (last_updated_buf_idx) {
1236 ref_config.update_buffer_slot[sl_idx] = 1 << *last_updated_buf_idx;
1237 }
1238 }
1239
1240 return ref_config;
1241}
1242
asaperssona9455ab2015-07-31 06:10:09 -07001243int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -08001244 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -07001245
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001246 if (pkt->data.frame.sz == 0) {
1247 // Ignore dropped frame.
1248 return WEBRTC_VIDEO_CODEC_OK;
1249 }
1250
Sergey Silkin07f80cc2018-04-09 13:11:59 +02001251 vpx_svc_layer_id_t layer_id = {0};
1252 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
1253
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001254 if (!full_superframe_drop_) {
1255 // Deliver buffered low spatial layer frame.
1256 const bool end_of_picture = false;
1257 DeliverBufferedFrame(end_of_picture);
1258 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001259
asaperssond9f641e2016-01-21 01:11:35 -08001260 if (pkt->data.frame.sz > encoded_image_._size) {
1261 delete[] encoded_image_._buffer;
1262 encoded_image_._size = pkt->data.frame.sz;
1263 encoded_image_._buffer = new uint8_t[encoded_image_._size];
1264 }
asapersson86956de2016-01-26 01:05:20 -08001265 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
1266 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -08001267
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001268 const bool is_key_frame =
1269 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1270 // Ensure encoder issued key frame on request.
1271 RTC_DCHECK(is_key_frame || !force_key_frame_);
1272
asaperssona9455ab2015-07-31 06:10:09 -07001273 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -08001274 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001275 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +02001276 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001277 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001278 }
asapersson86956de2016-01-26 01:05:20 -08001279 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
1280
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001281 memset(&codec_specific_, 0, sizeof(codec_specific_));
Niels Möllerd3b8c632018-08-27 15:33:42 +02001282 absl::optional<int> spatial_index;
1283 PopulateCodecSpecific(&codec_specific_, &spatial_index, *pkt,
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001284 input_image_->timestamp());
Niels Möllerd3b8c632018-08-27 15:33:42 +02001285 encoded_image_.SetSpatialIndex(spatial_index);
asaperssona9455ab2015-07-31 06:10:09 -07001286
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001287 if (is_flexible_mode_) {
1288 UpdateReferenceBuffers(*pkt, pics_since_key_);
1289 }
1290
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001291 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
Niels Möller23775882018-08-16 10:24:12 +02001292 encoded_image_.SetTimestamp(input_image_->timestamp());
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001293 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
1294 encoded_image_.rotation_ = input_image_->rotation();
Niels Möllere3cf3d02018-06-13 11:52:16 +02001295 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001296 ? VideoContentType::SCREENSHARE
1297 : VideoContentType::UNSPECIFIED;
1298 encoded_image_._encodedHeight =
1299 pkt->data.frame.height[layer_id.spatial_layer_id];
1300 encoded_image_._encodedWidth =
1301 pkt->data.frame.width[layer_id.spatial_layer_id];
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +02001302 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001303 int qp = -1;
1304 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
1305 encoded_image_.qp_ = qp;
Johannes Kron4749e4e2018-11-21 10:18:18 +01001306 encoded_image_.SetColorSpace(input_image_->color_space());
ilnik04f4d122017-06-19 07:18:55 -07001307
Sergey Silkin88ce4ef2018-11-23 13:59:24 +01001308 if (full_superframe_drop_) {
1309 const bool end_of_picture = encoded_image_.SpatialIndex().value_or(0) + 1 ==
1310 num_active_spatial_layers_;
1311 DeliverBufferedFrame(end_of_picture);
1312 }
1313
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001314 return WEBRTC_VIDEO_CODEC_OK;
1315}
1316
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001317void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001318 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001319 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001320
1321 // No data partitioning in VP9, so 1 partition only.
1322 int part_idx = 0;
1323 RTPFragmentationHeader frag_info;
1324 frag_info.VerifyAndAllocateFragmentationHeader(1);
1325 frag_info.fragmentationOffset[part_idx] = 0;
1326 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
1327 frag_info.fragmentationPlType[part_idx] = 0;
1328 frag_info.fragmentationTimeDiff[part_idx] = 0;
1329
1330 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
1331 &frag_info);
1332 encoded_image_._length = 0;
Sergey Silkind902d582018-05-18 17:31:19 +02001333
Sergey Silkin96f2c972018-09-05 21:07:17 +02001334 if (codec_.mode == VideoCodecMode::kScreensharing) {
1335 const uint8_t spatial_idx = encoded_image_.SpatialIndex().value_or(0);
1336 const uint32_t frame_timestamp_ms =
Niels Möller23775882018-08-16 10:24:12 +02001337 1000 * encoded_image_.Timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkin96f2c972018-09-05 21:07:17 +02001338 framerate_controller_[spatial_idx].AddFrame(frame_timestamp_ms);
Sergey Silkind902d582018-05-18 17:31:19 +02001339 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001340 }
1341}
1342
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001343int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1344 EncodedImageCallback* callback) {
1345 encoded_complete_callback_ = callback;
1346 return WEBRTC_VIDEO_CODEC_OK;
1347}
1348
Erik Språng727d1642018-11-07 16:54:15 +01001349VideoEncoder::EncoderInfo VP9EncoderImpl::GetEncoderInfo() const {
1350 EncoderInfo info;
1351 info.supports_native_handle = false;
1352 info.implementation_name = "libvpx";
1353 info.scaling_settings = VideoEncoder::ScalingSettings::kOff;
Erik Språngd3438aa2018-11-08 16:56:43 +01001354 info.has_trusted_rate_controller = trusted_rate_controller_;
Mirta Dvornicic897a9912018-11-30 13:12:21 +01001355 info.is_hardware_accelerated = false;
1356 info.has_internal_source = false;
Erik Språng727d1642018-11-07 16:54:15 +01001357 return info;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001358}
1359
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001360VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001361 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001362 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001363 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001364 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001365
1366VP9DecoderImpl::~VP9DecoderImpl() {
1367 inited_ = true; // in order to do the actual release
1368 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001369 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1370 if (num_buffers_in_use > 0) {
1371 // The frame buffers are reference counted and frames are exposed after
1372 // decoding. There may be valid usage cases where previous frames are still
1373 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001374 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1375 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001376 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001377}
1378
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001379int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001380 int ret_val = Release();
1381 if (ret_val < 0) {
1382 return ret_val;
1383 }
Sergey Silkinb674cd12018-10-09 10:59:06 +02001384
sprang3958ed82017-08-17 08:12:10 -07001385 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001386 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001387 }
philipelcce46fc2015-12-21 03:04:49 -08001388 vpx_codec_dec_cfg_t cfg;
Sergey Silkinb674cd12018-10-09 10:59:06 +02001389 memset(&cfg, 0, sizeof(cfg));
1390
1391 // We want to use multithreading when decoding high resolution videos. But,
1392 // since we don't know resolution of input stream at this stage, we always
1393 // enable it.
1394 cfg.threads = std::min(number_of_cores, kMaxNumTiles4kVideo);
1395
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001396 vpx_codec_flags_t flags = 0;
1397 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1398 return WEBRTC_VIDEO_CODEC_MEMORY;
1399 }
Henrik Boström9695d852015-05-06 10:42:15 +02001400
1401 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1402 return WEBRTC_VIDEO_CODEC_MEMORY;
1403 }
1404
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001405 inited_ = true;
1406 // Always start with a complete key frame.
1407 key_frame_required_ = true;
1408 return WEBRTC_VIDEO_CODEC_OK;
1409}
1410
1411int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1412 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001413 const CodecSpecificInfo* codec_specific_info,
1414 int64_t /*render_time_ms*/) {
1415 if (!inited_) {
1416 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1417 }
sprang3958ed82017-08-17 08:12:10 -07001418 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001419 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1420 }
1421 // Always start with a complete key frame.
1422 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +02001423 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001424 return WEBRTC_VIDEO_CODEC_ERROR;
1425 // We have a key frame - is it complete?
1426 if (input_image._completeFrame) {
1427 key_frame_required_ = false;
1428 } else {
1429 return WEBRTC_VIDEO_CODEC_ERROR;
1430 }
1431 }
sprang3958ed82017-08-17 08:12:10 -07001432 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001433 vpx_image_t* img;
1434 uint8_t* buffer = input_image._buffer;
1435 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -07001436 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001437 }
Henrik Boström9695d852015-05-06 10:42:15 +02001438 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1439 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001440 if (vpx_codec_decode(decoder_, buffer,
1441 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001442 VPX_DL_REALTIME)) {
1443 return WEBRTC_VIDEO_CODEC_ERROR;
1444 }
Henrik Boström9695d852015-05-06 10:42:15 +02001445 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1446 // It may be released by libvpx during future vpx_codec_decode or
1447 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001448 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001449 int qp;
1450 vpx_codec_err_t vpx_ret =
1451 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1452 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
Johannes Kron9973fa82018-11-07 14:39:26 +01001453 int ret = ReturnFrame(img, input_image.Timestamp(), input_image.ntp_time_ms_,
Johannes Kron4749e4e2018-11-21 10:18:18 +01001454 qp, input_image.ColorSpace());
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001455 if (ret != 0) {
1456 return ret;
1457 }
1458 return WEBRTC_VIDEO_CODEC_OK;
1459}
1460
asapersson1490f7a2016-09-23 02:09:46 -07001461int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
1462 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -08001463 int64_t ntp_time_ms,
Johannes Kron9973fa82018-11-07 14:39:26 +01001464 int qp,
Johannes Kron4749e4e2018-11-21 10:18:18 +01001465 const ColorSpace* explicit_color_space) {
sprang3958ed82017-08-17 08:12:10 -07001466 if (img == nullptr) {
1467 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001468 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1469 }
Henrik Boström9695d852015-05-06 10:42:15 +02001470
1471 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001472 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001473 // vpx_codec_decode calls or vpx_codec_destroy).
1474 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1475 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001476
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001477 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001478 // using a Wrapped*Buffer.
1479 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1480 switch (img->bit_depth) {
1481 case 8:
1482 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001483 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1484 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1485 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1486 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001487 // WrappedI420Buffer's mechanism for allowing the release of its frame
1488 // buffer is through a callback function. This is where we should
1489 // release |img_buffer|.
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001490 rtc::KeepRefUntilDone(img_buffer));
1491 break;
1492 case 10:
1493 img_wrapped_buffer = WrapI010Buffer(
1494 img->d_w, img->d_h,
1495 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1496 img->stride[VPX_PLANE_Y] / 2,
1497 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1498 img->stride[VPX_PLANE_U] / 2,
1499 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1500 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1501 break;
1502 default:
1503 RTC_NOTREACHED();
1504 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1505 }
nisseca6d5d12016-06-17 05:03:04 -07001506
Johannes Kron4749e4e2018-11-21 10:18:18 +01001507 auto builder = VideoFrame::Builder()
1508 .set_video_frame_buffer(img_wrapped_buffer)
1509 .set_timestamp_ms(0)
1510 .set_timestamp_rtp(timestamp)
1511 .set_ntp_time_ms(ntp_time_ms)
1512 .set_rotation(webrtc::kVideoRotation_0);
1513 if (explicit_color_space) {
1514 builder.set_color_space(explicit_color_space);
1515 } else {
1516 builder.set_color_space(
1517 ExtractVP9ColorSpace(img->cs, img->range, img->bit_depth));
1518 }
1519
1520 VideoFrame decoded_image = builder.build();
1521
Danil Chapovalov0040b662018-06-18 10:48:16 +02001522 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001523 return WEBRTC_VIDEO_CODEC_OK;
1524}
1525
1526int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1527 DecodedImageCallback* callback) {
1528 decode_complete_callback_ = callback;
1529 return WEBRTC_VIDEO_CODEC_OK;
1530}
1531
1532int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001533 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1534
sprang3958ed82017-08-17 08:12:10 -07001535 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001536 if (inited_) {
1537 // When a codec is destroyed libvpx will release any buffers of
1538 // |frame_buffer_pool_| it is currently using.
1539 if (vpx_codec_destroy(decoder_)) {
1540 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1541 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001542 }
1543 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001544 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001545 }
Henrik Boström9695d852015-05-06 10:42:15 +02001546 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1547 // still referenced externally are deleted once fully released, not returning
1548 // to the pool.
1549 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001550 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001551 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001552}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001553
1554const char* VP9DecoderImpl::ImplementationName() const {
1555 return "libvpx";
1556}
1557
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001558} // namespace webrtc
Mirko Bonadei95adedb2018-11-19 09:52:37 +01001559
1560#endif // RTC_ENABLE_VP9