blob: 89b51975932bff899d49be9de0bc0fc059b93a4f [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),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020077 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -070078 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -080079 num_spatial_layers_(0),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020080 inter_layer_pred_(InterLayerPredMode::kOn),
Erik Språng08127a92016-11-16 16:41:30 +010081 is_flexible_mode_(false),
philipelcfc319b2015-11-10 07:17:23 -080082 frames_encoded_(0),
83 // Use two spatial when screensharing with flexible mode.
84 spatial_layer_(new ScreenshareLayersVP9(2)) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +000085 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -080086 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +000087}
88
89VP9EncoderImpl::~VP9EncoderImpl() {
90 Release();
91}
92
93int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +010094 int ret_val = WEBRTC_VIDEO_CODEC_OK;
95
sprang3958ed82017-08-17 08:12:10 -070096 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -080097 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -070098 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +000099 }
sprang3958ed82017-08-17 08:12:10 -0700100 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100101 if (inited_) {
102 if (vpx_codec_destroy(encoder_)) {
103 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
104 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000105 }
106 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700107 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000108 }
sprang3958ed82017-08-17 08:12:10 -0700109 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000110 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700111 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000112 }
sprang3958ed82017-08-17 08:12:10 -0700113 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000114 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700115 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000116 }
117 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100118 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000119}
120
sprangce4aef12015-11-02 07:23:20 -0800121bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
122 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
123 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100124 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800125}
126
Erik Språng566124a2018-04-23 12:32:22 +0200127bool VP9EncoderImpl::SetSvcRates(
128 const VideoBitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700129 uint8_t i = 0;
130
Sergey Silkin86684962018-03-28 19:32:37 +0200131 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
132 spatial_layer_->ConfigureBitrate(bitrate_allocation.get_sum_kbps(), 0);
133
sprangce4aef12015-11-02 07:23:20 -0800134 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200135 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
136 config_->ss_target_bitrate[sl_idx] =
137 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
138
139 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
140 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
141 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
142 }
sprangce4aef12015-11-02 07:23:20 -0800143 }
144 } else {
145 float rate_ratio[VPX_MAX_LAYERS] = {0};
146 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700147
sprangce4aef12015-11-02 07:23:20 -0800148 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800149 if (svc_params_.scaling_factor_num[i] <= 0 ||
150 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100151 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800152 return false;
153 }
154 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800155 static_cast<float>(svc_params_.scaling_factor_num[i]) /
156 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800157 total += rate_ratio[i];
158 }
159
160 for (i = 0; i < num_spatial_layers_; ++i) {
161 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
162 config_->rc_target_bitrate * rate_ratio[i] / total);
163 if (num_temporal_layers_ == 1) {
164 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
165 } else if (num_temporal_layers_ == 2) {
166 config_->layer_target_bitrate[i * num_temporal_layers_] =
167 config_->ss_target_bitrate[i] * 2 / 3;
168 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
169 config_->ss_target_bitrate[i];
170 } else if (num_temporal_layers_ == 3) {
171 config_->layer_target_bitrate[i * num_temporal_layers_] =
172 config_->ss_target_bitrate[i] / 2;
173 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
174 config_->layer_target_bitrate[i * num_temporal_layers_] +
175 (config_->ss_target_bitrate[i] / 4);
176 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
177 config_->ss_target_bitrate[i];
178 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
180 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800181 return false;
182 }
asaperssona9455ab2015-07-31 06:10:09 -0700183 }
184 }
185
186 // For now, temporal layers only supported when having one spatial layer.
187 if (num_spatial_layers_ == 1) {
188 for (i = 0; i < num_temporal_layers_; ++i) {
189 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
190 }
191 }
192
193 return true;
194}
195
Erik Språng08127a92016-11-16 16:41:30 +0100196int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200197 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100198 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000199 if (!inited_) {
200 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
201 }
202 if (encoder_->err) {
203 return WEBRTC_VIDEO_CODEC_ERROR;
204 }
Erik Språng08127a92016-11-16 16:41:30 +0100205 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000206 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
207 }
208 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100209 if (codec_.maxBitrate > 0 &&
210 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
211 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000212 }
Erik Språng08127a92016-11-16 16:41:30 +0100213
Erik Språng08127a92016-11-16 16:41:30 +0100214 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700215
Sergey Silkin86684962018-03-28 19:32:37 +0200216 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700217 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
218 }
219
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000220 // Update encoder context
221 if (vpx_codec_enc_config_set(encoder_, config_)) {
222 return WEBRTC_VIDEO_CODEC_ERROR;
223 }
224 return WEBRTC_VIDEO_CODEC_OK;
225}
226
227int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
228 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000229 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700230 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000231 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
232 }
233 if (inst->maxFramerate < 1) {
234 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
235 }
236 // Allow zero to represent an unspecified maxBitRate
237 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
238 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
239 }
240 if (inst->width < 1 || inst->height < 1) {
241 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
242 }
243 if (number_of_cores < 1) {
244 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
245 }
hta257dc392016-10-25 09:05:06 -0700246 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700247 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
248 }
ilnik2a8c2f52017-02-15 02:23:28 -0800249 // libvpx probably does not support more than 3 spatial layers.
250 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700251 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
252 }
philipelcfc319b2015-11-10 07:17:23 -0800253
asapersson86956de2016-01-26 01:05:20 -0800254 int ret_val = Release();
255 if (ret_val < 0) {
256 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000257 }
sprang3958ed82017-08-17 08:12:10 -0700258 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000259 encoder_ = new vpx_codec_ctx_t;
260 }
sprang3958ed82017-08-17 08:12:10 -0700261 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000262 config_ = new vpx_codec_enc_cfg_t;
263 }
264 timestamp_ = 0;
265 if (&codec_ != inst) {
266 codec_ = *inst;
267 }
asaperssona9455ab2015-07-31 06:10:09 -0700268
hta257dc392016-10-25 09:05:06 -0700269 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200270 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700271 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700272 if (num_temporal_layers_ == 0)
273 num_temporal_layers_ = 1;
274
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000275 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700276 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800277 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000278 }
nisseeb44b392017-04-28 07:18:05 -0700279 encoded_image_._size =
280 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000281 encoded_image_._buffer = new uint8_t[encoded_image_._size];
282 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700283 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000284 // pointer will be set in encode. Setting align to 1, as it is meaningless
285 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700286 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
287 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000288 // Populate encoder configuration with default values.
289 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
290 return WEBRTC_VIDEO_CODEC_ERROR;
291 }
292 config_->g_w = codec_.width;
293 config_->g_h = codec_.height;
294 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Niels Möller65fb4042018-04-25 14:46:06 +0200295 config_->g_error_resilient =
296 (num_spatial_layers_ > 1 || num_temporal_layers_ > 1) ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000297 // Setting the time base of the codec.
298 config_->g_timebase.num = 1;
299 config_->g_timebase.den = 90000;
300 config_->g_lag_in_frames = 0; // 0- no frame lagging
301 config_->g_threads = 1;
302 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700303 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000304 config_->rc_end_usage = VPX_CBR;
305 config_->g_pass = VPX_RC_ONE_PASS;
306 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000307 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000308 config_->rc_undershoot_pct = 50;
309 config_->rc_overshoot_pct = 50;
310 config_->rc_buf_initial_sz = 500;
311 config_->rc_buf_optimal_sz = 600;
312 config_->rc_buf_sz = 1000;
313 // Set the maximum target size of any key-frame.
314 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700315 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000316 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700317 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100318 // Needs to be set (in svc mode) to get correct periodic key frame interval
319 // (will have no effect in non-svc).
320 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000321 } else {
322 config_->kf_mode = VPX_KF_DISABLED;
323 }
hta257dc392016-10-25 09:05:06 -0700324 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000325 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800326 config_->g_threads =
327 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700328
Marco6e89b252015-07-07 14:40:38 -0700329 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700330
331 // TODO(asapersson): Check configuration of temporal switch up and increase
332 // pattern length.
hta257dc392016-10-25 09:05:06 -0700333 is_flexible_mode_ = inst->VP9().flexibleMode;
philipelcfc319b2015-11-10 07:17:23 -0800334 if (is_flexible_mode_) {
335 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
336 config_->ts_number_layers = num_temporal_layers_;
337 if (codec_.mode == kScreensharing)
338 spatial_layer_->ConfigureBitrate(inst->startBitrate, 0);
339 } else if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700340 gof_.SetGofInfoVP9(kTemporalStructureMode1);
341 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
342 config_->ts_number_layers = 1;
343 config_->ts_rate_decimator[0] = 1;
344 config_->ts_periodicity = 1;
345 config_->ts_layer_id[0] = 0;
346 } else if (num_temporal_layers_ == 2) {
347 gof_.SetGofInfoVP9(kTemporalStructureMode2);
348 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
349 config_->ts_number_layers = 2;
350 config_->ts_rate_decimator[0] = 2;
351 config_->ts_rate_decimator[1] = 1;
352 config_->ts_periodicity = 2;
353 config_->ts_layer_id[0] = 0;
354 config_->ts_layer_id[1] = 1;
355 } else if (num_temporal_layers_ == 3) {
356 gof_.SetGofInfoVP9(kTemporalStructureMode3);
357 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
358 config_->ts_number_layers = 3;
359 config_->ts_rate_decimator[0] = 4;
360 config_->ts_rate_decimator[1] = 2;
361 config_->ts_rate_decimator[2] = 1;
362 config_->ts_periodicity = 4;
363 config_->ts_layer_id[0] = 0;
364 config_->ts_layer_id[1] = 2;
365 config_->ts_layer_id[2] = 1;
366 config_->ts_layer_id[3] = 2;
367 } else {
368 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
369 }
370
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200371 inter_layer_pred_ = inst->VP9().interLayerPred;
372
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000373 return InitAndSetControlSettings(inst);
374}
375
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000376int VP9EncoderImpl::NumberOfThreads(int width,
377 int height,
378 int number_of_cores) {
379 // Keep the number of encoder threads equal to the possible number of column
380 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
381 if (width * height >= 1280 * 720 && number_of_cores > 4) {
382 return 4;
jianj23173a32017-07-12 16:11:09 -0700383 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000384 return 2;
385 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800386 // Use 2 threads for low res on ARM.
387#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
388 defined(WEBRTC_ANDROID)
389 if (width * height >= 320 * 180 && number_of_cores > 2) {
390 return 2;
391 }
392#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000393 // 1 thread less than VGA.
394 return 1;
395 }
396}
397
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000398int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100399 // Set QP-min/max per spatial and temporal layer.
400 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
401 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800402 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
403 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100404 }
asaperssona9455ab2015-07-31 06:10:09 -0700405 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800406 if (ExplicitlyConfiguredSpatialLayers()) {
407 for (int i = 0; i < num_spatial_layers_; ++i) {
408 const auto& layer = codec_.spatialLayers[i];
Sergey Silkin13e74342018-03-02 12:28:00 +0100409 const int scale_factor = codec_.width / layer.width;
410 RTC_DCHECK_GT(scale_factor, 0);
411
412 // Ensure scaler factor is integer.
413 if (scale_factor * layer.width != codec_.width) {
414 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
415 }
416
417 // Ensure scale factor is the same in both dimensions.
418 if (scale_factor * layer.height != codec_.height) {
419 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
420 }
421
422 // Ensure scale factor is power of two.
423 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
424 if (!is_pow_of_two) {
425 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
426 }
427
428 svc_params_.scaling_factor_num[i] = 1;
429 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800430 }
431 } else {
432 int scaling_factor_num = 256;
433 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800434 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800435 svc_params_.scaling_factor_num[i] = scaling_factor_num;
436 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800437 if (codec_.mode != kScreensharing)
438 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800439 }
asaperssona9455ab2015-07-31 06:10:09 -0700440 }
441
Sergey Silkin86684962018-03-28 19:32:37 +0200442 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200443 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200444 inst->startBitrate * 1000, inst->maxFramerate);
445 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700446 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
447 }
448
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000449 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
450 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
451 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000452 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
453 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
454 rc_max_intra_target_);
455 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700456 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700457
jianj822e5932017-07-12 16:09:58 -0700458 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700459 vpx_codec_control(
460 encoder_, VP9E_SET_SVC,
461 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200462
asaperssona9455ab2015-07-31 06:10:09 -0700463 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
464 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800465 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700466 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200467
468 if (num_spatial_layers_ > 1) {
469 switch (inter_layer_pred_) {
470 case InterLayerPredMode::kOn:
471 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
472 break;
473 case InterLayerPredMode::kOff:
474 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
475 break;
476 case InterLayerPredMode::kOnKeyPic:
477 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
478 break;
479 default:
480 RTC_NOTREACHED();
481 }
482 }
483
asaperssona9455ab2015-07-31 06:10:09 -0700484 // Register callback for getting each spatial layer.
485 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800486 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
487 reinterpret_cast<void*>(this)};
488 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
489 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700490
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000491 // Control function to set the number of column tiles in encoding a frame, in
492 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
493 // The number tile columns will be capped by the encoder based on image size
494 // (minimum width of tile column is 256 pixels, maximum is 4096).
495 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700496
497 // Turn on row-based multithreading.
498 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700499
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700500#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
501 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700502 // Do not enable the denoiser on ARM since optimization is pending.
503 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000504 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700505 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000506#endif
jianj6bf57e32017-06-05 13:43:49 -0700507
ivica242d6382015-09-04 06:13:23 -0700508 if (codec_.mode == kScreensharing) {
509 // Adjust internal parameters to screen content.
510 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700511 }
Marco2520e722015-09-16 14:05:00 -0700512 // Enable encoder skip of static/low content blocks.
513 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000514 inited_ = true;
515 return WEBRTC_VIDEO_CODEC_OK;
516}
517
518uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
519 // Set max to the optimal buffer level (normalized by target BR),
520 // and scaled by a scale_par.
521 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
522 // This value is presented in percentage of perFrameBw:
523 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
524 // The target in % is as follows:
525 float scale_par = 0.5;
526 uint32_t target_pct =
527 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
528 // Don't go below 3 times the per frame bandwidth.
529 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800530 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000531}
532
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700533int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000534 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700535 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000536 if (!inited_) {
537 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
538 }
sprang3958ed82017-08-17 08:12:10 -0700539 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000540 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
541 }
Peter Boström49e196a2015-10-23 15:58:18 +0200542 FrameType frame_type = kVideoFrameDelta;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000543 // We only support one stream at the moment.
544 if (frame_types && frame_types->size() > 0) {
545 frame_type = (*frame_types)[0];
546 }
kwiberg352444f2016-11-28 15:58:53 -0800547 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
548 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700549
550 // Set input image for use in the callback.
551 // This was necessary since you need some information from input_image.
552 // You can save only the necessary information (such as timestamp) instead of
553 // doing this.
554 input_image_ = &input_image;
555
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000556 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
557 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000558 // Image in vpx_image_t format.
559 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000560 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
561 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
562 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
563 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
564 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
565 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000566
philipelcfc319b2015-11-10 07:17:23 -0800567 vpx_enc_frame_flags_t flags = 0;
Peter Boström49e196a2015-10-23 15:58:18 +0200568 bool send_keyframe = (frame_type == kVideoFrameKey);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000569 if (send_keyframe) {
570 // Key frame request from caller.
571 flags = VPX_EFLAG_FORCE_KF;
572 }
philipelcfc319b2015-11-10 07:17:23 -0800573
574 if (is_flexible_mode_) {
575 SuperFrameRefSettings settings;
576
577 // These structs are copied when calling vpx_codec_control,
578 // therefore it is ok for them to go out of scope.
579 vpx_svc_ref_frame_config enc_layer_conf;
580 vpx_svc_layer_id layer_id;
581
582 if (codec_.mode == kRealtimeVideo) {
583 // Real time video not yet implemented in flexible mode.
584 RTC_NOTREACHED();
585 } else {
586 settings = spatial_layer_->GetSuperFrameSettings(input_image.timestamp(),
587 send_keyframe);
588 }
589 enc_layer_conf = GenerateRefsAndFlags(settings);
590 layer_id.temporal_layer_id = 0;
591 layer_id.spatial_layer_id = settings.start_layer;
592 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
593 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
594 }
595
sprang3958ed82017-08-17 08:12:10 -0700596 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000597 uint32_t duration = 90000 / codec_.maxFramerate;
598 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
599 VPX_DL_REALTIME)) {
600 return WEBRTC_VIDEO_CODEC_ERROR;
601 }
602 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700603
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200604 const bool end_of_picture = true;
605 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200606
asaperssona9455ab2015-07-31 06:10:09 -0700607 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000608}
609
610void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800611 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200612 uint32_t timestamp,
613 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700614 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000615 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700616 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800617 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200618
619 vp9_info->first_frame_in_picture = first_frame_in_picture;
Åsa Perssonff24c042015-12-04 10:58:08 +0100620 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700621 vp9_info->inter_pic_predicted =
622 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700623 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
624 vp9_info->ss_data_available =
625 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
626 ? true
627 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700628
629 vpx_svc_layer_id_t layer_id = {0};
630 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
631
sprang3958ed82017-08-17 08:12:10 -0700632 RTC_CHECK_GT(num_temporal_layers_, 0);
633 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700634 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700635 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700636 vp9_info->temporal_idx = kNoTemporalIdx;
637 } else {
638 vp9_info->temporal_idx = layer_id.temporal_layer_id;
639 }
640 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700641 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700642 vp9_info->spatial_idx = kNoSpatialIdx;
643 } else {
644 vp9_info->spatial_idx = layer_id.spatial_layer_id;
645 }
646 if (layer_id.spatial_layer_id != 0) {
647 vp9_info->ss_data_available = false;
648 }
649
asaperssona9455ab2015-07-31 06:10:09 -0700650 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800651 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700652
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200653 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
654 pics_since_key_ = 0;
655 } else if (first_frame_in_picture) {
656 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700657 }
658
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200659 const bool is_key_pic = (pics_since_key_ == 0);
660 const bool is_inter_layer_pred_allowed =
661 (inter_layer_pred_ == InterLayerPredMode::kOn ||
662 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
663
664 // Always set inter_layer_predicted to true on high layer frame if inter-layer
665 // prediction (ILP) is allowed even if encoder didn't actually use it.
666 // Setting inter_layer_predicted to false would allow receiver to decode high
667 // layer frame without decoding low layer frame. If that would happen (e.g.
668 // if low layer frame is lost) then receiver won't be able to decode next high
669 // layer frame which uses ILP.
670 vp9_info->inter_layer_predicted =
671 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
672
673 const bool is_last_layer =
674 (layer_id.spatial_layer_id + 1 == num_spatial_layers_);
675 vp9_info->non_ref_for_inter_layer_pred =
676 is_last_layer ? true : !is_inter_layer_pred_allowed;
asapersson00ac85e2015-11-11 05:30:48 -0800677
ivica7f6a6fc2015-09-08 02:40:29 -0700678 // Always populate this, so that the packetizer can properly set the marker
679 // bit.
680 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800681
682 vp9_info->num_ref_pics = 0;
683 if (vp9_info->flexible_mode) {
684 vp9_info->gof_idx = kNoGofIdx;
685 vp9_info->num_ref_pics = num_ref_pics_[layer_id.spatial_layer_id];
686 for (int i = 0; i < num_ref_pics_[layer_id.spatial_layer_id]; ++i) {
687 vp9_info->p_diff[i] = p_diff_[layer_id.spatial_layer_id][i];
688 }
689 } else {
690 vp9_info->gof_idx =
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200691 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
asapersson00ac85e2015-11-11 05:30:48 -0800692 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800693 }
philipelcfc319b2015-11-10 07:17:23 -0800694
asaperssona9455ab2015-07-31 06:10:09 -0700695 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700696 vp9_info->spatial_layer_resolution_present = true;
697 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
698 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800699 svc_params_.scaling_factor_num[i] /
700 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700701 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800702 svc_params_.scaling_factor_num[i] /
703 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700704 }
705 if (!vp9_info->flexible_mode) {
706 vp9_info->gof.CopyGofInfoVP9(gof_);
707 }
708 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000709}
710
asaperssona9455ab2015-07-31 06:10:09 -0700711int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800712 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700713
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200714 if (pkt->data.frame.sz == 0) {
715 // Ignore dropped frame.
716 return WEBRTC_VIDEO_CODEC_OK;
717 }
718
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200719 vpx_svc_layer_id_t layer_id = {0};
720 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
721
722 const bool first_frame_in_picture = encoded_image_._length == 0;
723 // Ensure we don't buffer layers of previous picture (superframe).
724 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
725
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200726 const bool end_of_picture = false;
727 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200728
asaperssond9f641e2016-01-21 01:11:35 -0800729 if (pkt->data.frame.sz > encoded_image_._size) {
730 delete[] encoded_image_._buffer;
731 encoded_image_._size = pkt->data.frame.sz;
732 encoded_image_._buffer = new uint8_t[encoded_image_._size];
733 }
asapersson86956de2016-01-26 01:05:20 -0800734 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
735 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800736
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200737 if (is_flexible_mode_ && codec_.mode == kScreensharing) {
philipelcfc319b2015-11-10 07:17:23 -0800738 spatial_layer_->LayerFrameEncoded(
739 static_cast<unsigned int>(encoded_image_._length),
740 layer_id.spatial_layer_id);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200741 }
philipelcfc319b2015-11-10 07:17:23 -0800742
asaperssona9455ab2015-07-31 06:10:09 -0700743 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800744 encoded_image_._frameType = kVideoFrameDelta;
asaperssona9455ab2015-07-31 06:10:09 -0700745 if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
Peter Boström49e196a2015-10-23 15:58:18 +0200746 encoded_image_._frameType = kVideoFrameKey;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000747 }
asapersson86956de2016-01-26 01:05:20 -0800748 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
749
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200750 memset(&codec_specific_, 0, sizeof(codec_specific_));
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200751 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
752 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -0700753
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200754 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
755 encoded_image_._timeStamp = input_image_->timestamp();
756 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
757 encoded_image_.rotation_ = input_image_->rotation();
758 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
759 ? VideoContentType::SCREENSHARE
760 : VideoContentType::UNSPECIFIED;
761 encoded_image_._encodedHeight =
762 pkt->data.frame.height[layer_id.spatial_layer_id];
763 encoded_image_._encodedWidth =
764 pkt->data.frame.width[layer_id.spatial_layer_id];
765 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
766 int qp = -1;
767 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
768 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700769
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000770 return WEBRTC_VIDEO_CODEC_OK;
771}
772
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200773void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200774 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200775 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200776
777 // No data partitioning in VP9, so 1 partition only.
778 int part_idx = 0;
779 RTPFragmentationHeader frag_info;
780 frag_info.VerifyAndAllocateFragmentationHeader(1);
781 frag_info.fragmentationOffset[part_idx] = 0;
782 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
783 frag_info.fragmentationPlType[part_idx] = 0;
784 frag_info.fragmentationTimeDiff[part_idx] = 0;
785
786 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
787 &frag_info);
788 encoded_image_._length = 0;
789 }
790}
791
philipelcfc319b2015-11-10 07:17:23 -0800792vpx_svc_ref_frame_config VP9EncoderImpl::GenerateRefsAndFlags(
793 const SuperFrameRefSettings& settings) {
794 static const vpx_enc_frame_flags_t kAllFlags =
795 VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_LAST |
796 VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF;
797 vpx_svc_ref_frame_config sf_conf = {};
798 if (settings.is_keyframe) {
799 // Used later on to make sure we don't make any invalid references.
800 memset(buffer_updated_at_frame_, -1, sizeof(buffer_updated_at_frame_));
801 for (int layer = settings.start_layer; layer <= settings.stop_layer;
802 ++layer) {
803 num_ref_pics_[layer] = 0;
804 buffer_updated_at_frame_[settings.layer[layer].upd_buf] = frames_encoded_;
805 // When encoding a keyframe only the alt_fb_idx is used
806 // to specify which layer ends up in which buffer.
807 sf_conf.alt_fb_idx[layer] = settings.layer[layer].upd_buf;
808 }
809 } else {
810 for (int layer_idx = settings.start_layer; layer_idx <= settings.stop_layer;
811 ++layer_idx) {
812 vpx_enc_frame_flags_t layer_flags = kAllFlags;
813 num_ref_pics_[layer_idx] = 0;
814 int8_t refs[3] = {settings.layer[layer_idx].ref_buf1,
815 settings.layer[layer_idx].ref_buf2,
816 settings.layer[layer_idx].ref_buf3};
817
818 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
819 if (refs[ref_idx] == -1)
820 continue;
821
822 RTC_DCHECK_GE(refs[ref_idx], 0);
823 RTC_DCHECK_LE(refs[ref_idx], 7);
824 // Easier to remove flags from all flags rather than having to
825 // build the flags from 0.
826 switch (num_ref_pics_[layer_idx]) {
827 case 0: {
828 sf_conf.lst_fb_idx[layer_idx] = refs[ref_idx];
829 layer_flags &= ~VP8_EFLAG_NO_REF_LAST;
830 break;
831 }
832 case 1: {
833 sf_conf.gld_fb_idx[layer_idx] = refs[ref_idx];
834 layer_flags &= ~VP8_EFLAG_NO_REF_GF;
835 break;
836 }
837 case 2: {
838 sf_conf.alt_fb_idx[layer_idx] = refs[ref_idx];
839 layer_flags &= ~VP8_EFLAG_NO_REF_ARF;
840 break;
841 }
842 }
843 // Make sure we don't reference a buffer that hasn't been
844 // used at all or hasn't been used since a keyframe.
845 RTC_DCHECK_NE(buffer_updated_at_frame_[refs[ref_idx]], -1);
846
847 p_diff_[layer_idx][num_ref_pics_[layer_idx]] =
848 frames_encoded_ - buffer_updated_at_frame_[refs[ref_idx]];
849 num_ref_pics_[layer_idx]++;
850 }
851
852 bool upd_buf_same_as_a_ref = false;
853 if (settings.layer[layer_idx].upd_buf != -1) {
854 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
855 if (settings.layer[layer_idx].upd_buf == refs[ref_idx]) {
856 switch (ref_idx) {
857 case 0: {
858 layer_flags &= ~VP8_EFLAG_NO_UPD_LAST;
859 break;
860 }
861 case 1: {
862 layer_flags &= ~VP8_EFLAG_NO_UPD_GF;
863 break;
864 }
865 case 2: {
866 layer_flags &= ~VP8_EFLAG_NO_UPD_ARF;
867 break;
868 }
869 }
870 upd_buf_same_as_a_ref = true;
871 break;
872 }
873 }
874 if (!upd_buf_same_as_a_ref) {
875 // If we have three references and a buffer is specified to be
876 // updated, then that buffer must be the same as one of the
877 // three references.
878 RTC_CHECK_LT(num_ref_pics_[layer_idx], kMaxVp9RefPics);
879
880 sf_conf.alt_fb_idx[layer_idx] = settings.layer[layer_idx].upd_buf;
881 layer_flags ^= VP8_EFLAG_NO_UPD_ARF;
882 }
883
884 int updated_buffer = settings.layer[layer_idx].upd_buf;
885 buffer_updated_at_frame_[updated_buffer] = frames_encoded_;
886 sf_conf.frame_flags[layer_idx] = layer_flags;
887 }
888 }
889 }
890 ++frames_encoded_;
891 return sf_conf;
892}
893
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000894int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000895 return WEBRTC_VIDEO_CODEC_OK;
896}
897
898int VP9EncoderImpl::RegisterEncodeCompleteCallback(
899 EncodedImageCallback* callback) {
900 encoded_complete_callback_ = callback;
901 return WEBRTC_VIDEO_CODEC_OK;
902}
903
Peter Boströmb7d9a972015-12-18 16:01:11 +0100904const char* VP9EncoderImpl::ImplementationName() const {
905 return "libvpx";
906}
907
Peter Boström12996152016-05-14 02:03:18 +0200908bool VP9Decoder::IsSupported() {
909 return true;
910}
911
Magnus Jedvert46a27652017-11-13 14:10:02 +0100912std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
913 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000914}
915
916VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700917 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000918 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700919 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +0200920 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000921
922VP9DecoderImpl::~VP9DecoderImpl() {
923 inited_ = true; // in order to do the actual release
924 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200925 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
926 if (num_buffers_in_use > 0) {
927 // The frame buffers are reference counted and frames are exposed after
928 // decoding. There may be valid usage cases where previous frames are still
929 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100930 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
931 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200932 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000933}
934
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000935int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000936 int ret_val = Release();
937 if (ret_val < 0) {
938 return ret_val;
939 }
sprang3958ed82017-08-17 08:12:10 -0700940 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000941 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000942 }
philipelcce46fc2015-12-21 03:04:49 -0800943 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000944 // Setting number of threads to a constant value (1)
945 cfg.threads = 1;
946 cfg.h = cfg.w = 0; // set after decode
947 vpx_codec_flags_t flags = 0;
948 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
949 return WEBRTC_VIDEO_CODEC_MEMORY;
950 }
Henrik Boström9695d852015-05-06 10:42:15 +0200951
952 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
953 return WEBRTC_VIDEO_CODEC_MEMORY;
954 }
955
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000956 inited_ = true;
957 // Always start with a complete key frame.
958 key_frame_required_ = true;
959 return WEBRTC_VIDEO_CODEC_OK;
960}
961
962int VP9DecoderImpl::Decode(const EncodedImage& input_image,
963 bool missing_frames,
964 const RTPFragmentationHeader* fragmentation,
965 const CodecSpecificInfo* codec_specific_info,
966 int64_t /*render_time_ms*/) {
967 if (!inited_) {
968 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
969 }
sprang3958ed82017-08-17 08:12:10 -0700970 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000971 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
972 }
973 // Always start with a complete key frame.
974 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200975 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000976 return WEBRTC_VIDEO_CODEC_ERROR;
977 // We have a key frame - is it complete?
978 if (input_image._completeFrame) {
979 key_frame_required_ = false;
980 } else {
981 return WEBRTC_VIDEO_CODEC_ERROR;
982 }
983 }
sprang3958ed82017-08-17 08:12:10 -0700984 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000985 vpx_image_t* img;
986 uint8_t* buffer = input_image._buffer;
987 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700988 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000989 }
Henrik Boström9695d852015-05-06 10:42:15 +0200990 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
991 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800992 if (vpx_codec_decode(decoder_, buffer,
993 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000994 VPX_DL_REALTIME)) {
995 return WEBRTC_VIDEO_CODEC_ERROR;
996 }
Henrik Boström9695d852015-05-06 10:42:15 +0200997 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
998 // It may be released by libvpx during future vpx_codec_decode or
999 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001000 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001001 int qp;
1002 vpx_codec_err_t vpx_ret =
1003 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1004 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
1005 int ret =
1006 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001007 if (ret != 0) {
1008 return ret;
1009 }
1010 return WEBRTC_VIDEO_CODEC_OK;
1011}
1012
asapersson1490f7a2016-09-23 02:09:46 -07001013int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
1014 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -08001015 int64_t ntp_time_ms,
1016 int qp) {
sprang3958ed82017-08-17 08:12:10 -07001017 if (img == nullptr) {
1018 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001019 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1020 }
Henrik Boström9695d852015-05-06 10:42:15 +02001021
1022 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001023 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001024 // vpx_codec_decode calls or vpx_codec_destroy).
1025 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1026 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001027 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +02001028 // using a WrappedI420Buffer.
1029 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
1030 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -08001031 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1032 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1033 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1034 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001035 // WrappedI420Buffer's mechanism for allowing the release of its frame
1036 // buffer is through a callback function. This is where we should
1037 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -08001038 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +02001039
nisseca6d5d12016-06-17 05:03:04 -07001040 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
1041 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -07001042 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -07001043
Oskar Sundbom6bd39022017-11-16 10:54:49 +01001044 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001045 return WEBRTC_VIDEO_CODEC_OK;
1046}
1047
1048int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1049 DecodedImageCallback* callback) {
1050 decode_complete_callback_ = callback;
1051 return WEBRTC_VIDEO_CODEC_OK;
1052}
1053
1054int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001055 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1056
sprang3958ed82017-08-17 08:12:10 -07001057 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001058 if (inited_) {
1059 // When a codec is destroyed libvpx will release any buffers of
1060 // |frame_buffer_pool_| it is currently using.
1061 if (vpx_codec_destroy(decoder_)) {
1062 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1063 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001064 }
1065 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001066 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001067 }
Henrik Boström9695d852015-05-06 10:42:15 +02001068 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1069 // still referenced externally are deleted once fully released, not returning
1070 // to the pool.
1071 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001072 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001073 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001074}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001075
1076const char* VP9DecoderImpl::ImplementationName() const {
1077 return "libvpx";
1078}
1079
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001080} // namespace webrtc