blob: 5076af2e9da42e70a0f1dece8beadff71070f694 [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"
26#include "modules/video_coding/codecs/vp9/screenshare_layers.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
Marco6e89b252015-07-07 14:40:38 -070037// Only positive speeds, range for real-time coding currently is: 5 - 8.
38// Lower means slower/better quality, higher means fastest/lower quality.
39int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070040#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080041 return 8;
42#else
Marco6e89b252015-07-07 14:40:38 -070043 // For smaller resolutions, use lower speed setting (get some coding gain at
44 // the cost of increased encoding complexity).
45 if (width * height <= 352 * 288)
46 return 5;
47 else
48 return 7;
Marco002f0d02015-12-17 09:49:31 -080049#endif
Marco6e89b252015-07-07 14:40:38 -070050}
51
Peter Boström12996152016-05-14 02:03:18 +020052bool VP9Encoder::IsSupported() {
53 return true;
54}
55
Magnus Jedvert46a27652017-11-13 14:10:02 +010056std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
57 return rtc::MakeUnique<VP9EncoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +000058}
59
asaperssona9455ab2015-07-31 06:10:09 -070060void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
61 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -080062 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -070063 enc->GetEncodedLayerFrame(pkt);
64}
65
marpan@webrtc.org5b883172014-11-01 06:10:48 +000066VP9EncoderImpl::VP9EncoderImpl()
67 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -070068 encoded_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000069 inited_(false),
70 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000071 cpu_speed_(3),
72 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -070073 encoder_(nullptr),
74 config_(nullptr),
75 raw_(nullptr),
76 input_image_(nullptr),
philipelcfc319b2015-11-10 07:17:23 -080077 frames_since_kf_(0),
asaperssona9455ab2015-07-31 06:10:09 -070078 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -080079 num_spatial_layers_(0),
Erik Språng08127a92016-11-16 16:41:30 +010080 is_flexible_mode_(false),
philipelcfc319b2015-11-10 07:17:23 -080081 frames_encoded_(0),
82 // Use two spatial when screensharing with flexible mode.
83 spatial_layer_(new ScreenshareLayersVP9(2)) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +000084 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -080085 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +000086}
87
88VP9EncoderImpl::~VP9EncoderImpl() {
89 Release();
90}
91
92int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +010093 int ret_val = WEBRTC_VIDEO_CODEC_OK;
94
sprang3958ed82017-08-17 08:12:10 -070095 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -080096 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -070097 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +000098 }
sprang3958ed82017-08-17 08:12:10 -070099 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100100 if (inited_) {
101 if (vpx_codec_destroy(encoder_)) {
102 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
103 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000104 }
105 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700106 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000107 }
sprang3958ed82017-08-17 08:12:10 -0700108 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000109 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700110 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000111 }
sprang3958ed82017-08-17 08:12:10 -0700112 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000113 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700114 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000115 }
116 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100117 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000118}
119
sprangce4aef12015-11-02 07:23:20 -0800120bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
121 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
122 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100123 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800124}
125
Erik Språng566124a2018-04-23 12:32:22 +0200126bool VP9EncoderImpl::SetSvcRates(
127 const VideoBitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700128 uint8_t i = 0;
129
Sergey Silkin86684962018-03-28 19:32:37 +0200130 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
131 spatial_layer_->ConfigureBitrate(bitrate_allocation.get_sum_kbps(), 0);
132
sprangce4aef12015-11-02 07:23:20 -0800133 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200134 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
135 config_->ss_target_bitrate[sl_idx] =
136 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
137
138 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
139 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
140 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
141 }
sprangce4aef12015-11-02 07:23:20 -0800142 }
143 } else {
144 float rate_ratio[VPX_MAX_LAYERS] = {0};
145 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700146
sprangce4aef12015-11-02 07:23:20 -0800147 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800148 if (svc_params_.scaling_factor_num[i] <= 0 ||
149 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800151 return false;
152 }
153 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800154 static_cast<float>(svc_params_.scaling_factor_num[i]) /
155 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800156 total += rate_ratio[i];
157 }
158
159 for (i = 0; i < num_spatial_layers_; ++i) {
160 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
161 config_->rc_target_bitrate * rate_ratio[i] / total);
162 if (num_temporal_layers_ == 1) {
163 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
164 } else if (num_temporal_layers_ == 2) {
165 config_->layer_target_bitrate[i * num_temporal_layers_] =
166 config_->ss_target_bitrate[i] * 2 / 3;
167 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
168 config_->ss_target_bitrate[i];
169 } else if (num_temporal_layers_ == 3) {
170 config_->layer_target_bitrate[i * num_temporal_layers_] =
171 config_->ss_target_bitrate[i] / 2;
172 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
173 config_->layer_target_bitrate[i * num_temporal_layers_] +
174 (config_->ss_target_bitrate[i] / 4);
175 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
176 config_->ss_target_bitrate[i];
177 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100178 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
179 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800180 return false;
181 }
asaperssona9455ab2015-07-31 06:10:09 -0700182 }
183 }
184
185 // For now, temporal layers only supported when having one spatial layer.
186 if (num_spatial_layers_ == 1) {
187 for (i = 0; i < num_temporal_layers_; ++i) {
188 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
189 }
190 }
191
192 return true;
193}
194
Erik Språng08127a92016-11-16 16:41:30 +0100195int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200196 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100197 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000198 if (!inited_) {
199 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
200 }
201 if (encoder_->err) {
202 return WEBRTC_VIDEO_CODEC_ERROR;
203 }
Erik Språng08127a92016-11-16 16:41:30 +0100204 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000205 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
206 }
207 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100208 if (codec_.maxBitrate > 0 &&
209 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
210 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000211 }
Erik Språng08127a92016-11-16 16:41:30 +0100212
Erik Språng08127a92016-11-16 16:41:30 +0100213 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700214
Sergey Silkin86684962018-03-28 19:32:37 +0200215 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700216 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
217 }
218
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000219 // Update encoder context
220 if (vpx_codec_enc_config_set(encoder_, config_)) {
221 return WEBRTC_VIDEO_CODEC_ERROR;
222 }
223 return WEBRTC_VIDEO_CODEC_OK;
224}
225
226int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
227 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000228 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700229 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000230 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
231 }
232 if (inst->maxFramerate < 1) {
233 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
234 }
235 // Allow zero to represent an unspecified maxBitRate
236 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
237 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
238 }
239 if (inst->width < 1 || inst->height < 1) {
240 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
241 }
242 if (number_of_cores < 1) {
243 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
244 }
hta257dc392016-10-25 09:05:06 -0700245 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700246 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
247 }
ilnik2a8c2f52017-02-15 02:23:28 -0800248 // libvpx probably does not support more than 3 spatial layers.
249 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700250 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
251 }
philipelcfc319b2015-11-10 07:17:23 -0800252
asapersson86956de2016-01-26 01:05:20 -0800253 int ret_val = Release();
254 if (ret_val < 0) {
255 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000256 }
sprang3958ed82017-08-17 08:12:10 -0700257 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000258 encoder_ = new vpx_codec_ctx_t;
259 }
sprang3958ed82017-08-17 08:12:10 -0700260 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000261 config_ = new vpx_codec_enc_cfg_t;
262 }
263 timestamp_ = 0;
264 if (&codec_ != inst) {
265 codec_ = *inst;
266 }
asaperssona9455ab2015-07-31 06:10:09 -0700267
hta257dc392016-10-25 09:05:06 -0700268 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
269 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700270 if (num_temporal_layers_ == 0)
271 num_temporal_layers_ = 1;
272
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000273 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700274 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800275 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000276 }
nisseeb44b392017-04-28 07:18:05 -0700277 encoded_image_._size =
278 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000279 encoded_image_._buffer = new uint8_t[encoded_image_._size];
280 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700281 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000282 // pointer will be set in encode. Setting align to 1, as it is meaningless
283 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700284 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
285 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000286 // Populate encoder configuration with default values.
287 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
288 return WEBRTC_VIDEO_CODEC_ERROR;
289 }
290 config_->g_w = codec_.width;
291 config_->g_h = codec_.height;
292 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
asapersson15dcb382017-06-08 02:55:08 -0700293 config_->g_error_resilient = inst->VP9().resilienceOn ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000294 // Setting the time base of the codec.
295 config_->g_timebase.num = 1;
296 config_->g_timebase.den = 90000;
297 config_->g_lag_in_frames = 0; // 0- no frame lagging
298 config_->g_threads = 1;
299 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700300 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000301 config_->rc_end_usage = VPX_CBR;
302 config_->g_pass = VPX_RC_ONE_PASS;
303 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000304 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000305 config_->rc_undershoot_pct = 50;
306 config_->rc_overshoot_pct = 50;
307 config_->rc_buf_initial_sz = 500;
308 config_->rc_buf_optimal_sz = 600;
309 config_->rc_buf_sz = 1000;
310 // Set the maximum target size of any key-frame.
311 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700312 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000313 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700314 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100315 // Needs to be set (in svc mode) to get correct periodic key frame interval
316 // (will have no effect in non-svc).
317 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000318 } else {
319 config_->kf_mode = VPX_KF_DISABLED;
320 }
hta257dc392016-10-25 09:05:06 -0700321 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000322 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800323 config_->g_threads =
324 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700325
Marco6e89b252015-07-07 14:40:38 -0700326 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700327
328 // TODO(asapersson): Check configuration of temporal switch up and increase
329 // pattern length.
hta257dc392016-10-25 09:05:06 -0700330 is_flexible_mode_ = inst->VP9().flexibleMode;
philipelcfc319b2015-11-10 07:17:23 -0800331 if (is_flexible_mode_) {
332 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
333 config_->ts_number_layers = num_temporal_layers_;
334 if (codec_.mode == kScreensharing)
335 spatial_layer_->ConfigureBitrate(inst->startBitrate, 0);
336 } else if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700337 gof_.SetGofInfoVP9(kTemporalStructureMode1);
338 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
339 config_->ts_number_layers = 1;
340 config_->ts_rate_decimator[0] = 1;
341 config_->ts_periodicity = 1;
342 config_->ts_layer_id[0] = 0;
343 } else if (num_temporal_layers_ == 2) {
344 gof_.SetGofInfoVP9(kTemporalStructureMode2);
345 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
346 config_->ts_number_layers = 2;
347 config_->ts_rate_decimator[0] = 2;
348 config_->ts_rate_decimator[1] = 1;
349 config_->ts_periodicity = 2;
350 config_->ts_layer_id[0] = 0;
351 config_->ts_layer_id[1] = 1;
352 } else if (num_temporal_layers_ == 3) {
353 gof_.SetGofInfoVP9(kTemporalStructureMode3);
354 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
355 config_->ts_number_layers = 3;
356 config_->ts_rate_decimator[0] = 4;
357 config_->ts_rate_decimator[1] = 2;
358 config_->ts_rate_decimator[2] = 1;
359 config_->ts_periodicity = 4;
360 config_->ts_layer_id[0] = 0;
361 config_->ts_layer_id[1] = 2;
362 config_->ts_layer_id[2] = 1;
363 config_->ts_layer_id[3] = 2;
364 } else {
365 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
366 }
367
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000368 return InitAndSetControlSettings(inst);
369}
370
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000371int VP9EncoderImpl::NumberOfThreads(int width,
372 int height,
373 int number_of_cores) {
374 // Keep the number of encoder threads equal to the possible number of column
375 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
376 if (width * height >= 1280 * 720 && number_of_cores > 4) {
377 return 4;
jianj23173a32017-07-12 16:11:09 -0700378 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000379 return 2;
380 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800381 // Use 2 threads for low res on ARM.
382#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
383 defined(WEBRTC_ANDROID)
384 if (width * height >= 320 * 180 && number_of_cores > 2) {
385 return 2;
386 }
387#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000388 // 1 thread less than VGA.
389 return 1;
390 }
391}
392
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000393int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100394 // Set QP-min/max per spatial and temporal layer.
395 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
396 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800397 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
398 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100399 }
asaperssona9455ab2015-07-31 06:10:09 -0700400 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800401 if (ExplicitlyConfiguredSpatialLayers()) {
402 for (int i = 0; i < num_spatial_layers_; ++i) {
403 const auto& layer = codec_.spatialLayers[i];
Sergey Silkin13e74342018-03-02 12:28:00 +0100404 const int scale_factor = codec_.width / layer.width;
405 RTC_DCHECK_GT(scale_factor, 0);
406
407 // Ensure scaler factor is integer.
408 if (scale_factor * layer.width != codec_.width) {
409 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
410 }
411
412 // Ensure scale factor is the same in both dimensions.
413 if (scale_factor * layer.height != codec_.height) {
414 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
415 }
416
417 // Ensure scale factor is power of two.
418 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
419 if (!is_pow_of_two) {
420 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
421 }
422
423 svc_params_.scaling_factor_num[i] = 1;
424 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800425 }
426 } else {
427 int scaling_factor_num = 256;
428 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800429 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800430 svc_params_.scaling_factor_num[i] = scaling_factor_num;
431 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800432 if (codec_.mode != kScreensharing)
433 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800434 }
asaperssona9455ab2015-07-31 06:10:09 -0700435 }
436
Sergey Silkin86684962018-03-28 19:32:37 +0200437 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200438 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200439 inst->startBitrate * 1000, inst->maxFramerate);
440 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700441 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
442 }
443
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000444 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
445 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
446 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000447 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
448 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
449 rc_max_intra_target_);
450 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700451 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700452
jianj822e5932017-07-12 16:09:58 -0700453 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700454 vpx_codec_control(
455 encoder_, VP9E_SET_SVC,
456 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
457 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
458 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800459 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700460 }
461 // Register callback for getting each spatial layer.
462 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800463 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
464 reinterpret_cast<void*>(this)};
465 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
466 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700467
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000468 // Control function to set the number of column tiles in encoding a frame, in
469 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
470 // The number tile columns will be capped by the encoder based on image size
471 // (minimum width of tile column is 256 pixels, maximum is 4096).
472 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700473
474 // Turn on row-based multithreading.
475 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700476
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700477#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
478 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700479 // Do not enable the denoiser on ARM since optimization is pending.
480 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000481 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700482 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000483#endif
jianj6bf57e32017-06-05 13:43:49 -0700484
ivica242d6382015-09-04 06:13:23 -0700485 if (codec_.mode == kScreensharing) {
486 // Adjust internal parameters to screen content.
487 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700488 }
Marco2520e722015-09-16 14:05:00 -0700489 // Enable encoder skip of static/low content blocks.
490 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000491 inited_ = true;
492 return WEBRTC_VIDEO_CODEC_OK;
493}
494
495uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
496 // Set max to the optimal buffer level (normalized by target BR),
497 // and scaled by a scale_par.
498 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
499 // This value is presented in percentage of perFrameBw:
500 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
501 // The target in % is as follows:
502 float scale_par = 0.5;
503 uint32_t target_pct =
504 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
505 // Don't go below 3 times the per frame bandwidth.
506 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800507 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000508}
509
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700510int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000511 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700512 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000513 if (!inited_) {
514 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
515 }
sprang3958ed82017-08-17 08:12:10 -0700516 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000517 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
518 }
Peter Boström49e196a2015-10-23 15:58:18 +0200519 FrameType frame_type = kVideoFrameDelta;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000520 // We only support one stream at the moment.
521 if (frame_types && frame_types->size() > 0) {
522 frame_type = (*frame_types)[0];
523 }
kwiberg352444f2016-11-28 15:58:53 -0800524 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
525 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700526
527 // Set input image for use in the callback.
528 // This was necessary since you need some information from input_image.
529 // You can save only the necessary information (such as timestamp) instead of
530 // doing this.
531 input_image_ = &input_image;
532
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000533 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
534 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000535 // Image in vpx_image_t format.
536 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000537 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
538 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
539 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
540 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
541 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
542 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000543
philipelcfc319b2015-11-10 07:17:23 -0800544 vpx_enc_frame_flags_t flags = 0;
Peter Boström49e196a2015-10-23 15:58:18 +0200545 bool send_keyframe = (frame_type == kVideoFrameKey);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000546 if (send_keyframe) {
547 // Key frame request from caller.
548 flags = VPX_EFLAG_FORCE_KF;
549 }
philipelcfc319b2015-11-10 07:17:23 -0800550
551 if (is_flexible_mode_) {
552 SuperFrameRefSettings settings;
553
554 // These structs are copied when calling vpx_codec_control,
555 // therefore it is ok for them to go out of scope.
556 vpx_svc_ref_frame_config enc_layer_conf;
557 vpx_svc_layer_id layer_id;
558
559 if (codec_.mode == kRealtimeVideo) {
560 // Real time video not yet implemented in flexible mode.
561 RTC_NOTREACHED();
562 } else {
563 settings = spatial_layer_->GetSuperFrameSettings(input_image.timestamp(),
564 send_keyframe);
565 }
566 enc_layer_conf = GenerateRefsAndFlags(settings);
567 layer_id.temporal_layer_id = 0;
568 layer_id.spatial_layer_id = settings.start_layer;
569 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
570 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
571 }
572
sprang3958ed82017-08-17 08:12:10 -0700573 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000574 uint32_t duration = 90000 / codec_.maxFramerate;
575 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
576 VPX_DL_REALTIME)) {
577 return WEBRTC_VIDEO_CODEC_ERROR;
578 }
579 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700580
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200581 const bool end_of_superframe = true;
582 DeliverBufferedFrame(end_of_superframe);
583
asaperssona9455ab2015-07-31 06:10:09 -0700584 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000585}
586
587void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800588 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200589 uint32_t timestamp,
590 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700591 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000592 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700593 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800594 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200595
596 vp9_info->first_frame_in_picture = first_frame_in_picture;
Åsa Perssonff24c042015-12-04 10:58:08 +0100597 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700598 vp9_info->inter_pic_predicted =
599 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700600 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
601 vp9_info->ss_data_available =
602 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
603 ? true
604 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700605
606 vpx_svc_layer_id_t layer_id = {0};
607 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
608
sprang3958ed82017-08-17 08:12:10 -0700609 RTC_CHECK_GT(num_temporal_layers_, 0);
610 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700611 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700612 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700613 vp9_info->temporal_idx = kNoTemporalIdx;
614 } else {
615 vp9_info->temporal_idx = layer_id.temporal_layer_id;
616 }
617 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700618 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700619 vp9_info->spatial_idx = kNoSpatialIdx;
620 } else {
621 vp9_info->spatial_idx = layer_id.spatial_layer_id;
622 }
623 if (layer_id.spatial_layer_id != 0) {
624 vp9_info->ss_data_available = false;
625 }
626
asaperssona9455ab2015-07-31 06:10:09 -0700627 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800628 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700629
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200630 if (first_frame_in_picture) {
asaperssona9455ab2015-07-31 06:10:09 -0700631 // TODO(asapersson): this info has to be obtained from the encoder.
632 vp9_info->inter_layer_predicted = false;
asapersson00ac85e2015-11-11 05:30:48 -0800633 ++frames_since_kf_;
asaperssona9455ab2015-07-31 06:10:09 -0700634 } else {
635 // TODO(asapersson): this info has to be obtained from the encoder.
636 vp9_info->inter_layer_predicted = true;
637 }
638
asapersson00ac85e2015-11-11 05:30:48 -0800639 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
640 frames_since_kf_ = 0;
641 }
642
ivica7f6a6fc2015-09-08 02:40:29 -0700643 // Always populate this, so that the packetizer can properly set the marker
644 // bit.
645 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800646
647 vp9_info->num_ref_pics = 0;
648 if (vp9_info->flexible_mode) {
649 vp9_info->gof_idx = kNoGofIdx;
650 vp9_info->num_ref_pics = num_ref_pics_[layer_id.spatial_layer_id];
651 for (int i = 0; i < num_ref_pics_[layer_id.spatial_layer_id]; ++i) {
652 vp9_info->p_diff[i] = p_diff_[layer_id.spatial_layer_id][i];
653 }
654 } else {
655 vp9_info->gof_idx =
656 static_cast<uint8_t>(frames_since_kf_ % gof_.num_frames_in_gof);
asapersson00ac85e2015-11-11 05:30:48 -0800657 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800658 }
philipelcfc319b2015-11-10 07:17:23 -0800659
asaperssona9455ab2015-07-31 06:10:09 -0700660 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700661 vp9_info->spatial_layer_resolution_present = true;
662 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
663 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800664 svc_params_.scaling_factor_num[i] /
665 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700666 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800667 svc_params_.scaling_factor_num[i] /
668 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700669 }
670 if (!vp9_info->flexible_mode) {
671 vp9_info->gof.CopyGofInfoVP9(gof_);
672 }
673 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000674}
675
asaperssona9455ab2015-07-31 06:10:09 -0700676int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800677 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700678
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200679 if (pkt->data.frame.sz == 0) {
680 // Ignore dropped frame.
681 return WEBRTC_VIDEO_CODEC_OK;
682 }
683
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200684 vpx_svc_layer_id_t layer_id = {0};
685 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
686
687 const bool first_frame_in_picture = encoded_image_._length == 0;
688 // Ensure we don't buffer layers of previous picture (superframe).
689 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
690
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200691 const bool end_of_superframe = false;
692 DeliverBufferedFrame(end_of_superframe);
693
asaperssond9f641e2016-01-21 01:11:35 -0800694 if (pkt->data.frame.sz > encoded_image_._size) {
695 delete[] encoded_image_._buffer;
696 encoded_image_._size = pkt->data.frame.sz;
697 encoded_image_._buffer = new uint8_t[encoded_image_._size];
698 }
asapersson86956de2016-01-26 01:05:20 -0800699 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
700 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800701
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200702 if (is_flexible_mode_ && codec_.mode == kScreensharing) {
philipelcfc319b2015-11-10 07:17:23 -0800703 spatial_layer_->LayerFrameEncoded(
704 static_cast<unsigned int>(encoded_image_._length),
705 layer_id.spatial_layer_id);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200706 }
philipelcfc319b2015-11-10 07:17:23 -0800707
asaperssona9455ab2015-07-31 06:10:09 -0700708 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800709 encoded_image_._frameType = kVideoFrameDelta;
asaperssona9455ab2015-07-31 06:10:09 -0700710 if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
Peter Boström49e196a2015-10-23 15:58:18 +0200711 encoded_image_._frameType = kVideoFrameKey;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000712 }
asapersson86956de2016-01-26 01:05:20 -0800713 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
714
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200715 memset(&codec_specific_, 0, sizeof(codec_specific_));
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200716 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
717 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -0700718
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200719 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
720 encoded_image_._timeStamp = input_image_->timestamp();
721 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
722 encoded_image_.rotation_ = input_image_->rotation();
723 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
724 ? VideoContentType::SCREENSHARE
725 : VideoContentType::UNSPECIFIED;
726 encoded_image_._encodedHeight =
727 pkt->data.frame.height[layer_id.spatial_layer_id];
728 encoded_image_._encodedWidth =
729 pkt->data.frame.width[layer_id.spatial_layer_id];
730 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
731 int qp = -1;
732 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
733 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700734
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000735 return WEBRTC_VIDEO_CODEC_OK;
736}
737
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200738void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_superframe) {
739 if (encoded_image_._length > 0) {
740 codec_specific_.codecSpecific.VP9.end_of_superframe = end_of_superframe;
741
742 // No data partitioning in VP9, so 1 partition only.
743 int part_idx = 0;
744 RTPFragmentationHeader frag_info;
745 frag_info.VerifyAndAllocateFragmentationHeader(1);
746 frag_info.fragmentationOffset[part_idx] = 0;
747 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
748 frag_info.fragmentationPlType[part_idx] = 0;
749 frag_info.fragmentationTimeDiff[part_idx] = 0;
750
751 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
752 &frag_info);
753 encoded_image_._length = 0;
754 }
755}
756
philipelcfc319b2015-11-10 07:17:23 -0800757vpx_svc_ref_frame_config VP9EncoderImpl::GenerateRefsAndFlags(
758 const SuperFrameRefSettings& settings) {
759 static const vpx_enc_frame_flags_t kAllFlags =
760 VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_LAST |
761 VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF;
762 vpx_svc_ref_frame_config sf_conf = {};
763 if (settings.is_keyframe) {
764 // Used later on to make sure we don't make any invalid references.
765 memset(buffer_updated_at_frame_, -1, sizeof(buffer_updated_at_frame_));
766 for (int layer = settings.start_layer; layer <= settings.stop_layer;
767 ++layer) {
768 num_ref_pics_[layer] = 0;
769 buffer_updated_at_frame_[settings.layer[layer].upd_buf] = frames_encoded_;
770 // When encoding a keyframe only the alt_fb_idx is used
771 // to specify which layer ends up in which buffer.
772 sf_conf.alt_fb_idx[layer] = settings.layer[layer].upd_buf;
773 }
774 } else {
775 for (int layer_idx = settings.start_layer; layer_idx <= settings.stop_layer;
776 ++layer_idx) {
777 vpx_enc_frame_flags_t layer_flags = kAllFlags;
778 num_ref_pics_[layer_idx] = 0;
779 int8_t refs[3] = {settings.layer[layer_idx].ref_buf1,
780 settings.layer[layer_idx].ref_buf2,
781 settings.layer[layer_idx].ref_buf3};
782
783 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
784 if (refs[ref_idx] == -1)
785 continue;
786
787 RTC_DCHECK_GE(refs[ref_idx], 0);
788 RTC_DCHECK_LE(refs[ref_idx], 7);
789 // Easier to remove flags from all flags rather than having to
790 // build the flags from 0.
791 switch (num_ref_pics_[layer_idx]) {
792 case 0: {
793 sf_conf.lst_fb_idx[layer_idx] = refs[ref_idx];
794 layer_flags &= ~VP8_EFLAG_NO_REF_LAST;
795 break;
796 }
797 case 1: {
798 sf_conf.gld_fb_idx[layer_idx] = refs[ref_idx];
799 layer_flags &= ~VP8_EFLAG_NO_REF_GF;
800 break;
801 }
802 case 2: {
803 sf_conf.alt_fb_idx[layer_idx] = refs[ref_idx];
804 layer_flags &= ~VP8_EFLAG_NO_REF_ARF;
805 break;
806 }
807 }
808 // Make sure we don't reference a buffer that hasn't been
809 // used at all or hasn't been used since a keyframe.
810 RTC_DCHECK_NE(buffer_updated_at_frame_[refs[ref_idx]], -1);
811
812 p_diff_[layer_idx][num_ref_pics_[layer_idx]] =
813 frames_encoded_ - buffer_updated_at_frame_[refs[ref_idx]];
814 num_ref_pics_[layer_idx]++;
815 }
816
817 bool upd_buf_same_as_a_ref = false;
818 if (settings.layer[layer_idx].upd_buf != -1) {
819 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
820 if (settings.layer[layer_idx].upd_buf == refs[ref_idx]) {
821 switch (ref_idx) {
822 case 0: {
823 layer_flags &= ~VP8_EFLAG_NO_UPD_LAST;
824 break;
825 }
826 case 1: {
827 layer_flags &= ~VP8_EFLAG_NO_UPD_GF;
828 break;
829 }
830 case 2: {
831 layer_flags &= ~VP8_EFLAG_NO_UPD_ARF;
832 break;
833 }
834 }
835 upd_buf_same_as_a_ref = true;
836 break;
837 }
838 }
839 if (!upd_buf_same_as_a_ref) {
840 // If we have three references and a buffer is specified to be
841 // updated, then that buffer must be the same as one of the
842 // three references.
843 RTC_CHECK_LT(num_ref_pics_[layer_idx], kMaxVp9RefPics);
844
845 sf_conf.alt_fb_idx[layer_idx] = settings.layer[layer_idx].upd_buf;
846 layer_flags ^= VP8_EFLAG_NO_UPD_ARF;
847 }
848
849 int updated_buffer = settings.layer[layer_idx].upd_buf;
850 buffer_updated_at_frame_[updated_buffer] = frames_encoded_;
851 sf_conf.frame_flags[layer_idx] = layer_flags;
852 }
853 }
854 }
855 ++frames_encoded_;
856 return sf_conf;
857}
858
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000859int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000860 return WEBRTC_VIDEO_CODEC_OK;
861}
862
863int VP9EncoderImpl::RegisterEncodeCompleteCallback(
864 EncodedImageCallback* callback) {
865 encoded_complete_callback_ = callback;
866 return WEBRTC_VIDEO_CODEC_OK;
867}
868
Peter Boströmb7d9a972015-12-18 16:01:11 +0100869const char* VP9EncoderImpl::ImplementationName() const {
870 return "libvpx";
871}
872
Peter Boström12996152016-05-14 02:03:18 +0200873bool VP9Decoder::IsSupported() {
874 return true;
875}
876
Magnus Jedvert46a27652017-11-13 14:10:02 +0100877std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
878 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000879}
880
881VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700882 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000883 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700884 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +0200885 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000886
887VP9DecoderImpl::~VP9DecoderImpl() {
888 inited_ = true; // in order to do the actual release
889 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200890 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
891 if (num_buffers_in_use > 0) {
892 // The frame buffers are reference counted and frames are exposed after
893 // decoding. There may be valid usage cases where previous frames are still
894 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100895 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
896 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200897 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000898}
899
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000900int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000901 int ret_val = Release();
902 if (ret_val < 0) {
903 return ret_val;
904 }
sprang3958ed82017-08-17 08:12:10 -0700905 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000906 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000907 }
philipelcce46fc2015-12-21 03:04:49 -0800908 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000909 // Setting number of threads to a constant value (1)
910 cfg.threads = 1;
911 cfg.h = cfg.w = 0; // set after decode
912 vpx_codec_flags_t flags = 0;
913 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
914 return WEBRTC_VIDEO_CODEC_MEMORY;
915 }
Henrik Boström9695d852015-05-06 10:42:15 +0200916
917 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
918 return WEBRTC_VIDEO_CODEC_MEMORY;
919 }
920
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000921 inited_ = true;
922 // Always start with a complete key frame.
923 key_frame_required_ = true;
924 return WEBRTC_VIDEO_CODEC_OK;
925}
926
927int VP9DecoderImpl::Decode(const EncodedImage& input_image,
928 bool missing_frames,
929 const RTPFragmentationHeader* fragmentation,
930 const CodecSpecificInfo* codec_specific_info,
931 int64_t /*render_time_ms*/) {
932 if (!inited_) {
933 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
934 }
sprang3958ed82017-08-17 08:12:10 -0700935 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000936 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
937 }
938 // Always start with a complete key frame.
939 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200940 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000941 return WEBRTC_VIDEO_CODEC_ERROR;
942 // We have a key frame - is it complete?
943 if (input_image._completeFrame) {
944 key_frame_required_ = false;
945 } else {
946 return WEBRTC_VIDEO_CODEC_ERROR;
947 }
948 }
sprang3958ed82017-08-17 08:12:10 -0700949 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000950 vpx_image_t* img;
951 uint8_t* buffer = input_image._buffer;
952 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700953 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000954 }
Henrik Boström9695d852015-05-06 10:42:15 +0200955 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
956 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800957 if (vpx_codec_decode(decoder_, buffer,
958 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000959 VPX_DL_REALTIME)) {
960 return WEBRTC_VIDEO_CODEC_ERROR;
961 }
Henrik Boström9695d852015-05-06 10:42:15 +0200962 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
963 // It may be released by libvpx during future vpx_codec_decode or
964 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000965 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -0800966 int qp;
967 vpx_codec_err_t vpx_ret =
968 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
969 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
970 int ret =
971 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000972 if (ret != 0) {
973 return ret;
974 }
975 return WEBRTC_VIDEO_CODEC_OK;
976}
977
asapersson1490f7a2016-09-23 02:09:46 -0700978int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
979 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -0800980 int64_t ntp_time_ms,
981 int qp) {
sprang3958ed82017-08-17 08:12:10 -0700982 if (img == nullptr) {
983 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000984 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
985 }
Henrik Boström9695d852015-05-06 10:42:15 +0200986
987 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -0800988 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +0200989 // vpx_codec_decode calls or vpx_codec_destroy).
990 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
991 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700992 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +0200993 // using a WrappedI420Buffer.
994 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
995 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -0800996 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
997 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
998 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
999 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001000 // WrappedI420Buffer's mechanism for allowing the release of its frame
1001 // buffer is through a callback function. This is where we should
1002 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -08001003 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +02001004
nisseca6d5d12016-06-17 05:03:04 -07001005 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
1006 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -07001007 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -07001008
Oskar Sundbom6bd39022017-11-16 10:54:49 +01001009 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001010 return WEBRTC_VIDEO_CODEC_OK;
1011}
1012
1013int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1014 DecodedImageCallback* callback) {
1015 decode_complete_callback_ = callback;
1016 return WEBRTC_VIDEO_CODEC_OK;
1017}
1018
1019int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001020 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1021
sprang3958ed82017-08-17 08:12:10 -07001022 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001023 if (inited_) {
1024 // When a codec is destroyed libvpx will release any buffers of
1025 // |frame_buffer_pool_| it is currently using.
1026 if (vpx_codec_destroy(decoder_)) {
1027 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1028 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001029 }
1030 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001031 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001032 }
Henrik Boström9695d852015-05-06 10:42:15 +02001033 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1034 // still referenced externally are deleted once fully released, not returning
1035 // to the pool.
1036 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001037 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001038 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001039}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001040
1041const char* VP9DecoderImpl::ImplementationName() const {
1042 return "libvpx";
1043}
1044
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001045} // namespace webrtc