blob: c1f7d5d5aa9b748031e2735a5e833a611776ac90 [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
Sergey Silkin86684962018-03-28 19:32:37 +0200126bool VP9EncoderImpl::SetSvcRates(const BitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700127 uint8_t i = 0;
128
Sergey Silkin86684962018-03-28 19:32:37 +0200129 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
130 spatial_layer_->ConfigureBitrate(bitrate_allocation.get_sum_kbps(), 0);
131
sprangce4aef12015-11-02 07:23:20 -0800132 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200133 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
134 config_->ss_target_bitrate[sl_idx] =
135 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
136
137 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
138 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
139 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
140 }
sprangce4aef12015-11-02 07:23:20 -0800141 }
142 } else {
143 float rate_ratio[VPX_MAX_LAYERS] = {0};
144 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700145
sprangce4aef12015-11-02 07:23:20 -0800146 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800147 if (svc_params_.scaling_factor_num[i] <= 0 ||
148 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100149 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800150 return false;
151 }
152 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800153 static_cast<float>(svc_params_.scaling_factor_num[i]) /
154 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800155 total += rate_ratio[i];
156 }
157
158 for (i = 0; i < num_spatial_layers_; ++i) {
159 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
160 config_->rc_target_bitrate * rate_ratio[i] / total);
161 if (num_temporal_layers_ == 1) {
162 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
163 } else if (num_temporal_layers_ == 2) {
164 config_->layer_target_bitrate[i * num_temporal_layers_] =
165 config_->ss_target_bitrate[i] * 2 / 3;
166 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
167 config_->ss_target_bitrate[i];
168 } else if (num_temporal_layers_ == 3) {
169 config_->layer_target_bitrate[i * num_temporal_layers_] =
170 config_->ss_target_bitrate[i] / 2;
171 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
172 config_->layer_target_bitrate[i * num_temporal_layers_] +
173 (config_->ss_target_bitrate[i] / 4);
174 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
175 config_->ss_target_bitrate[i];
176 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100177 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
178 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800179 return false;
180 }
asaperssona9455ab2015-07-31 06:10:09 -0700181 }
182 }
183
184 // For now, temporal layers only supported when having one spatial layer.
185 if (num_spatial_layers_ == 1) {
186 for (i = 0; i < num_temporal_layers_; ++i) {
187 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
188 }
189 }
190
191 return true;
192}
193
Erik Språng08127a92016-11-16 16:41:30 +0100194int VP9EncoderImpl::SetRateAllocation(
195 const BitrateAllocation& bitrate_allocation,
196 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000197 if (!inited_) {
198 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
199 }
200 if (encoder_->err) {
201 return WEBRTC_VIDEO_CODEC_ERROR;
202 }
Erik Språng08127a92016-11-16 16:41:30 +0100203 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000204 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
205 }
206 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100207 if (codec_.maxBitrate > 0 &&
208 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
209 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000210 }
Erik Språng08127a92016-11-16 16:41:30 +0100211
Erik Språng08127a92016-11-16 16:41:30 +0100212 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700213
Sergey Silkin86684962018-03-28 19:32:37 +0200214 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700215 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
216 }
217
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000218 // Update encoder context
219 if (vpx_codec_enc_config_set(encoder_, config_)) {
220 return WEBRTC_VIDEO_CODEC_ERROR;
221 }
222 return WEBRTC_VIDEO_CODEC_OK;
223}
224
225int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
226 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000227 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700228 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000229 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
230 }
231 if (inst->maxFramerate < 1) {
232 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
233 }
234 // Allow zero to represent an unspecified maxBitRate
235 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
236 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
237 }
238 if (inst->width < 1 || inst->height < 1) {
239 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
240 }
241 if (number_of_cores < 1) {
242 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
243 }
hta257dc392016-10-25 09:05:06 -0700244 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700245 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
246 }
ilnik2a8c2f52017-02-15 02:23:28 -0800247 // libvpx probably does not support more than 3 spatial layers.
248 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700249 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
250 }
philipelcfc319b2015-11-10 07:17:23 -0800251
asapersson86956de2016-01-26 01:05:20 -0800252 int ret_val = Release();
253 if (ret_val < 0) {
254 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000255 }
sprang3958ed82017-08-17 08:12:10 -0700256 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000257 encoder_ = new vpx_codec_ctx_t;
258 }
sprang3958ed82017-08-17 08:12:10 -0700259 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000260 config_ = new vpx_codec_enc_cfg_t;
261 }
262 timestamp_ = 0;
263 if (&codec_ != inst) {
264 codec_ = *inst;
265 }
asaperssona9455ab2015-07-31 06:10:09 -0700266
hta257dc392016-10-25 09:05:06 -0700267 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
268 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700269 if (num_temporal_layers_ == 0)
270 num_temporal_layers_ = 1;
271
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000272 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700273 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800274 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000275 }
nisseeb44b392017-04-28 07:18:05 -0700276 encoded_image_._size =
277 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000278 encoded_image_._buffer = new uint8_t[encoded_image_._size];
279 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700280 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000281 // pointer will be set in encode. Setting align to 1, as it is meaningless
282 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700283 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
284 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000285 // Populate encoder configuration with default values.
286 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
287 return WEBRTC_VIDEO_CODEC_ERROR;
288 }
289 config_->g_w = codec_.width;
290 config_->g_h = codec_.height;
291 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
asapersson15dcb382017-06-08 02:55:08 -0700292 config_->g_error_resilient = inst->VP9().resilienceOn ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000293 // Setting the time base of the codec.
294 config_->g_timebase.num = 1;
295 config_->g_timebase.den = 90000;
296 config_->g_lag_in_frames = 0; // 0- no frame lagging
297 config_->g_threads = 1;
298 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700299 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000300 config_->rc_end_usage = VPX_CBR;
301 config_->g_pass = VPX_RC_ONE_PASS;
302 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000303 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000304 config_->rc_undershoot_pct = 50;
305 config_->rc_overshoot_pct = 50;
306 config_->rc_buf_initial_sz = 500;
307 config_->rc_buf_optimal_sz = 600;
308 config_->rc_buf_sz = 1000;
309 // Set the maximum target size of any key-frame.
310 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700311 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000312 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700313 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100314 // Needs to be set (in svc mode) to get correct periodic key frame interval
315 // (will have no effect in non-svc).
316 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000317 } else {
318 config_->kf_mode = VPX_KF_DISABLED;
319 }
hta257dc392016-10-25 09:05:06 -0700320 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000321 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800322 config_->g_threads =
323 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700324
Marco6e89b252015-07-07 14:40:38 -0700325 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700326
327 // TODO(asapersson): Check configuration of temporal switch up and increase
328 // pattern length.
hta257dc392016-10-25 09:05:06 -0700329 is_flexible_mode_ = inst->VP9().flexibleMode;
philipelcfc319b2015-11-10 07:17:23 -0800330 if (is_flexible_mode_) {
331 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
332 config_->ts_number_layers = num_temporal_layers_;
333 if (codec_.mode == kScreensharing)
334 spatial_layer_->ConfigureBitrate(inst->startBitrate, 0);
335 } else if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700336 gof_.SetGofInfoVP9(kTemporalStructureMode1);
337 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
338 config_->ts_number_layers = 1;
339 config_->ts_rate_decimator[0] = 1;
340 config_->ts_periodicity = 1;
341 config_->ts_layer_id[0] = 0;
342 } else if (num_temporal_layers_ == 2) {
343 gof_.SetGofInfoVP9(kTemporalStructureMode2);
344 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
345 config_->ts_number_layers = 2;
346 config_->ts_rate_decimator[0] = 2;
347 config_->ts_rate_decimator[1] = 1;
348 config_->ts_periodicity = 2;
349 config_->ts_layer_id[0] = 0;
350 config_->ts_layer_id[1] = 1;
351 } else if (num_temporal_layers_ == 3) {
352 gof_.SetGofInfoVP9(kTemporalStructureMode3);
353 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
354 config_->ts_number_layers = 3;
355 config_->ts_rate_decimator[0] = 4;
356 config_->ts_rate_decimator[1] = 2;
357 config_->ts_rate_decimator[2] = 1;
358 config_->ts_periodicity = 4;
359 config_->ts_layer_id[0] = 0;
360 config_->ts_layer_id[1] = 2;
361 config_->ts_layer_id[2] = 1;
362 config_->ts_layer_id[3] = 2;
363 } else {
364 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
365 }
366
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000367 return InitAndSetControlSettings(inst);
368}
369
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000370int VP9EncoderImpl::NumberOfThreads(int width,
371 int height,
372 int number_of_cores) {
373 // Keep the number of encoder threads equal to the possible number of column
374 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
375 if (width * height >= 1280 * 720 && number_of_cores > 4) {
376 return 4;
jianj23173a32017-07-12 16:11:09 -0700377 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000378 return 2;
379 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800380 // Use 2 threads for low res on ARM.
381#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
382 defined(WEBRTC_ANDROID)
383 if (width * height >= 320 * 180 && number_of_cores > 2) {
384 return 2;
385 }
386#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000387 // 1 thread less than VGA.
388 return 1;
389 }
390}
391
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000392int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100393 // Set QP-min/max per spatial and temporal layer.
394 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
395 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800396 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
397 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100398 }
asaperssona9455ab2015-07-31 06:10:09 -0700399 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800400 if (ExplicitlyConfiguredSpatialLayers()) {
401 for (int i = 0; i < num_spatial_layers_; ++i) {
402 const auto& layer = codec_.spatialLayers[i];
Sergey Silkin13e74342018-03-02 12:28:00 +0100403 const int scale_factor = codec_.width / layer.width;
404 RTC_DCHECK_GT(scale_factor, 0);
405
406 // Ensure scaler factor is integer.
407 if (scale_factor * layer.width != codec_.width) {
408 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
409 }
410
411 // Ensure scale factor is the same in both dimensions.
412 if (scale_factor * layer.height != codec_.height) {
413 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
414 }
415
416 // Ensure scale factor is power of two.
417 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
418 if (!is_pow_of_two) {
419 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
420 }
421
422 svc_params_.scaling_factor_num[i] = 1;
423 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800424 }
425 } else {
426 int scaling_factor_num = 256;
427 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800428 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800429 svc_params_.scaling_factor_num[i] = scaling_factor_num;
430 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800431 if (codec_.mode != kScreensharing)
432 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800433 }
asaperssona9455ab2015-07-31 06:10:09 -0700434 }
435
Sergey Silkin86684962018-03-28 19:32:37 +0200436 SvcRateAllocator init_allocator(codec_);
437 BitrateAllocation allocation = init_allocator.GetAllocation(
438 inst->startBitrate * 1000, inst->maxFramerate);
439 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700440 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
441 }
442
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000443 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
444 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
445 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000446 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
447 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
448 rc_max_intra_target_);
449 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700450 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700451
jianj822e5932017-07-12 16:09:58 -0700452 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700453 vpx_codec_control(
454 encoder_, VP9E_SET_SVC,
455 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
456 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
457 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800458 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700459 }
460 // Register callback for getting each spatial layer.
461 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800462 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
463 reinterpret_cast<void*>(this)};
464 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
465 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700466
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000467 // Control function to set the number of column tiles in encoding a frame, in
468 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
469 // The number tile columns will be capped by the encoder based on image size
470 // (minimum width of tile column is 256 pixels, maximum is 4096).
471 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700472
473 // Turn on row-based multithreading.
474 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700475
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700476#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
477 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700478 // Do not enable the denoiser on ARM since optimization is pending.
479 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000480 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700481 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000482#endif
jianj6bf57e32017-06-05 13:43:49 -0700483
ivica242d6382015-09-04 06:13:23 -0700484 if (codec_.mode == kScreensharing) {
485 // Adjust internal parameters to screen content.
486 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700487 }
Marco2520e722015-09-16 14:05:00 -0700488 // Enable encoder skip of static/low content blocks.
489 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
Sergey Silkine803dbe2018-04-03 14:13:04 +0200490
491 // Turn off per-layer frame dropping.
492 vpx_svc_frame_drop_t svc_frame_drop;
493 svc_frame_drop.framedrop_mode = CONSTRAINED_LAYER_DROP;
494 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
495 svc_frame_drop.framedrop_thresh[sl_idx] = config_->rc_dropframe_thresh;
496 }
497 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_frame_drop);
498
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000499 inited_ = true;
500 return WEBRTC_VIDEO_CODEC_OK;
501}
502
503uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
504 // Set max to the optimal buffer level (normalized by target BR),
505 // and scaled by a scale_par.
506 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
507 // This value is presented in percentage of perFrameBw:
508 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
509 // The target in % is as follows:
510 float scale_par = 0.5;
511 uint32_t target_pct =
512 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
513 // Don't go below 3 times the per frame bandwidth.
514 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800515 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000516}
517
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700518int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000519 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700520 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000521 if (!inited_) {
522 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
523 }
sprang3958ed82017-08-17 08:12:10 -0700524 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000525 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
526 }
Peter Boström49e196a2015-10-23 15:58:18 +0200527 FrameType frame_type = kVideoFrameDelta;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000528 // We only support one stream at the moment.
529 if (frame_types && frame_types->size() > 0) {
530 frame_type = (*frame_types)[0];
531 }
kwiberg352444f2016-11-28 15:58:53 -0800532 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
533 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700534
535 // Set input image for use in the callback.
536 // This was necessary since you need some information from input_image.
537 // You can save only the necessary information (such as timestamp) instead of
538 // doing this.
539 input_image_ = &input_image;
540
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000541 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
542 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000543 // Image in vpx_image_t format.
544 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000545 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
546 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
547 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
548 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
549 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
550 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000551
philipelcfc319b2015-11-10 07:17:23 -0800552 vpx_enc_frame_flags_t flags = 0;
Peter Boström49e196a2015-10-23 15:58:18 +0200553 bool send_keyframe = (frame_type == kVideoFrameKey);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000554 if (send_keyframe) {
555 // Key frame request from caller.
556 flags = VPX_EFLAG_FORCE_KF;
557 }
philipelcfc319b2015-11-10 07:17:23 -0800558
559 if (is_flexible_mode_) {
560 SuperFrameRefSettings settings;
561
562 // These structs are copied when calling vpx_codec_control,
563 // therefore it is ok for them to go out of scope.
564 vpx_svc_ref_frame_config enc_layer_conf;
565 vpx_svc_layer_id layer_id;
566
567 if (codec_.mode == kRealtimeVideo) {
568 // Real time video not yet implemented in flexible mode.
569 RTC_NOTREACHED();
570 } else {
571 settings = spatial_layer_->GetSuperFrameSettings(input_image.timestamp(),
572 send_keyframe);
573 }
574 enc_layer_conf = GenerateRefsAndFlags(settings);
575 layer_id.temporal_layer_id = 0;
576 layer_id.spatial_layer_id = settings.start_layer;
577 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
578 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
579 }
580
sprang3958ed82017-08-17 08:12:10 -0700581 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000582 uint32_t duration = 90000 / codec_.maxFramerate;
583 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
584 VPX_DL_REALTIME)) {
585 return WEBRTC_VIDEO_CODEC_ERROR;
586 }
587 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700588
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200589 const bool end_of_superframe = true;
590 DeliverBufferedFrame(end_of_superframe);
591
asaperssona9455ab2015-07-31 06:10:09 -0700592 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000593}
594
595void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800596 const vpx_codec_cx_pkt& pkt,
597 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -0700598 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000599 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700600 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800601 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Åsa Perssonff24c042015-12-04 10:58:08 +0100602 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700603 vp9_info->inter_pic_predicted =
604 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700605 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
606 vp9_info->ss_data_available =
607 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
608 ? true
609 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700610
611 vpx_svc_layer_id_t layer_id = {0};
612 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
613
sprang3958ed82017-08-17 08:12:10 -0700614 RTC_CHECK_GT(num_temporal_layers_, 0);
615 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700616 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700617 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700618 vp9_info->temporal_idx = kNoTemporalIdx;
619 } else {
620 vp9_info->temporal_idx = layer_id.temporal_layer_id;
621 }
622 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700623 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700624 vp9_info->spatial_idx = kNoSpatialIdx;
625 } else {
626 vp9_info->spatial_idx = layer_id.spatial_layer_id;
627 }
628 if (layer_id.spatial_layer_id != 0) {
629 vp9_info->ss_data_available = false;
630 }
631
asaperssona9455ab2015-07-31 06:10:09 -0700632 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800633 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700634
philipelcfc319b2015-11-10 07:17:23 -0800635 bool is_first_frame = false;
636 if (is_flexible_mode_) {
637 is_first_frame =
638 layer_id.spatial_layer_id == spatial_layer_->GetStartLayer();
639 } else {
640 is_first_frame = layer_id.spatial_layer_id == 0;
641 }
642
643 if (is_first_frame) {
asaperssona9455ab2015-07-31 06:10:09 -0700644 // TODO(asapersson): this info has to be obtained from the encoder.
645 vp9_info->inter_layer_predicted = false;
asapersson00ac85e2015-11-11 05:30:48 -0800646 ++frames_since_kf_;
asaperssona9455ab2015-07-31 06:10:09 -0700647 } else {
648 // TODO(asapersson): this info has to be obtained from the encoder.
649 vp9_info->inter_layer_predicted = true;
650 }
651
Niels Möllerbb894ff2018-03-15 12:28:53 +0100652 vp9_info->first_frame_in_picture = is_first_frame;
653
asapersson00ac85e2015-11-11 05:30:48 -0800654 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
655 frames_since_kf_ = 0;
656 }
657
ivica7f6a6fc2015-09-08 02:40:29 -0700658 // Always populate this, so that the packetizer can properly set the marker
659 // bit.
660 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800661
662 vp9_info->num_ref_pics = 0;
663 if (vp9_info->flexible_mode) {
664 vp9_info->gof_idx = kNoGofIdx;
665 vp9_info->num_ref_pics = num_ref_pics_[layer_id.spatial_layer_id];
666 for (int i = 0; i < num_ref_pics_[layer_id.spatial_layer_id]; ++i) {
667 vp9_info->p_diff[i] = p_diff_[layer_id.spatial_layer_id][i];
668 }
669 } else {
670 vp9_info->gof_idx =
671 static_cast<uint8_t>(frames_since_kf_ % gof_.num_frames_in_gof);
asapersson00ac85e2015-11-11 05:30:48 -0800672 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800673 }
philipelcfc319b2015-11-10 07:17:23 -0800674
asaperssona9455ab2015-07-31 06:10:09 -0700675 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700676 vp9_info->spatial_layer_resolution_present = true;
677 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
678 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800679 svc_params_.scaling_factor_num[i] /
680 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700681 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800682 svc_params_.scaling_factor_num[i] /
683 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700684 }
685 if (!vp9_info->flexible_mode) {
686 vp9_info->gof.CopyGofInfoVP9(gof_);
687 }
688 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000689}
690
asaperssona9455ab2015-07-31 06:10:09 -0700691int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800692 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700693
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200694 if (pkt->data.frame.sz == 0) {
695 // Ignore dropped frame.
696 return WEBRTC_VIDEO_CODEC_OK;
697 }
698
699 const bool end_of_superframe = false;
700 DeliverBufferedFrame(end_of_superframe);
701
asaperssond9f641e2016-01-21 01:11:35 -0800702 if (pkt->data.frame.sz > encoded_image_._size) {
703 delete[] encoded_image_._buffer;
704 encoded_image_._size = pkt->data.frame.sz;
705 encoded_image_._buffer = new uint8_t[encoded_image_._size];
706 }
asapersson86956de2016-01-26 01:05:20 -0800707 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
708 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800709
philipelcfc319b2015-11-10 07:17:23 -0800710 vpx_svc_layer_id_t layer_id = {0};
711 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
712 if (is_flexible_mode_ && codec_.mode == kScreensharing)
713 spatial_layer_->LayerFrameEncoded(
714 static_cast<unsigned int>(encoded_image_._length),
715 layer_id.spatial_layer_id);
716
asaperssona9455ab2015-07-31 06:10:09 -0700717 // End of frame.
718 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800719 encoded_image_._frameType = kVideoFrameDelta;
asaperssona9455ab2015-07-31 06:10:09 -0700720 if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
Peter Boström49e196a2015-10-23 15:58:18 +0200721 encoded_image_._frameType = kVideoFrameKey;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000722 }
asapersson86956de2016-01-26 01:05:20 -0800723 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
724
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200725 memset(&codec_specific_, 0, sizeof(codec_specific_));
726 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp());
asaperssona9455ab2015-07-31 06:10:09 -0700727
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200728 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
729 encoded_image_._timeStamp = input_image_->timestamp();
730 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
731 encoded_image_.rotation_ = input_image_->rotation();
732 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
733 ? VideoContentType::SCREENSHARE
734 : VideoContentType::UNSPECIFIED;
735 encoded_image_._encodedHeight =
736 pkt->data.frame.height[layer_id.spatial_layer_id];
737 encoded_image_._encodedWidth =
738 pkt->data.frame.width[layer_id.spatial_layer_id];
739 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
740 int qp = -1;
741 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
742 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700743
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000744 return WEBRTC_VIDEO_CODEC_OK;
745}
746
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200747void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_superframe) {
748 if (encoded_image_._length > 0) {
749 codec_specific_.codecSpecific.VP9.end_of_superframe = end_of_superframe;
750
751 // No data partitioning in VP9, so 1 partition only.
752 int part_idx = 0;
753 RTPFragmentationHeader frag_info;
754 frag_info.VerifyAndAllocateFragmentationHeader(1);
755 frag_info.fragmentationOffset[part_idx] = 0;
756 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
757 frag_info.fragmentationPlType[part_idx] = 0;
758 frag_info.fragmentationTimeDiff[part_idx] = 0;
759
760 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
761 &frag_info);
762 encoded_image_._length = 0;
763 }
764}
765
philipelcfc319b2015-11-10 07:17:23 -0800766vpx_svc_ref_frame_config VP9EncoderImpl::GenerateRefsAndFlags(
767 const SuperFrameRefSettings& settings) {
768 static const vpx_enc_frame_flags_t kAllFlags =
769 VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_LAST |
770 VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF;
771 vpx_svc_ref_frame_config sf_conf = {};
772 if (settings.is_keyframe) {
773 // Used later on to make sure we don't make any invalid references.
774 memset(buffer_updated_at_frame_, -1, sizeof(buffer_updated_at_frame_));
775 for (int layer = settings.start_layer; layer <= settings.stop_layer;
776 ++layer) {
777 num_ref_pics_[layer] = 0;
778 buffer_updated_at_frame_[settings.layer[layer].upd_buf] = frames_encoded_;
779 // When encoding a keyframe only the alt_fb_idx is used
780 // to specify which layer ends up in which buffer.
781 sf_conf.alt_fb_idx[layer] = settings.layer[layer].upd_buf;
782 }
783 } else {
784 for (int layer_idx = settings.start_layer; layer_idx <= settings.stop_layer;
785 ++layer_idx) {
786 vpx_enc_frame_flags_t layer_flags = kAllFlags;
787 num_ref_pics_[layer_idx] = 0;
788 int8_t refs[3] = {settings.layer[layer_idx].ref_buf1,
789 settings.layer[layer_idx].ref_buf2,
790 settings.layer[layer_idx].ref_buf3};
791
792 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
793 if (refs[ref_idx] == -1)
794 continue;
795
796 RTC_DCHECK_GE(refs[ref_idx], 0);
797 RTC_DCHECK_LE(refs[ref_idx], 7);
798 // Easier to remove flags from all flags rather than having to
799 // build the flags from 0.
800 switch (num_ref_pics_[layer_idx]) {
801 case 0: {
802 sf_conf.lst_fb_idx[layer_idx] = refs[ref_idx];
803 layer_flags &= ~VP8_EFLAG_NO_REF_LAST;
804 break;
805 }
806 case 1: {
807 sf_conf.gld_fb_idx[layer_idx] = refs[ref_idx];
808 layer_flags &= ~VP8_EFLAG_NO_REF_GF;
809 break;
810 }
811 case 2: {
812 sf_conf.alt_fb_idx[layer_idx] = refs[ref_idx];
813 layer_flags &= ~VP8_EFLAG_NO_REF_ARF;
814 break;
815 }
816 }
817 // Make sure we don't reference a buffer that hasn't been
818 // used at all or hasn't been used since a keyframe.
819 RTC_DCHECK_NE(buffer_updated_at_frame_[refs[ref_idx]], -1);
820
821 p_diff_[layer_idx][num_ref_pics_[layer_idx]] =
822 frames_encoded_ - buffer_updated_at_frame_[refs[ref_idx]];
823 num_ref_pics_[layer_idx]++;
824 }
825
826 bool upd_buf_same_as_a_ref = false;
827 if (settings.layer[layer_idx].upd_buf != -1) {
828 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
829 if (settings.layer[layer_idx].upd_buf == refs[ref_idx]) {
830 switch (ref_idx) {
831 case 0: {
832 layer_flags &= ~VP8_EFLAG_NO_UPD_LAST;
833 break;
834 }
835 case 1: {
836 layer_flags &= ~VP8_EFLAG_NO_UPD_GF;
837 break;
838 }
839 case 2: {
840 layer_flags &= ~VP8_EFLAG_NO_UPD_ARF;
841 break;
842 }
843 }
844 upd_buf_same_as_a_ref = true;
845 break;
846 }
847 }
848 if (!upd_buf_same_as_a_ref) {
849 // If we have three references and a buffer is specified to be
850 // updated, then that buffer must be the same as one of the
851 // three references.
852 RTC_CHECK_LT(num_ref_pics_[layer_idx], kMaxVp9RefPics);
853
854 sf_conf.alt_fb_idx[layer_idx] = settings.layer[layer_idx].upd_buf;
855 layer_flags ^= VP8_EFLAG_NO_UPD_ARF;
856 }
857
858 int updated_buffer = settings.layer[layer_idx].upd_buf;
859 buffer_updated_at_frame_[updated_buffer] = frames_encoded_;
860 sf_conf.frame_flags[layer_idx] = layer_flags;
861 }
862 }
863 }
864 ++frames_encoded_;
865 return sf_conf;
866}
867
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000868int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000869 return WEBRTC_VIDEO_CODEC_OK;
870}
871
872int VP9EncoderImpl::RegisterEncodeCompleteCallback(
873 EncodedImageCallback* callback) {
874 encoded_complete_callback_ = callback;
875 return WEBRTC_VIDEO_CODEC_OK;
876}
877
Peter Boströmb7d9a972015-12-18 16:01:11 +0100878const char* VP9EncoderImpl::ImplementationName() const {
879 return "libvpx";
880}
881
Peter Boström12996152016-05-14 02:03:18 +0200882bool VP9Decoder::IsSupported() {
883 return true;
884}
885
Magnus Jedvert46a27652017-11-13 14:10:02 +0100886std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
887 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000888}
889
890VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700891 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000892 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700893 decoder_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000894 key_frame_required_(true) {
895 memset(&codec_, 0, sizeof(codec_));
896}
897
898VP9DecoderImpl::~VP9DecoderImpl() {
899 inited_ = true; // in order to do the actual release
900 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200901 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
902 if (num_buffers_in_use > 0) {
903 // The frame buffers are reference counted and frames are exposed after
904 // decoding. There may be valid usage cases where previous frames are still
905 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100906 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
907 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200908 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000909}
910
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000911int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
sprang3958ed82017-08-17 08:12:10 -0700912 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000913 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
914 }
915 int ret_val = Release();
916 if (ret_val < 0) {
917 return ret_val;
918 }
sprang3958ed82017-08-17 08:12:10 -0700919 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000920 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000921 }
philipelcce46fc2015-12-21 03:04:49 -0800922 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000923 // Setting number of threads to a constant value (1)
924 cfg.threads = 1;
925 cfg.h = cfg.w = 0; // set after decode
926 vpx_codec_flags_t flags = 0;
927 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
928 return WEBRTC_VIDEO_CODEC_MEMORY;
929 }
930 if (&codec_ != inst) {
931 // Save VideoCodec instance for later; mainly for duplicating the decoder.
932 codec_ = *inst;
933 }
Henrik Boström9695d852015-05-06 10:42:15 +0200934
935 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
936 return WEBRTC_VIDEO_CODEC_MEMORY;
937 }
938
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000939 inited_ = true;
940 // Always start with a complete key frame.
941 key_frame_required_ = true;
942 return WEBRTC_VIDEO_CODEC_OK;
943}
944
945int VP9DecoderImpl::Decode(const EncodedImage& input_image,
946 bool missing_frames,
947 const RTPFragmentationHeader* fragmentation,
948 const CodecSpecificInfo* codec_specific_info,
949 int64_t /*render_time_ms*/) {
950 if (!inited_) {
951 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
952 }
sprang3958ed82017-08-17 08:12:10 -0700953 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000954 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
955 }
956 // Always start with a complete key frame.
957 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200958 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000959 return WEBRTC_VIDEO_CODEC_ERROR;
960 // We have a key frame - is it complete?
961 if (input_image._completeFrame) {
962 key_frame_required_ = false;
963 } else {
964 return WEBRTC_VIDEO_CODEC_ERROR;
965 }
966 }
sprang3958ed82017-08-17 08:12:10 -0700967 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000968 vpx_image_t* img;
969 uint8_t* buffer = input_image._buffer;
970 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700971 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000972 }
Henrik Boström9695d852015-05-06 10:42:15 +0200973 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
974 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800975 if (vpx_codec_decode(decoder_, buffer,
976 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000977 VPX_DL_REALTIME)) {
978 return WEBRTC_VIDEO_CODEC_ERROR;
979 }
Henrik Boström9695d852015-05-06 10:42:15 +0200980 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
981 // It may be released by libvpx during future vpx_codec_decode or
982 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000983 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -0800984 int qp;
985 vpx_codec_err_t vpx_ret =
986 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
987 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
988 int ret =
989 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000990 if (ret != 0) {
991 return ret;
992 }
993 return WEBRTC_VIDEO_CODEC_OK;
994}
995
asapersson1490f7a2016-09-23 02:09:46 -0700996int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
997 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -0800998 int64_t ntp_time_ms,
999 int qp) {
sprang3958ed82017-08-17 08:12:10 -07001000 if (img == nullptr) {
1001 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001002 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1003 }
Henrik Boström9695d852015-05-06 10:42:15 +02001004
1005 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001006 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001007 // vpx_codec_decode calls or vpx_codec_destroy).
1008 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1009 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001010 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +02001011 // using a WrappedI420Buffer.
1012 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
1013 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -08001014 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1015 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1016 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1017 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001018 // WrappedI420Buffer's mechanism for allowing the release of its frame
1019 // buffer is through a callback function. This is where we should
1020 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -08001021 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +02001022
nisseca6d5d12016-06-17 05:03:04 -07001023 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
1024 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -07001025 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -07001026
Oskar Sundbom6bd39022017-11-16 10:54:49 +01001027 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001028 return WEBRTC_VIDEO_CODEC_OK;
1029}
1030
1031int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1032 DecodedImageCallback* callback) {
1033 decode_complete_callback_ = callback;
1034 return WEBRTC_VIDEO_CODEC_OK;
1035}
1036
1037int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001038 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1039
sprang3958ed82017-08-17 08:12:10 -07001040 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001041 if (inited_) {
1042 // When a codec is destroyed libvpx will release any buffers of
1043 // |frame_buffer_pool_| it is currently using.
1044 if (vpx_codec_destroy(decoder_)) {
1045 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1046 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001047 }
1048 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001049 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001050 }
Henrik Boström9695d852015-05-06 10:42:15 +02001051 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1052 // still referenced externally are deleted once fully released, not returning
1053 // to the pool.
1054 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001055 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001056 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001057}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001058
1059const char* VP9DecoderImpl::ImplementationName() const {
1060 return "libvpx";
1061}
1062
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001063} // namespace webrtc