blob: 56ff936bc1e29295a5bce33a2bf155d11049c45e [file] [log] [blame]
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001/*
2 * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 *
10 */
11
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020012#include "modules/video_coding/codecs/vp9/vp9_impl.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000013
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +020014#include <algorithm>
Sergey Silkind45b3452018-05-31 16:00:24 +020015#include <limits>
marpan@webrtc.org5b883172014-11-01 06:10:48 +000016#include <vector>
17
marpan@webrtc.org5b883172014-11-01 06:10:48 +000018#include "vpx/vp8cx.h"
19#include "vpx/vp8dx.h"
Yves Gerey665174f2018-06-19 15:03:05 +020020#include "vpx/vpx_decoder.h"
21#include "vpx/vpx_encoder.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000022
Karl Wiberg918f50c2018-07-05 11:40:33 +020023#include "absl/memory/memory.h"
Emircan Uysaler0823eec2018-07-13 17:10:00 -070024#include "api/video/i010_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "common_video/include/video_frame_buffer.h"
26#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkind902d582018-05-18 17:31:19 +020027#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020028#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/checks.h"
30#include "rtc_base/keep_ref_until_done.h"
31#include "rtc_base/logging.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/timeutils.h"
33#include "rtc_base/trace_event.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000034
35namespace webrtc {
36
Sergey Silkind902d582018-05-18 17:31:19 +020037namespace {
38const float kMaxScreenSharingFramerateFps = 5.0f;
39}
40
Marco6e89b252015-07-07 14:40:38 -070041// Only positive speeds, range for real-time coding currently is: 5 - 8.
42// Lower means slower/better quality, higher means fastest/lower quality.
43int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070044#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080045 return 8;
46#else
Marco6e89b252015-07-07 14:40:38 -070047 // For smaller resolutions, use lower speed setting (get some coding gain at
48 // the cost of increased encoding complexity).
49 if (width * height <= 352 * 288)
50 return 5;
51 else
52 return 7;
Marco002f0d02015-12-17 09:49:31 -080053#endif
Marco6e89b252015-07-07 14:40:38 -070054}
55
Emircan Uysaler98badbc2018-06-28 10:59:02 -070056std::vector<SdpVideoFormat> SupportedVP9Codecs() {
Emircan Uysaler0823eec2018-07-13 17:10:00 -070057 // TODO(emircan): Add Profile 2 support after fixing browser_tests.
58 std::vector<SdpVideoFormat> supported_formats{SdpVideoFormat(
59 cricket::kVp9CodecName,
60 {{kVP9FmtpProfileId, VP9ProfileToString(VP9Profile::kProfile0)}})};
61 return supported_formats;
Peter Boström12996152016-05-14 02:03:18 +020062}
63
Magnus Jedvert46a27652017-11-13 14:10:02 +010064std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +020065 return absl::make_unique<VP9EncoderImpl>(cricket::VideoCodec());
Emircan Uysaler98badbc2018-06-28 10:59:02 -070066}
67
68std::unique_ptr<VP9Encoder> VP9Encoder::Create(
69 const cricket::VideoCodec& codec) {
Karl Wiberg918f50c2018-07-05 11:40:33 +020070 return absl::make_unique<VP9EncoderImpl>(codec);
marpan@webrtc.org5b883172014-11-01 06:10:48 +000071}
72
asaperssona9455ab2015-07-31 06:10:09 -070073void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
74 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -080075 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -070076 enc->GetEncodedLayerFrame(pkt);
77}
78
Emircan Uysaler98badbc2018-06-28 10:59:02 -070079VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +000080 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -070081 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -070082 profile_(
83 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000084 inited_(false),
85 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000086 cpu_speed_(3),
87 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -070088 encoder_(nullptr),
89 config_(nullptr),
90 raw_(nullptr),
91 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +020092 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020093 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -070094 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -080095 num_spatial_layers_(0),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +020096 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020097 inter_layer_pred_(InterLayerPredMode::kOn),
Sergey Silkind902d582018-05-18 17:31:19 +020098 output_framerate_(1000.0, 1000.0),
99 last_encoded_frame_rtp_timestamp_(0),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200100 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000101 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -0800102 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000103}
104
105VP9EncoderImpl::~VP9EncoderImpl() {
106 Release();
107}
108
109int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100110 int ret_val = WEBRTC_VIDEO_CODEC_OK;
111
sprang3958ed82017-08-17 08:12:10 -0700112 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800113 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -0700114 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000115 }
sprang3958ed82017-08-17 08:12:10 -0700116 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100117 if (inited_) {
118 if (vpx_codec_destroy(encoder_)) {
119 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
120 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000121 }
122 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700123 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000124 }
sprang3958ed82017-08-17 08:12:10 -0700125 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000126 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700127 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000128 }
sprang3958ed82017-08-17 08:12:10 -0700129 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000130 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700131 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000132 }
133 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100134 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000135}
136
sprangce4aef12015-11-02 07:23:20 -0800137bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
138 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
139 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100140 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800141}
142
Erik Språng566124a2018-04-23 12:32:22 +0200143bool VP9EncoderImpl::SetSvcRates(
144 const VideoBitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700145 uint8_t i = 0;
146
Sergey Silkin86684962018-03-28 19:32:37 +0200147 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200148
“Michael23c5a992018-06-21 11:07:21 -0500149 num_active_spatial_layers_ = 0;
150 for (i = 0; i < num_spatial_layers_; ++i)
151 num_active_spatial_layers_ += bitrate_allocation.IsSpatialLayerUsed(i);
152 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
153 RTC_DCHECK_LE(num_active_spatial_layers_, num_spatial_layers_);
154
sprangce4aef12015-11-02 07:23:20 -0800155 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200156 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200157 const bool was_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200158 config_->ss_target_bitrate[sl_idx] =
159 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
160
161 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
162 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
163 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
164 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200165
166 const bool is_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
167 if (is_layer_enabled && !was_layer_enabled) {
168 if (inter_layer_pred_ == InterLayerPredMode::kOff ||
169 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic) {
170 // TODO(wemb:1526): remove key frame request when issue is fixed.
171 force_key_frame_ = true;
172 }
173 }
sprangce4aef12015-11-02 07:23:20 -0800174 }
175 } else {
176 float rate_ratio[VPX_MAX_LAYERS] = {0};
177 float total = 0;
“Michael67c8bcf2018-06-27 04:24:13 -0500178 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800179 if (svc_params_.scaling_factor_num[i] <= 0 ||
180 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100181 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800182 return false;
183 }
Yves Gerey665174f2018-06-19 15:03:05 +0200184 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
185 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800186 total += rate_ratio[i];
187 }
188
“Michael67c8bcf2018-06-27 04:24:13 -0500189 for (i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200190 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800191 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
192 config_->rc_target_bitrate * rate_ratio[i] / total);
193 if (num_temporal_layers_ == 1) {
194 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
195 } else if (num_temporal_layers_ == 2) {
196 config_->layer_target_bitrate[i * num_temporal_layers_] =
197 config_->ss_target_bitrate[i] * 2 / 3;
198 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
199 config_->ss_target_bitrate[i];
200 } else if (num_temporal_layers_ == 3) {
201 config_->layer_target_bitrate[i * num_temporal_layers_] =
202 config_->ss_target_bitrate[i] / 2;
203 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
204 config_->layer_target_bitrate[i * num_temporal_layers_] +
205 (config_->ss_target_bitrate[i] / 4);
206 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
207 config_->ss_target_bitrate[i];
208 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100209 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
210 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800211 return false;
212 }
asaperssona9455ab2015-07-31 06:10:09 -0700213 }
214 }
asaperssona9455ab2015-07-31 06:10:09 -0700215 return true;
216}
217
Erik Språng08127a92016-11-16 16:41:30 +0100218int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200219 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100220 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000221 if (!inited_) {
222 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
223 }
224 if (encoder_->err) {
225 return WEBRTC_VIDEO_CODEC_ERROR;
226 }
Erik Språng08127a92016-11-16 16:41:30 +0100227 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000228 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
229 }
230 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100231 if (codec_.maxBitrate > 0 &&
232 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
233 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000234 }
Erik Språng08127a92016-11-16 16:41:30 +0100235
Erik Språng08127a92016-11-16 16:41:30 +0100236 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700237
Sergey Silkin86684962018-03-28 19:32:37 +0200238 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700239 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
240 }
241
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000242 // Update encoder context
243 if (vpx_codec_enc_config_set(encoder_, config_)) {
244 return WEBRTC_VIDEO_CODEC_ERROR;
245 }
246 return WEBRTC_VIDEO_CODEC_OK;
247}
248
249int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
250 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000251 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700252 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000253 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
254 }
255 if (inst->maxFramerate < 1) {
256 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
257 }
258 // Allow zero to represent an unspecified maxBitRate
259 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
260 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
261 }
262 if (inst->width < 1 || inst->height < 1) {
263 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
264 }
265 if (number_of_cores < 1) {
266 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
267 }
hta257dc392016-10-25 09:05:06 -0700268 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700269 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
270 }
ilnik2a8c2f52017-02-15 02:23:28 -0800271 // libvpx probably does not support more than 3 spatial layers.
272 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700273 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
274 }
philipelcfc319b2015-11-10 07:17:23 -0800275
asapersson86956de2016-01-26 01:05:20 -0800276 int ret_val = Release();
277 if (ret_val < 0) {
278 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000279 }
sprang3958ed82017-08-17 08:12:10 -0700280 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000281 encoder_ = new vpx_codec_ctx_t;
282 }
sprang3958ed82017-08-17 08:12:10 -0700283 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000284 config_ = new vpx_codec_enc_cfg_t;
285 }
286 timestamp_ = 0;
287 if (&codec_ != inst) {
288 codec_ = *inst;
289 }
asaperssona9455ab2015-07-31 06:10:09 -0700290
hta257dc392016-10-25 09:05:06 -0700291 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200292 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700293 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700294 if (num_temporal_layers_ == 0)
295 num_temporal_layers_ = 1;
296
Sergey Silkind902d582018-05-18 17:31:19 +0200297 // Init framerate controller.
298 output_framerate_.Reset();
Niels Möllere3cf3d02018-06-13 11:52:16 +0200299 if (codec_.mode == VideoCodecMode::kScreensharing) {
Sergey Silkind902d582018-05-18 17:31:19 +0200300 target_framerate_fps_ = kMaxScreenSharingFramerateFps;
301 } else {
302 target_framerate_fps_.reset();
303 }
304
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200305 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
306 // Flexible mode requires SVC to be enabled since libvpx API only allows
307 // to get reference list in SVC mode.
308 RTC_DCHECK(!inst->VP9().flexibleMode || is_svc_);
309
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000310 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700311 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800312 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000313 }
nisseeb44b392017-04-28 07:18:05 -0700314 encoded_image_._size =
315 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000316 encoded_image_._buffer = new uint8_t[encoded_image_._size];
317 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000318 // Populate encoder configuration with default values.
319 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
320 return WEBRTC_VIDEO_CODEC_ERROR;
321 }
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700322
323 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
324 unsigned int bits_for_storage = 8;
325 switch (profile_) {
326 case VP9Profile::kProfile0:
327 img_fmt = VPX_IMG_FMT_I420;
328 bits_for_storage = 8;
329 config_->g_bit_depth = VPX_BITS_8;
330 config_->g_profile = 0;
331 config_->g_input_bit_depth = 8;
332 break;
333 case VP9Profile::kProfile2:
334 img_fmt = VPX_IMG_FMT_I42016;
335 bits_for_storage = 16;
336 config_->g_bit_depth = VPX_BITS_10;
337 config_->g_profile = 2;
338 config_->g_input_bit_depth = 10;
339 break;
340 }
341
342 // Creating a wrapper to the image - setting image data to nullptr. Actual
343 // pointer will be set in encode. Setting align to 1, as it is meaningless
344 // (actual memory is not allocated).
345 raw_ =
346 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
347 raw_->bit_depth = bits_for_storage;
348
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000349 config_->g_w = codec_.width;
350 config_->g_h = codec_.height;
351 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200352 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000353 // Setting the time base of the codec.
354 config_->g_timebase.num = 1;
355 config_->g_timebase.den = 90000;
356 config_->g_lag_in_frames = 0; // 0- no frame lagging
357 config_->g_threads = 1;
358 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700359 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000360 config_->rc_end_usage = VPX_CBR;
361 config_->g_pass = VPX_RC_ONE_PASS;
362 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000363 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000364 config_->rc_undershoot_pct = 50;
365 config_->rc_overshoot_pct = 50;
366 config_->rc_buf_initial_sz = 500;
367 config_->rc_buf_optimal_sz = 600;
368 config_->rc_buf_sz = 1000;
369 // Set the maximum target size of any key-frame.
370 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700371 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000372 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700373 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100374 // Needs to be set (in svc mode) to get correct periodic key frame interval
375 // (will have no effect in non-svc).
376 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000377 } else {
378 config_->kf_mode = VPX_KF_DISABLED;
379 }
hta257dc392016-10-25 09:05:06 -0700380 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000381 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800382 config_->g_threads =
383 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700384
Marco6e89b252015-07-07 14:40:38 -0700385 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700386
387 // TODO(asapersson): Check configuration of temporal switch up and increase
388 // pattern length.
hta257dc392016-10-25 09:05:06 -0700389 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200390
391 // TODO(ssilkin): Only non-flexible mode is supported for now.
392 RTC_DCHECK(!is_flexible_mode_);
393
394 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700395 gof_.SetGofInfoVP9(kTemporalStructureMode1);
396 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
397 config_->ts_number_layers = 1;
398 config_->ts_rate_decimator[0] = 1;
399 config_->ts_periodicity = 1;
400 config_->ts_layer_id[0] = 0;
401 } else if (num_temporal_layers_ == 2) {
402 gof_.SetGofInfoVP9(kTemporalStructureMode2);
403 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
404 config_->ts_number_layers = 2;
405 config_->ts_rate_decimator[0] = 2;
406 config_->ts_rate_decimator[1] = 1;
407 config_->ts_periodicity = 2;
408 config_->ts_layer_id[0] = 0;
409 config_->ts_layer_id[1] = 1;
410 } else if (num_temporal_layers_ == 3) {
411 gof_.SetGofInfoVP9(kTemporalStructureMode3);
412 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
413 config_->ts_number_layers = 3;
414 config_->ts_rate_decimator[0] = 4;
415 config_->ts_rate_decimator[1] = 2;
416 config_->ts_rate_decimator[2] = 1;
417 config_->ts_periodicity = 4;
418 config_->ts_layer_id[0] = 0;
419 config_->ts_layer_id[1] = 2;
420 config_->ts_layer_id[2] = 1;
421 config_->ts_layer_id[3] = 2;
422 } else {
423 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
424 }
425
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200426 inter_layer_pred_ = inst->VP9().interLayerPred;
427
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200428 ref_buf_.clear();
429
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000430 return InitAndSetControlSettings(inst);
431}
432
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000433int VP9EncoderImpl::NumberOfThreads(int width,
434 int height,
435 int number_of_cores) {
436 // Keep the number of encoder threads equal to the possible number of column
437 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
438 if (width * height >= 1280 * 720 && number_of_cores > 4) {
439 return 4;
jianj23173a32017-07-12 16:11:09 -0700440 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000441 return 2;
442 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200443// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800444#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
445 defined(WEBRTC_ANDROID)
446 if (width * height >= 320 * 180 && number_of_cores > 2) {
447 return 2;
448 }
449#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000450 // 1 thread less than VGA.
451 return 1;
452 }
453}
454
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000455int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100456 // Set QP-min/max per spatial and temporal layer.
457 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
458 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800459 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
460 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100461 }
asaperssona9455ab2015-07-31 06:10:09 -0700462 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800463 if (ExplicitlyConfiguredSpatialLayers()) {
464 for (int i = 0; i < num_spatial_layers_; ++i) {
465 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200466 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100467 const int scale_factor = codec_.width / layer.width;
468 RTC_DCHECK_GT(scale_factor, 0);
469
470 // Ensure scaler factor is integer.
471 if (scale_factor * layer.width != codec_.width) {
472 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
473 }
474
475 // Ensure scale factor is the same in both dimensions.
476 if (scale_factor * layer.height != codec_.height) {
477 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
478 }
479
480 // Ensure scale factor is power of two.
481 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
482 if (!is_pow_of_two) {
483 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
484 }
485
486 svc_params_.scaling_factor_num[i] = 1;
487 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800488 }
489 } else {
490 int scaling_factor_num = 256;
491 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800492 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800493 svc_params_.scaling_factor_num[i] = scaling_factor_num;
494 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800495 }
asaperssona9455ab2015-07-31 06:10:09 -0700496 }
497
Sergey Silkin86684962018-03-28 19:32:37 +0200498 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200499 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200500 inst->startBitrate * 1000, inst->maxFramerate);
501 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700502 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
503 }
504
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700505 const vpx_codec_err_t rv = vpx_codec_enc_init(
506 encoder_, vpx_codec_vp9_cx(), config_,
507 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
508 if (rv != VPX_CODEC_OK) {
509 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000510 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
511 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000512 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
513 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
514 rc_max_intra_target_);
515 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700516 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700517
jianj822e5932017-07-12 16:09:58 -0700518 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200519
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200520 if (is_svc_) {
521 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
522 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700523 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200524
525 if (num_spatial_layers_ > 1) {
526 switch (inter_layer_pred_) {
527 case InterLayerPredMode::kOn:
528 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
529 break;
530 case InterLayerPredMode::kOff:
531 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
532 break;
533 case InterLayerPredMode::kOnKeyPic:
534 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
535 break;
536 default:
537 RTC_NOTREACHED();
538 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200539
Sergey Silkinee203362018-05-30 11:34:08 +0200540 // Configure encoder to drop entire superframe whenever it needs to drop
541 // a layer. This mode is prefered over per-layer dropping which causes
542 // quality flickering and is not compatible with RTP non-flexible mode.
543 vpx_svc_frame_drop_t svc_drop_frame;
544 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
545 svc_drop_frame.framedrop_mode = FULL_SUPERFRAME_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200546 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200547 for (size_t i = 0; i < num_spatial_layers_; ++i) {
548 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200549 }
Sergey Silkinee203362018-05-30 11:34:08 +0200550 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200551 }
552
asaperssona9455ab2015-07-31 06:10:09 -0700553 // Register callback for getting each spatial layer.
554 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800555 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
556 reinterpret_cast<void*>(this)};
557 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
558 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700559
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000560 // Control function to set the number of column tiles in encoding a frame, in
561 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
562 // The number tile columns will be capped by the encoder based on image size
563 // (minimum width of tile column is 256 pixels, maximum is 4096).
564 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700565
566 // Turn on row-based multithreading.
567 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700568
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700569#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200570 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700571 // Do not enable the denoiser on ARM since optimization is pending.
572 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000573 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700574 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000575#endif
jianj6bf57e32017-06-05 13:43:49 -0700576
Niels Möllere3cf3d02018-06-13 11:52:16 +0200577 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700578 // Adjust internal parameters to screen content.
579 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700580 }
Marco2520e722015-09-16 14:05:00 -0700581 // Enable encoder skip of static/low content blocks.
582 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000583 inited_ = true;
584 return WEBRTC_VIDEO_CODEC_OK;
585}
586
587uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
588 // Set max to the optimal buffer level (normalized by target BR),
589 // and scaled by a scale_par.
590 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
591 // This value is presented in percentage of perFrameBw:
592 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
593 // The target in % is as follows:
594 float scale_par = 0.5;
595 uint32_t target_pct =
596 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
597 // Don't go below 3 times the per frame bandwidth.
598 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800599 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000600}
601
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700602int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000603 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700604 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000605 if (!inited_) {
606 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
607 }
sprang3958ed82017-08-17 08:12:10 -0700608 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000609 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
610 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200611
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000612 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200613 if (frame_types && !frame_types->empty()) {
614 if ((*frame_types)[0] == kVideoFrameKey) {
615 force_key_frame_ = true;
616 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000617 }
Sergey Silkind902d582018-05-18 17:31:19 +0200618
Niels Möllere3cf3d02018-06-13 11:52:16 +0200619 if (VideoCodecMode::kScreensharing == codec_.mode && !force_key_frame_) {
Sergey Silkind902d582018-05-18 17:31:19 +0200620 if (DropFrame(input_image.timestamp())) {
621 return WEBRTC_VIDEO_CODEC_OK;
622 }
623 }
624
kwiberg352444f2016-11-28 15:58:53 -0800625 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
626 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700627
628 // Set input image for use in the callback.
629 // This was necessary since you need some information from input_image.
630 // You can save only the necessary information (such as timestamp) instead of
631 // doing this.
632 input_image_ = &input_image;
633
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700634 // Keep reference to buffer until encode completes.
635 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
636 rtc::scoped_refptr<I010BufferInterface> i010_buffer;
637 switch (profile_) {
638 case VP9Profile::kProfile0: {
639 i420_buffer = input_image.video_frame_buffer()->ToI420();
640 // Image in vpx_image_t format.
641 // Input image is const. VPX's raw image is not defined as const.
642 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
643 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
644 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
645 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
646 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
647 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
648 break;
649 }
650 case VP9Profile::kProfile2: {
651 // We can inject kI010 frames directly for encode. All other formats
652 // should be converted to it.
653 switch (input_image.video_frame_buffer()->type()) {
654 case VideoFrameBuffer::Type::kI010: {
655 i010_buffer = input_image.video_frame_buffer()->GetI010();
656 break;
657 }
658 default: {
659 i010_buffer =
660 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
661 }
662 }
663 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
664 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
665 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
666 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
667 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
668 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
669 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
670 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
671 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
672 break;
673 }
674 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000675
philipelcfc319b2015-11-10 07:17:23 -0800676 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200677 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000678 flags = VPX_EFLAG_FORCE_KF;
679 }
philipelcfc319b2015-11-10 07:17:23 -0800680
sprang3958ed82017-08-17 08:12:10 -0700681 RTC_CHECK_GT(codec_.maxFramerate, 0);
Sergey Silkind902d582018-05-18 17:31:19 +0200682 uint32_t duration =
683 90000 / target_framerate_fps_.value_or(codec_.maxFramerate);
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700684 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
685 duration, flags, VPX_DL_REALTIME);
686 if (rv != VPX_CODEC_OK) {
687 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
688 << "\n"
689 << "Details: " << vpx_codec_error(encoder_) << "\n"
690 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000691 return WEBRTC_VIDEO_CODEC_ERROR;
692 }
693 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700694
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200695 const bool end_of_picture = true;
696 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200697
asaperssona9455ab2015-07-31 06:10:09 -0700698 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000699}
700
701void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800702 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200703 uint32_t timestamp,
704 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700705 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000706 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700707 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800708 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200709
710 vp9_info->first_frame_in_picture = first_frame_in_picture;
hta257dc392016-10-25 09:05:06 -0700711 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
712 vp9_info->ss_data_available =
713 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
714 ? true
715 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700716
717 vpx_svc_layer_id_t layer_id = {0};
718 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
719
sprang3958ed82017-08-17 08:12:10 -0700720 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -0500721 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700722 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700723 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700724 vp9_info->temporal_idx = kNoTemporalIdx;
725 } else {
726 vp9_info->temporal_idx = layer_id.temporal_layer_id;
727 }
“Michael23c5a992018-06-21 11:07:21 -0500728 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700729 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700730 vp9_info->spatial_idx = kNoSpatialIdx;
731 } else {
732 vp9_info->spatial_idx = layer_id.spatial_layer_id;
733 }
734 if (layer_id.spatial_layer_id != 0) {
735 vp9_info->ss_data_available = false;
736 }
737
asaperssona9455ab2015-07-31 06:10:09 -0700738 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800739 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700740
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200741 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
742 pics_since_key_ = 0;
743 } else if (first_frame_in_picture) {
744 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700745 }
746
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200747 const bool is_key_pic = (pics_since_key_ == 0);
748 const bool is_inter_layer_pred_allowed =
749 (inter_layer_pred_ == InterLayerPredMode::kOn ||
750 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
751
752 // Always set inter_layer_predicted to true on high layer frame if inter-layer
753 // prediction (ILP) is allowed even if encoder didn't actually use it.
754 // Setting inter_layer_predicted to false would allow receiver to decode high
755 // layer frame without decoding low layer frame. If that would happen (e.g.
756 // if low layer frame is lost) then receiver won't be able to decode next high
757 // layer frame which uses ILP.
758 vp9_info->inter_layer_predicted =
759 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
760
761 const bool is_last_layer =
“Michael23c5a992018-06-21 11:07:21 -0500762 (layer_id.spatial_layer_id + 1 == num_active_spatial_layers_);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200763 vp9_info->non_ref_for_inter_layer_pred =
764 is_last_layer ? true : !is_inter_layer_pred_allowed;
asapersson00ac85e2015-11-11 05:30:48 -0800765
ivica7f6a6fc2015-09-08 02:40:29 -0700766 // Always populate this, so that the packetizer can properly set the marker
767 // bit.
“Michael23c5a992018-06-21 11:07:21 -0500768 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800769
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200770 RTC_DCHECK(!vp9_info->flexible_mode);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200771
772 vp9_info->num_ref_pics = 0;
773 if (vp9_info->flexible_mode) {
774 vp9_info->gof_idx = kNoGofIdx;
775 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
776 vp9_info);
777 } else {
778 vp9_info->gof_idx =
779 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
780 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
781 vp9_info->num_ref_pics = gof_.num_ref_pics[vp9_info->gof_idx];
782 }
783
784 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
785
asaperssona9455ab2015-07-31 06:10:09 -0700786 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700787 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -0500788 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +0200789 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800790 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +0200791 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800792 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700793 }
794 if (!vp9_info->flexible_mode) {
795 vp9_info->gof.CopyGofInfoVP9(gof_);
796 }
797 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000798}
799
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200800void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
801 const size_t pic_num,
802 const bool inter_layer_predicted,
803 CodecSpecificInfoVP9* vp9_info) {
804 vpx_svc_layer_id_t layer_id = {0};
805 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
806
807 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
808 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
809
810 std::vector<RefFrameBuffer> ref_buf_list;
811 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
812 const size_t fb_idx = enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
813 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
814 ref_buf_list.push_back(ref_buf_.at(fb_idx));
815 }
816
817 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
818 const size_t fb_idx = enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
819 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
820 ref_buf_list.push_back(ref_buf_.at(fb_idx));
821 }
822
823 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
824 const size_t fb_idx = enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
825 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
826 ref_buf_list.push_back(ref_buf_.at(fb_idx));
827 }
828
829 size_t max_ref_temporal_layer_id = 0;
830
831 vp9_info->num_ref_pics = 0;
832 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
833 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
834 if (ref_buf.pic_num < pic_num) {
835 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
836 // RTP spec limits temporal prediction to the same spatial layer.
837 // It is safe to ignore this requirement if inter-layer prediction is
838 // enabled for all frames when all base frames are relayed to receiver.
839 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
840 }
841 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
842
843 const size_t p_diff = pic_num - ref_buf.pic_num;
844 RTC_DCHECK_LE(p_diff, 127UL);
845
846 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
847 ++vp9_info->num_ref_pics;
848
849 max_ref_temporal_layer_id =
850 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
851 } else {
852 RTC_DCHECK(inter_layer_predicted);
853 // RTP spec only allows to use previous spatial layer for inter-layer
854 // prediction.
855 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
856 }
857 }
858
859 vp9_info->temporal_up_switch =
860 (max_ref_temporal_layer_id <
861 static_cast<size_t>(layer_id.temporal_layer_id));
862}
863
864void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
865 const size_t pic_num) {
866 vpx_svc_layer_id_t layer_id = {0};
867 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
868
869 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
870 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
871
872 const bool is_key_frame =
873 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
874
875 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
876 layer_id.temporal_layer_id);
877
878 if (is_key_frame && layer_id.spatial_layer_id == 0) {
879 // Key frame updates all ref buffers.
880 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
881 ref_buf_[i] = frame_buf;
882 }
883 } else {
884 if (enc_layer_conf.update_last[layer_id.spatial_layer_id]) {
885 ref_buf_[enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id]] =
886 frame_buf;
887 }
888
889 if (enc_layer_conf.update_alt_ref[layer_id.spatial_layer_id]) {
890 ref_buf_[enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id]] =
891 frame_buf;
892 }
893
894 if (enc_layer_conf.update_golden[layer_id.spatial_layer_id]) {
895 ref_buf_[enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id]] =
896 frame_buf;
897 }
898 }
899}
900
asaperssona9455ab2015-07-31 06:10:09 -0700901int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800902 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700903
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200904 if (pkt->data.frame.sz == 0) {
905 // Ignore dropped frame.
906 return WEBRTC_VIDEO_CODEC_OK;
907 }
908
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200909 vpx_svc_layer_id_t layer_id = {0};
910 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
911
912 const bool first_frame_in_picture = encoded_image_._length == 0;
913 // Ensure we don't buffer layers of previous picture (superframe).
914 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
915
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200916 const bool end_of_picture = false;
917 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200918
asaperssond9f641e2016-01-21 01:11:35 -0800919 if (pkt->data.frame.sz > encoded_image_._size) {
920 delete[] encoded_image_._buffer;
921 encoded_image_._size = pkt->data.frame.sz;
922 encoded_image_._buffer = new uint8_t[encoded_image_._size];
923 }
asapersson86956de2016-01-26 01:05:20 -0800924 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
925 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800926
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200927 const bool is_key_frame =
928 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
929 // Ensure encoder issued key frame on request.
930 RTC_DCHECK(is_key_frame || !force_key_frame_);
931
asaperssona9455ab2015-07-31 06:10:09 -0700932 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800933 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200934 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +0200935 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200936 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000937 }
asapersson86956de2016-01-26 01:05:20 -0800938 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
939
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200940 memset(&codec_specific_, 0, sizeof(codec_specific_));
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200941 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
942 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -0700943
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200944 if (is_flexible_mode_) {
945 UpdateReferenceBuffers(*pkt, pics_since_key_);
946 }
947
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200948 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
949 encoded_image_._timeStamp = input_image_->timestamp();
950 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
951 encoded_image_.rotation_ = input_image_->rotation();
Niels Möllere3cf3d02018-06-13 11:52:16 +0200952 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200953 ? VideoContentType::SCREENSHARE
954 : VideoContentType::UNSPECIFIED;
955 encoded_image_._encodedHeight =
956 pkt->data.frame.height[layer_id.spatial_layer_id];
957 encoded_image_._encodedWidth =
958 pkt->data.frame.width[layer_id.spatial_layer_id];
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +0200959 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200960 int qp = -1;
961 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
962 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700963
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000964 return WEBRTC_VIDEO_CODEC_OK;
965}
966
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200967void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200968 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200969 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200970
971 // No data partitioning in VP9, so 1 partition only.
972 int part_idx = 0;
973 RTPFragmentationHeader frag_info;
974 frag_info.VerifyAndAllocateFragmentationHeader(1);
975 frag_info.fragmentationOffset[part_idx] = 0;
976 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
977 frag_info.fragmentationPlType[part_idx] = 0;
978 frag_info.fragmentationTimeDiff[part_idx] = 0;
979
980 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
981 &frag_info);
982 encoded_image_._length = 0;
Sergey Silkind902d582018-05-18 17:31:19 +0200983
984 if (end_of_picture) {
985 const uint32_t timestamp_ms =
986 1000 * encoded_image_._timeStamp / kVideoPayloadTypeFrequency;
987 output_framerate_.Update(1, timestamp_ms);
988 last_encoded_frame_rtp_timestamp_ = encoded_image_._timeStamp;
989 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200990 }
991}
992
Sergey Silkind902d582018-05-18 17:31:19 +0200993bool VP9EncoderImpl::DropFrame(uint32_t rtp_timestamp) {
994 if (target_framerate_fps_) {
995 if (rtp_timestamp < last_encoded_frame_rtp_timestamp_) {
996 // Timestamp has wrapped around. Reset framerate statistic.
997 output_framerate_.Reset();
998 return false;
999 }
1000
1001 const uint32_t timestamp_ms =
1002 1000 * rtp_timestamp / kVideoPayloadTypeFrequency;
1003 const uint32_t framerate_fps =
1004 output_framerate_.Rate(timestamp_ms).value_or(0);
1005 if (framerate_fps > *target_framerate_fps_) {
1006 return true;
1007 }
1008
1009 // Primarily check if frame interval is too short using frame timestamps,
1010 // as if they are correct they won't be affected by queuing in webrtc.
1011 const uint32_t expected_frame_interval =
1012 kVideoPayloadTypeFrequency / *target_framerate_fps_;
1013
1014 const uint32_t ts_diff = rtp_timestamp - last_encoded_frame_rtp_timestamp_;
1015 if (ts_diff < 85 * expected_frame_interval / 100) {
1016 return true;
1017 }
1018 }
1019
1020 return false;
1021}
1022
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001023int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001024 return WEBRTC_VIDEO_CODEC_OK;
1025}
1026
1027int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1028 EncodedImageCallback* callback) {
1029 encoded_complete_callback_ = callback;
1030 return WEBRTC_VIDEO_CODEC_OK;
1031}
1032
Peter Boströmb7d9a972015-12-18 16:01:11 +01001033const char* VP9EncoderImpl::ImplementationName() const {
1034 return "libvpx";
1035}
1036
Magnus Jedvert46a27652017-11-13 14:10:02 +01001037std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001038 return absl::make_unique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001039}
1040
1041VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001042 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001043 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001044 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001045 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001046
1047VP9DecoderImpl::~VP9DecoderImpl() {
1048 inited_ = true; // in order to do the actual release
1049 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001050 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1051 if (num_buffers_in_use > 0) {
1052 // The frame buffers are reference counted and frames are exposed after
1053 // decoding. There may be valid usage cases where previous frames are still
1054 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001055 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1056 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001057 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001058}
1059
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001060int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001061 int ret_val = Release();
1062 if (ret_val < 0) {
1063 return ret_val;
1064 }
sprang3958ed82017-08-17 08:12:10 -07001065 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001066 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001067 }
philipelcce46fc2015-12-21 03:04:49 -08001068 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001069 // Setting number of threads to a constant value (1)
1070 cfg.threads = 1;
1071 cfg.h = cfg.w = 0; // set after decode
1072 vpx_codec_flags_t flags = 0;
1073 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1074 return WEBRTC_VIDEO_CODEC_MEMORY;
1075 }
Henrik Boström9695d852015-05-06 10:42:15 +02001076
1077 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1078 return WEBRTC_VIDEO_CODEC_MEMORY;
1079 }
1080
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001081 inited_ = true;
1082 // Always start with a complete key frame.
1083 key_frame_required_ = true;
1084 return WEBRTC_VIDEO_CODEC_OK;
1085}
1086
1087int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1088 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001089 const CodecSpecificInfo* codec_specific_info,
1090 int64_t /*render_time_ms*/) {
1091 if (!inited_) {
1092 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1093 }
sprang3958ed82017-08-17 08:12:10 -07001094 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001095 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1096 }
1097 // Always start with a complete key frame.
1098 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +02001099 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001100 return WEBRTC_VIDEO_CODEC_ERROR;
1101 // We have a key frame - is it complete?
1102 if (input_image._completeFrame) {
1103 key_frame_required_ = false;
1104 } else {
1105 return WEBRTC_VIDEO_CODEC_ERROR;
1106 }
1107 }
sprang3958ed82017-08-17 08:12:10 -07001108 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001109 vpx_image_t* img;
1110 uint8_t* buffer = input_image._buffer;
1111 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -07001112 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001113 }
Henrik Boström9695d852015-05-06 10:42:15 +02001114 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1115 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001116 if (vpx_codec_decode(decoder_, buffer,
1117 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001118 VPX_DL_REALTIME)) {
1119 return WEBRTC_VIDEO_CODEC_ERROR;
1120 }
Henrik Boström9695d852015-05-06 10:42:15 +02001121 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1122 // It may be released by libvpx during future vpx_codec_decode or
1123 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001124 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001125 int qp;
1126 vpx_codec_err_t vpx_ret =
1127 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1128 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
1129 int ret =
1130 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001131 if (ret != 0) {
1132 return ret;
1133 }
1134 return WEBRTC_VIDEO_CODEC_OK;
1135}
1136
asapersson1490f7a2016-09-23 02:09:46 -07001137int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
1138 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -08001139 int64_t ntp_time_ms,
1140 int qp) {
sprang3958ed82017-08-17 08:12:10 -07001141 if (img == nullptr) {
1142 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001143 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1144 }
Henrik Boström9695d852015-05-06 10:42:15 +02001145
1146 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001147 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001148 // vpx_codec_decode calls or vpx_codec_destroy).
1149 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1150 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001151
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001152 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001153 // using a Wrapped*Buffer.
1154 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1155 switch (img->bit_depth) {
1156 case 8:
1157 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001158 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1159 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1160 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1161 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001162 // WrappedI420Buffer's mechanism for allowing the release of its frame
1163 // buffer is through a callback function. This is where we should
1164 // release |img_buffer|.
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001165 rtc::KeepRefUntilDone(img_buffer));
1166 break;
1167 case 10:
1168 img_wrapped_buffer = WrapI010Buffer(
1169 img->d_w, img->d_h,
1170 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1171 img->stride[VPX_PLANE_Y] / 2,
1172 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1173 img->stride[VPX_PLANE_U] / 2,
1174 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1175 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1176 break;
1177 default:
1178 RTC_NOTREACHED();
1179 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1180 }
nisseca6d5d12016-06-17 05:03:04 -07001181 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
1182 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -07001183 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -07001184
Danil Chapovalov0040b662018-06-18 10:48:16 +02001185 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001186 return WEBRTC_VIDEO_CODEC_OK;
1187}
1188
1189int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1190 DecodedImageCallback* callback) {
1191 decode_complete_callback_ = callback;
1192 return WEBRTC_VIDEO_CODEC_OK;
1193}
1194
1195int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001196 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1197
sprang3958ed82017-08-17 08:12:10 -07001198 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001199 if (inited_) {
1200 // When a codec is destroyed libvpx will release any buffers of
1201 // |frame_buffer_pool_| it is currently using.
1202 if (vpx_codec_destroy(decoder_)) {
1203 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1204 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001205 }
1206 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001207 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001208 }
Henrik Boström9695d852015-05-06 10:42:15 +02001209 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1210 // still referenced externally are deleted once fully released, not returning
1211 // to the pool.
1212 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001213 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001214 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001215}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001216
1217const char* VP9DecoderImpl::ImplementationName() const {
1218 return "libvpx";
1219}
1220
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001221} // namespace webrtc