blob: 366038b52f7ce8856fb9a49401df85bae6db2071 [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
14#include <stdlib.h>
15#include <string.h>
16#include <time.h>
17#include <vector>
18
19#include "vpx/vpx_encoder.h"
20#include "vpx/vpx_decoder.h"
21#include "vpx/vp8cx.h"
22#include "vpx/vp8dx.h"
23
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "common_video/include/video_frame_buffer.h"
25#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkind902d582018-05-18 17:31:19 +020026#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020027#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/checks.h"
29#include "rtc_base/keep_ref_until_done.h"
30#include "rtc_base/logging.h"
Magnus Jedvert46a27652017-11-13 14:10:02 +010031#include "rtc_base/ptr_util.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
Peter Boström12996152016-05-14 02:03:18 +020056bool VP9Encoder::IsSupported() {
57 return true;
58}
59
Magnus Jedvert46a27652017-11-13 14:10:02 +010060std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
61 return rtc::MakeUnique<VP9EncoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +000062}
63
asaperssona9455ab2015-07-31 06:10:09 -070064void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
65 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -080066 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -070067 enc->GetEncodedLayerFrame(pkt);
68}
69
marpan@webrtc.org5b883172014-11-01 06:10:48 +000070VP9EncoderImpl::VP9EncoderImpl()
71 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -070072 encoded_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000073 inited_(false),
74 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000075 cpu_speed_(3),
76 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -070077 encoder_(nullptr),
78 config_(nullptr),
79 raw_(nullptr),
80 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +020081 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020082 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -070083 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -080084 num_spatial_layers_(0),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020085 inter_layer_pred_(InterLayerPredMode::kOn),
Sergey Silkind902d582018-05-18 17:31:19 +020086 output_framerate_(1000.0, 1000.0),
87 last_encoded_frame_rtp_timestamp_(0),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +020088 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +000089 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -080090 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +000091}
92
93VP9EncoderImpl::~VP9EncoderImpl() {
94 Release();
95}
96
97int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +010098 int ret_val = WEBRTC_VIDEO_CODEC_OK;
99
sprang3958ed82017-08-17 08:12:10 -0700100 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800101 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -0700102 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000103 }
sprang3958ed82017-08-17 08:12:10 -0700104 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100105 if (inited_) {
106 if (vpx_codec_destroy(encoder_)) {
107 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
108 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000109 }
110 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700111 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000112 }
sprang3958ed82017-08-17 08:12:10 -0700113 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000114 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700115 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000116 }
sprang3958ed82017-08-17 08:12:10 -0700117 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000118 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700119 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000120 }
121 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100122 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000123}
124
sprangce4aef12015-11-02 07:23:20 -0800125bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
126 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
127 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100128 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800129}
130
Erik Språng566124a2018-04-23 12:32:22 +0200131bool VP9EncoderImpl::SetSvcRates(
132 const VideoBitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700133 uint8_t i = 0;
134
Sergey Silkin86684962018-03-28 19:32:37 +0200135 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200136
sprangce4aef12015-11-02 07:23:20 -0800137 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200138 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200139 const bool was_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200140 config_->ss_target_bitrate[sl_idx] =
141 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
142
143 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
144 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
145 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
146 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200147
148 const bool is_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
149 if (is_layer_enabled && !was_layer_enabled) {
150 if (inter_layer_pred_ == InterLayerPredMode::kOff ||
151 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic) {
152 // TODO(wemb:1526): remove key frame request when issue is fixed.
153 force_key_frame_ = true;
154 }
155 }
sprangce4aef12015-11-02 07:23:20 -0800156 }
157 } else {
158 float rate_ratio[VPX_MAX_LAYERS] = {0};
159 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700160
sprangce4aef12015-11-02 07:23:20 -0800161 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800162 if (svc_params_.scaling_factor_num[i] <= 0 ||
163 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100164 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800165 return false;
166 }
167 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800168 static_cast<float>(svc_params_.scaling_factor_num[i]) /
169 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800170 total += rate_ratio[i];
171 }
172
173 for (i = 0; i < num_spatial_layers_; ++i) {
174 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
175 config_->rc_target_bitrate * rate_ratio[i] / total);
176 if (num_temporal_layers_ == 1) {
177 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
178 } else if (num_temporal_layers_ == 2) {
179 config_->layer_target_bitrate[i * num_temporal_layers_] =
180 config_->ss_target_bitrate[i] * 2 / 3;
181 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
182 config_->ss_target_bitrate[i];
183 } else if (num_temporal_layers_ == 3) {
184 config_->layer_target_bitrate[i * num_temporal_layers_] =
185 config_->ss_target_bitrate[i] / 2;
186 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
187 config_->layer_target_bitrate[i * num_temporal_layers_] +
188 (config_->ss_target_bitrate[i] / 4);
189 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
190 config_->ss_target_bitrate[i];
191 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100192 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
193 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800194 return false;
195 }
asaperssona9455ab2015-07-31 06:10:09 -0700196 }
197 }
198
199 // For now, temporal layers only supported when having one spatial layer.
200 if (num_spatial_layers_ == 1) {
201 for (i = 0; i < num_temporal_layers_; ++i) {
202 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
203 }
204 }
205
206 return true;
207}
208
Erik Språng08127a92016-11-16 16:41:30 +0100209int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200210 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100211 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000212 if (!inited_) {
213 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
214 }
215 if (encoder_->err) {
216 return WEBRTC_VIDEO_CODEC_ERROR;
217 }
Erik Språng08127a92016-11-16 16:41:30 +0100218 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000219 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
220 }
221 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100222 if (codec_.maxBitrate > 0 &&
223 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
224 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000225 }
Erik Språng08127a92016-11-16 16:41:30 +0100226
Erik Språng08127a92016-11-16 16:41:30 +0100227 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700228
Sergey Silkin86684962018-03-28 19:32:37 +0200229 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700230 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
231 }
232
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000233 // Update encoder context
234 if (vpx_codec_enc_config_set(encoder_, config_)) {
235 return WEBRTC_VIDEO_CODEC_ERROR;
236 }
237 return WEBRTC_VIDEO_CODEC_OK;
238}
239
240int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
241 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000242 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700243 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000244 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
245 }
246 if (inst->maxFramerate < 1) {
247 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
248 }
249 // Allow zero to represent an unspecified maxBitRate
250 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
251 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
252 }
253 if (inst->width < 1 || inst->height < 1) {
254 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
255 }
256 if (number_of_cores < 1) {
257 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
258 }
hta257dc392016-10-25 09:05:06 -0700259 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700260 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
261 }
ilnik2a8c2f52017-02-15 02:23:28 -0800262 // libvpx probably does not support more than 3 spatial layers.
263 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700264 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
265 }
philipelcfc319b2015-11-10 07:17:23 -0800266
asapersson86956de2016-01-26 01:05:20 -0800267 int ret_val = Release();
268 if (ret_val < 0) {
269 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000270 }
sprang3958ed82017-08-17 08:12:10 -0700271 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000272 encoder_ = new vpx_codec_ctx_t;
273 }
sprang3958ed82017-08-17 08:12:10 -0700274 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000275 config_ = new vpx_codec_enc_cfg_t;
276 }
277 timestamp_ = 0;
278 if (&codec_ != inst) {
279 codec_ = *inst;
280 }
asaperssona9455ab2015-07-31 06:10:09 -0700281
hta257dc392016-10-25 09:05:06 -0700282 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200283 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700284 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700285 if (num_temporal_layers_ == 0)
286 num_temporal_layers_ = 1;
287
Sergey Silkind902d582018-05-18 17:31:19 +0200288 // Init framerate controller.
289 output_framerate_.Reset();
290 if (codec_.mode == kScreensharing) {
291 target_framerate_fps_ = kMaxScreenSharingFramerateFps;
292 } else {
293 target_framerate_fps_.reset();
294 }
295
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000296 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700297 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800298 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000299 }
nisseeb44b392017-04-28 07:18:05 -0700300 encoded_image_._size =
301 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000302 encoded_image_._buffer = new uint8_t[encoded_image_._size];
303 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700304 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000305 // pointer will be set in encode. Setting align to 1, as it is meaningless
306 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700307 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
308 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000309 // Populate encoder configuration with default values.
310 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
311 return WEBRTC_VIDEO_CODEC_ERROR;
312 }
313 config_->g_w = codec_.width;
314 config_->g_h = codec_.height;
315 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Niels Möller65fb4042018-04-25 14:46:06 +0200316 config_->g_error_resilient =
317 (num_spatial_layers_ > 1 || num_temporal_layers_ > 1) ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000318 // Setting the time base of the codec.
319 config_->g_timebase.num = 1;
320 config_->g_timebase.den = 90000;
321 config_->g_lag_in_frames = 0; // 0- no frame lagging
322 config_->g_threads = 1;
323 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700324 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000325 config_->rc_end_usage = VPX_CBR;
326 config_->g_pass = VPX_RC_ONE_PASS;
327 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000328 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000329 config_->rc_undershoot_pct = 50;
330 config_->rc_overshoot_pct = 50;
331 config_->rc_buf_initial_sz = 500;
332 config_->rc_buf_optimal_sz = 600;
333 config_->rc_buf_sz = 1000;
334 // Set the maximum target size of any key-frame.
335 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700336 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000337 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700338 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100339 // Needs to be set (in svc mode) to get correct periodic key frame interval
340 // (will have no effect in non-svc).
341 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000342 } else {
343 config_->kf_mode = VPX_KF_DISABLED;
344 }
hta257dc392016-10-25 09:05:06 -0700345 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000346 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800347 config_->g_threads =
348 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700349
Marco6e89b252015-07-07 14:40:38 -0700350 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700351
352 // TODO(asapersson): Check configuration of temporal switch up and increase
353 // pattern length.
hta257dc392016-10-25 09:05:06 -0700354 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200355
356 // TODO(ssilkin): Only non-flexible mode is supported for now.
357 RTC_DCHECK(!is_flexible_mode_);
358
359 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700360 gof_.SetGofInfoVP9(kTemporalStructureMode1);
361 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
362 config_->ts_number_layers = 1;
363 config_->ts_rate_decimator[0] = 1;
364 config_->ts_periodicity = 1;
365 config_->ts_layer_id[0] = 0;
366 } else if (num_temporal_layers_ == 2) {
367 gof_.SetGofInfoVP9(kTemporalStructureMode2);
368 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
369 config_->ts_number_layers = 2;
370 config_->ts_rate_decimator[0] = 2;
371 config_->ts_rate_decimator[1] = 1;
372 config_->ts_periodicity = 2;
373 config_->ts_layer_id[0] = 0;
374 config_->ts_layer_id[1] = 1;
375 } else if (num_temporal_layers_ == 3) {
376 gof_.SetGofInfoVP9(kTemporalStructureMode3);
377 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
378 config_->ts_number_layers = 3;
379 config_->ts_rate_decimator[0] = 4;
380 config_->ts_rate_decimator[1] = 2;
381 config_->ts_rate_decimator[2] = 1;
382 config_->ts_periodicity = 4;
383 config_->ts_layer_id[0] = 0;
384 config_->ts_layer_id[1] = 2;
385 config_->ts_layer_id[2] = 1;
386 config_->ts_layer_id[3] = 2;
387 } else {
388 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
389 }
390
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200391 inter_layer_pred_ = inst->VP9().interLayerPred;
392
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000393 return InitAndSetControlSettings(inst);
394}
395
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000396int VP9EncoderImpl::NumberOfThreads(int width,
397 int height,
398 int number_of_cores) {
399 // Keep the number of encoder threads equal to the possible number of column
400 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
401 if (width * height >= 1280 * 720 && number_of_cores > 4) {
402 return 4;
jianj23173a32017-07-12 16:11:09 -0700403 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000404 return 2;
405 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800406 // Use 2 threads for low res on ARM.
407#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
408 defined(WEBRTC_ANDROID)
409 if (width * height >= 320 * 180 && number_of_cores > 2) {
410 return 2;
411 }
412#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000413 // 1 thread less than VGA.
414 return 1;
415 }
416}
417
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000418int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100419 // Set QP-min/max per spatial and temporal layer.
420 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
421 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800422 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
423 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100424 }
asaperssona9455ab2015-07-31 06:10:09 -0700425 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800426 if (ExplicitlyConfiguredSpatialLayers()) {
427 for (int i = 0; i < num_spatial_layers_; ++i) {
428 const auto& layer = codec_.spatialLayers[i];
Sergey Silkin13e74342018-03-02 12:28:00 +0100429 const int scale_factor = codec_.width / layer.width;
430 RTC_DCHECK_GT(scale_factor, 0);
431
432 // Ensure scaler factor is integer.
433 if (scale_factor * layer.width != codec_.width) {
434 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
435 }
436
437 // Ensure scale factor is the same in both dimensions.
438 if (scale_factor * layer.height != codec_.height) {
439 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
440 }
441
442 // Ensure scale factor is power of two.
443 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
444 if (!is_pow_of_two) {
445 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
446 }
447
448 svc_params_.scaling_factor_num[i] = 1;
449 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800450 }
451 } else {
452 int scaling_factor_num = 256;
453 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800454 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800455 svc_params_.scaling_factor_num[i] = scaling_factor_num;
456 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800457 }
asaperssona9455ab2015-07-31 06:10:09 -0700458 }
459
Sergey Silkin86684962018-03-28 19:32:37 +0200460 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200461 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200462 inst->startBitrate * 1000, inst->maxFramerate);
463 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700464 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
465 }
466
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000467 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
468 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
469 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000470 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
471 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
472 rc_max_intra_target_);
473 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700474 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700475
jianj822e5932017-07-12 16:09:58 -0700476 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700477 vpx_codec_control(
478 encoder_, VP9E_SET_SVC,
479 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200480
asaperssona9455ab2015-07-31 06:10:09 -0700481 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
482 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800483 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700484 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200485
486 if (num_spatial_layers_ > 1) {
487 switch (inter_layer_pred_) {
488 case InterLayerPredMode::kOn:
489 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
490 break;
491 case InterLayerPredMode::kOff:
492 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
493 break;
494 case InterLayerPredMode::kOnKeyPic:
495 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
496 break;
497 default:
498 RTC_NOTREACHED();
499 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200500
501 if (!is_flexible_mode_) {
502 // In RTP non-flexible mode, frame dropping of individual layers in a
503 // superframe leads to incorrect reference picture ID values in the
504 // RTP header. Dropping the entire superframe if the base is dropped
505 // or not dropping upper layers if base is not dropped mitigates
506 // the problem.
507 vpx_svc_frame_drop_t svc_drop_frame;
Jerome Jiang0c2e8ce2018-05-25 22:26:43 -0700508 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200509 svc_drop_frame.framedrop_mode = CONSTRAINED_LAYER_DROP;
510 for (size_t i = 0; i < num_spatial_layers_; ++i) {
511 svc_drop_frame.framedrop_thresh[i] =
512 (i == 0) ? config_->rc_dropframe_thresh : 0;
513 }
514 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER,
515 &svc_drop_frame);
516 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200517 }
518
asaperssona9455ab2015-07-31 06:10:09 -0700519 // Register callback for getting each spatial layer.
520 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800521 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
522 reinterpret_cast<void*>(this)};
523 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
524 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700525
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000526 // Control function to set the number of column tiles in encoding a frame, in
527 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
528 // The number tile columns will be capped by the encoder based on image size
529 // (minimum width of tile column is 256 pixels, maximum is 4096).
530 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700531
532 // Turn on row-based multithreading.
533 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700534
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700535#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
536 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700537 // Do not enable the denoiser on ARM since optimization is pending.
538 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000539 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700540 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000541#endif
jianj6bf57e32017-06-05 13:43:49 -0700542
ivica242d6382015-09-04 06:13:23 -0700543 if (codec_.mode == kScreensharing) {
544 // Adjust internal parameters to screen content.
545 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700546 }
Marco2520e722015-09-16 14:05:00 -0700547 // Enable encoder skip of static/low content blocks.
548 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000549 inited_ = true;
550 return WEBRTC_VIDEO_CODEC_OK;
551}
552
553uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
554 // Set max to the optimal buffer level (normalized by target BR),
555 // and scaled by a scale_par.
556 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
557 // This value is presented in percentage of perFrameBw:
558 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
559 // The target in % is as follows:
560 float scale_par = 0.5;
561 uint32_t target_pct =
562 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
563 // Don't go below 3 times the per frame bandwidth.
564 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800565 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000566}
567
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700568int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000569 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700570 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000571 if (!inited_) {
572 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
573 }
sprang3958ed82017-08-17 08:12:10 -0700574 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000575 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
576 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200577
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000578 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200579 if (frame_types && !frame_types->empty()) {
580 if ((*frame_types)[0] == kVideoFrameKey) {
581 force_key_frame_ = true;
582 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000583 }
Sergey Silkind902d582018-05-18 17:31:19 +0200584
585 if (kScreensharing == codec_.mode && !force_key_frame_) {
586 if (DropFrame(input_image.timestamp())) {
587 return WEBRTC_VIDEO_CODEC_OK;
588 }
589 }
590
kwiberg352444f2016-11-28 15:58:53 -0800591 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
592 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700593
594 // Set input image for use in the callback.
595 // This was necessary since you need some information from input_image.
596 // You can save only the necessary information (such as timestamp) instead of
597 // doing this.
598 input_image_ = &input_image;
599
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000600 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
601 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000602 // Image in vpx_image_t format.
603 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000604 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
605 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
606 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
607 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
608 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
609 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000610
philipelcfc319b2015-11-10 07:17:23 -0800611 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200612 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000613 flags = VPX_EFLAG_FORCE_KF;
614 }
philipelcfc319b2015-11-10 07:17:23 -0800615
sprang3958ed82017-08-17 08:12:10 -0700616 RTC_CHECK_GT(codec_.maxFramerate, 0);
Sergey Silkind902d582018-05-18 17:31:19 +0200617 uint32_t duration =
618 90000 / target_framerate_fps_.value_or(codec_.maxFramerate);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000619 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
620 VPX_DL_REALTIME)) {
621 return WEBRTC_VIDEO_CODEC_ERROR;
622 }
623 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700624
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200625 const bool end_of_picture = true;
626 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200627
asaperssona9455ab2015-07-31 06:10:09 -0700628 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000629}
630
631void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800632 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200633 uint32_t timestamp,
634 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700635 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000636 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700637 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800638 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200639
640 vp9_info->first_frame_in_picture = first_frame_in_picture;
Åsa Perssonff24c042015-12-04 10:58:08 +0100641 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700642 vp9_info->inter_pic_predicted =
643 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700644 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
645 vp9_info->ss_data_available =
646 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
647 ? true
648 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700649
650 vpx_svc_layer_id_t layer_id = {0};
651 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
652
sprang3958ed82017-08-17 08:12:10 -0700653 RTC_CHECK_GT(num_temporal_layers_, 0);
654 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700655 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700656 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700657 vp9_info->temporal_idx = kNoTemporalIdx;
658 } else {
659 vp9_info->temporal_idx = layer_id.temporal_layer_id;
660 }
661 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700662 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700663 vp9_info->spatial_idx = kNoSpatialIdx;
664 } else {
665 vp9_info->spatial_idx = layer_id.spatial_layer_id;
666 }
667 if (layer_id.spatial_layer_id != 0) {
668 vp9_info->ss_data_available = false;
669 }
670
asaperssona9455ab2015-07-31 06:10:09 -0700671 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800672 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700673
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200674 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
675 pics_since_key_ = 0;
676 } else if (first_frame_in_picture) {
677 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700678 }
679
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200680 const bool is_key_pic = (pics_since_key_ == 0);
681 const bool is_inter_layer_pred_allowed =
682 (inter_layer_pred_ == InterLayerPredMode::kOn ||
683 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
684
685 // Always set inter_layer_predicted to true on high layer frame if inter-layer
686 // prediction (ILP) is allowed even if encoder didn't actually use it.
687 // Setting inter_layer_predicted to false would allow receiver to decode high
688 // layer frame without decoding low layer frame. If that would happen (e.g.
689 // if low layer frame is lost) then receiver won't be able to decode next high
690 // layer frame which uses ILP.
691 vp9_info->inter_layer_predicted =
692 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
693
694 const bool is_last_layer =
695 (layer_id.spatial_layer_id + 1 == num_spatial_layers_);
696 vp9_info->non_ref_for_inter_layer_pred =
697 is_last_layer ? true : !is_inter_layer_pred_allowed;
asapersson00ac85e2015-11-11 05:30:48 -0800698
ivica7f6a6fc2015-09-08 02:40:29 -0700699 // Always populate this, so that the packetizer can properly set the marker
700 // bit.
701 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800702
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200703 RTC_DCHECK(!vp9_info->flexible_mode);
704 vp9_info->gof_idx =
705 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
706 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
707 vp9_info->num_ref_pics =
708 is_key_pic ? 0 : gof_.num_ref_pics[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800709
asaperssona9455ab2015-07-31 06:10:09 -0700710 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700711 vp9_info->spatial_layer_resolution_present = true;
712 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
713 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800714 svc_params_.scaling_factor_num[i] /
715 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700716 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800717 svc_params_.scaling_factor_num[i] /
718 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700719 }
720 if (!vp9_info->flexible_mode) {
721 vp9_info->gof.CopyGofInfoVP9(gof_);
722 }
723 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000724}
725
asaperssona9455ab2015-07-31 06:10:09 -0700726int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800727 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700728
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200729 if (pkt->data.frame.sz == 0) {
730 // Ignore dropped frame.
731 return WEBRTC_VIDEO_CODEC_OK;
732 }
733
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200734 vpx_svc_layer_id_t layer_id = {0};
735 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
736
737 const bool first_frame_in_picture = encoded_image_._length == 0;
738 // Ensure we don't buffer layers of previous picture (superframe).
739 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
740
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200741 const bool end_of_picture = false;
742 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200743
asaperssond9f641e2016-01-21 01:11:35 -0800744 if (pkt->data.frame.sz > encoded_image_._size) {
745 delete[] encoded_image_._buffer;
746 encoded_image_._size = pkt->data.frame.sz;
747 encoded_image_._buffer = new uint8_t[encoded_image_._size];
748 }
asapersson86956de2016-01-26 01:05:20 -0800749 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
750 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800751
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200752 const bool is_key_frame =
753 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
754 // Ensure encoder issued key frame on request.
755 RTC_DCHECK(is_key_frame || !force_key_frame_);
756
asaperssona9455ab2015-07-31 06:10:09 -0700757 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800758 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200759 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +0200760 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200761 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000762 }
asapersson86956de2016-01-26 01:05:20 -0800763 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
764
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200765 memset(&codec_specific_, 0, sizeof(codec_specific_));
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200766 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
767 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -0700768
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200769 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
770 encoded_image_._timeStamp = input_image_->timestamp();
771 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
772 encoded_image_.rotation_ = input_image_->rotation();
773 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
774 ? VideoContentType::SCREENSHARE
775 : VideoContentType::UNSPECIFIED;
776 encoded_image_._encodedHeight =
777 pkt->data.frame.height[layer_id.spatial_layer_id];
778 encoded_image_._encodedWidth =
779 pkt->data.frame.width[layer_id.spatial_layer_id];
780 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
781 int qp = -1;
782 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
783 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700784
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000785 return WEBRTC_VIDEO_CODEC_OK;
786}
787
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200788void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200789 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200790 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200791
792 // No data partitioning in VP9, so 1 partition only.
793 int part_idx = 0;
794 RTPFragmentationHeader frag_info;
795 frag_info.VerifyAndAllocateFragmentationHeader(1);
796 frag_info.fragmentationOffset[part_idx] = 0;
797 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
798 frag_info.fragmentationPlType[part_idx] = 0;
799 frag_info.fragmentationTimeDiff[part_idx] = 0;
800
801 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
802 &frag_info);
803 encoded_image_._length = 0;
Sergey Silkind902d582018-05-18 17:31:19 +0200804
805 if (end_of_picture) {
806 const uint32_t timestamp_ms =
807 1000 * encoded_image_._timeStamp / kVideoPayloadTypeFrequency;
808 output_framerate_.Update(1, timestamp_ms);
809 last_encoded_frame_rtp_timestamp_ = encoded_image_._timeStamp;
810 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200811 }
812}
813
Sergey Silkind902d582018-05-18 17:31:19 +0200814bool VP9EncoderImpl::DropFrame(uint32_t rtp_timestamp) {
815 if (target_framerate_fps_) {
816 if (rtp_timestamp < last_encoded_frame_rtp_timestamp_) {
817 // Timestamp has wrapped around. Reset framerate statistic.
818 output_framerate_.Reset();
819 return false;
820 }
821
822 const uint32_t timestamp_ms =
823 1000 * rtp_timestamp / kVideoPayloadTypeFrequency;
824 const uint32_t framerate_fps =
825 output_framerate_.Rate(timestamp_ms).value_or(0);
826 if (framerate_fps > *target_framerate_fps_) {
827 return true;
828 }
829
830 // Primarily check if frame interval is too short using frame timestamps,
831 // as if they are correct they won't be affected by queuing in webrtc.
832 const uint32_t expected_frame_interval =
833 kVideoPayloadTypeFrequency / *target_framerate_fps_;
834
835 const uint32_t ts_diff = rtp_timestamp - last_encoded_frame_rtp_timestamp_;
836 if (ts_diff < 85 * expected_frame_interval / 100) {
837 return true;
838 }
839 }
840
841 return false;
842}
843
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000844int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000845 return WEBRTC_VIDEO_CODEC_OK;
846}
847
848int VP9EncoderImpl::RegisterEncodeCompleteCallback(
849 EncodedImageCallback* callback) {
850 encoded_complete_callback_ = callback;
851 return WEBRTC_VIDEO_CODEC_OK;
852}
853
Peter Boströmb7d9a972015-12-18 16:01:11 +0100854const char* VP9EncoderImpl::ImplementationName() const {
855 return "libvpx";
856}
857
Peter Boström12996152016-05-14 02:03:18 +0200858bool VP9Decoder::IsSupported() {
859 return true;
860}
861
Magnus Jedvert46a27652017-11-13 14:10:02 +0100862std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
863 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000864}
865
866VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700867 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000868 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700869 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +0200870 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000871
872VP9DecoderImpl::~VP9DecoderImpl() {
873 inited_ = true; // in order to do the actual release
874 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200875 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
876 if (num_buffers_in_use > 0) {
877 // The frame buffers are reference counted and frames are exposed after
878 // decoding. There may be valid usage cases where previous frames are still
879 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100880 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
881 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200882 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000883}
884
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000885int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000886 int ret_val = Release();
887 if (ret_val < 0) {
888 return ret_val;
889 }
sprang3958ed82017-08-17 08:12:10 -0700890 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000891 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000892 }
philipelcce46fc2015-12-21 03:04:49 -0800893 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000894 // Setting number of threads to a constant value (1)
895 cfg.threads = 1;
896 cfg.h = cfg.w = 0; // set after decode
897 vpx_codec_flags_t flags = 0;
898 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
899 return WEBRTC_VIDEO_CODEC_MEMORY;
900 }
Henrik Boström9695d852015-05-06 10:42:15 +0200901
902 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
903 return WEBRTC_VIDEO_CODEC_MEMORY;
904 }
905
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000906 inited_ = true;
907 // Always start with a complete key frame.
908 key_frame_required_ = true;
909 return WEBRTC_VIDEO_CODEC_OK;
910}
911
912int VP9DecoderImpl::Decode(const EncodedImage& input_image,
913 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000914 const CodecSpecificInfo* codec_specific_info,
915 int64_t /*render_time_ms*/) {
916 if (!inited_) {
917 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
918 }
sprang3958ed82017-08-17 08:12:10 -0700919 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000920 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
921 }
922 // Always start with a complete key frame.
923 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200924 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000925 return WEBRTC_VIDEO_CODEC_ERROR;
926 // We have a key frame - is it complete?
927 if (input_image._completeFrame) {
928 key_frame_required_ = false;
929 } else {
930 return WEBRTC_VIDEO_CODEC_ERROR;
931 }
932 }
sprang3958ed82017-08-17 08:12:10 -0700933 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000934 vpx_image_t* img;
935 uint8_t* buffer = input_image._buffer;
936 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700937 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000938 }
Henrik Boström9695d852015-05-06 10:42:15 +0200939 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
940 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800941 if (vpx_codec_decode(decoder_, buffer,
942 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000943 VPX_DL_REALTIME)) {
944 return WEBRTC_VIDEO_CODEC_ERROR;
945 }
Henrik Boström9695d852015-05-06 10:42:15 +0200946 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
947 // It may be released by libvpx during future vpx_codec_decode or
948 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000949 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -0800950 int qp;
951 vpx_codec_err_t vpx_ret =
952 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
953 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
954 int ret =
955 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000956 if (ret != 0) {
957 return ret;
958 }
959 return WEBRTC_VIDEO_CODEC_OK;
960}
961
asapersson1490f7a2016-09-23 02:09:46 -0700962int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
963 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -0800964 int64_t ntp_time_ms,
965 int qp) {
sprang3958ed82017-08-17 08:12:10 -0700966 if (img == nullptr) {
967 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000968 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
969 }
Henrik Boström9695d852015-05-06 10:42:15 +0200970
971 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -0800972 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +0200973 // vpx_codec_decode calls or vpx_codec_destroy).
974 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
975 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700976 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +0200977 // using a WrappedI420Buffer.
978 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
979 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -0800980 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
981 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
982 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
983 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +0200984 // WrappedI420Buffer's mechanism for allowing the release of its frame
985 // buffer is through a callback function. This is where we should
986 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -0800987 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +0200988
nisseca6d5d12016-06-17 05:03:04 -0700989 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
990 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -0700991 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -0700992
Oskar Sundbom6bd39022017-11-16 10:54:49 +0100993 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000994 return WEBRTC_VIDEO_CODEC_OK;
995}
996
997int VP9DecoderImpl::RegisterDecodeCompleteCallback(
998 DecodedImageCallback* callback) {
999 decode_complete_callback_ = callback;
1000 return WEBRTC_VIDEO_CODEC_OK;
1001}
1002
1003int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001004 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1005
sprang3958ed82017-08-17 08:12:10 -07001006 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001007 if (inited_) {
1008 // When a codec is destroyed libvpx will release any buffers of
1009 // |frame_buffer_pool_| it is currently using.
1010 if (vpx_codec_destroy(decoder_)) {
1011 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1012 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001013 }
1014 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001015 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001016 }
Henrik Boström9695d852015-05-06 10:42:15 +02001017 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1018 // still referenced externally are deleted once fully released, not returning
1019 // to the pool.
1020 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001021 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001022 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001023}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001024
1025const char* VP9DecoderImpl::ImplementationName() const {
1026 return "libvpx";
1027}
1028
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001029} // namespace webrtc