blob: 22993eb66aac1d1b74564dcb0348f4be92820d4f [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"
27#include "rtc_base/checks.h"
28#include "rtc_base/keep_ref_until_done.h"
29#include "rtc_base/logging.h"
Magnus Jedvert46a27652017-11-13 14:10:02 +010030#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/random.h"
32#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));
brandtr080830c2017-05-03 03:25:53 -070086
87 Random random(rtc::TimeMicros());
88 picture_id_ = random.Rand<uint16_t>() & 0x7FFF;
89 tl0_pic_idx_ = random.Rand<uint8_t>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +000090}
91
92VP9EncoderImpl::~VP9EncoderImpl() {
93 Release();
94}
95
96int VP9EncoderImpl::Release() {
sprang3958ed82017-08-17 08:12:10 -070097 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -080098 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -070099 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000100 }
sprang3958ed82017-08-17 08:12:10 -0700101 if (encoder_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000102 if (vpx_codec_destroy(encoder_)) {
103 return WEBRTC_VIDEO_CODEC_MEMORY;
104 }
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;
117 return WEBRTC_VIDEO_CODEC_OK;
118}
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.
123 return num_spatial_layers_ > 1 &&
124 codec_.spatialLayers[0].target_bitrate_bps > 0;
125}
126
asaperssona9455ab2015-07-31 06:10:09 -0700127bool VP9EncoderImpl::SetSvcRates() {
asaperssona9455ab2015-07-31 06:10:09 -0700128 uint8_t i = 0;
129
sprangce4aef12015-11-02 07:23:20 -0800130 if (ExplicitlyConfiguredSpatialLayers()) {
131 if (num_temporal_layers_ > 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100132 RTC_LOG(LS_ERROR) << "Multiple temporal layers when manually specifying "
133 "spatial layers not implemented yet!";
asaperssona9455ab2015-07-31 06:10:09 -0700134 return false;
135 }
sprangce4aef12015-11-02 07:23:20 -0800136 int total_bitrate_bps = 0;
137 for (i = 0; i < num_spatial_layers_; ++i)
138 total_bitrate_bps += codec_.spatialLayers[i].target_bitrate_bps;
139 // If total bitrate differs now from what has been specified at the
140 // beginning, update the bitrates in the same ratio as before.
141 for (i = 0; i < num_spatial_layers_; ++i) {
142 config_->ss_target_bitrate[i] = config_->layer_target_bitrate[i] =
143 static_cast<int>(static_cast<int64_t>(config_->rc_target_bitrate) *
144 codec_.spatialLayers[i].target_bitrate_bps /
145 total_bitrate_bps);
146 }
147 } else {
148 float rate_ratio[VPX_MAX_LAYERS] = {0};
149 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700150
sprangce4aef12015-11-02 07:23:20 -0800151 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800152 if (svc_params_.scaling_factor_num[i] <= 0 ||
153 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100154 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800155 return false;
156 }
157 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800158 static_cast<float>(svc_params_.scaling_factor_num[i]) /
159 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800160 total += rate_ratio[i];
161 }
162
163 for (i = 0; i < num_spatial_layers_; ++i) {
164 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
165 config_->rc_target_bitrate * rate_ratio[i] / total);
166 if (num_temporal_layers_ == 1) {
167 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
168 } else if (num_temporal_layers_ == 2) {
169 config_->layer_target_bitrate[i * num_temporal_layers_] =
170 config_->ss_target_bitrate[i] * 2 / 3;
171 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
172 config_->ss_target_bitrate[i];
173 } else if (num_temporal_layers_ == 3) {
174 config_->layer_target_bitrate[i * num_temporal_layers_] =
175 config_->ss_target_bitrate[i] / 2;
176 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
177 config_->layer_target_bitrate[i * num_temporal_layers_] +
178 (config_->ss_target_bitrate[i] / 4);
179 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
180 config_->ss_target_bitrate[i];
181 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100182 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
183 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800184 return false;
185 }
asaperssona9455ab2015-07-31 06:10:09 -0700186 }
187 }
188
189 // For now, temporal layers only supported when having one spatial layer.
190 if (num_spatial_layers_ == 1) {
191 for (i = 0; i < num_temporal_layers_; ++i) {
192 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
193 }
194 }
195
196 return true;
197}
198
Erik Språng08127a92016-11-16 16:41:30 +0100199int VP9EncoderImpl::SetRateAllocation(
200 const BitrateAllocation& bitrate_allocation,
201 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000202 if (!inited_) {
203 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
204 }
205 if (encoder_->err) {
206 return WEBRTC_VIDEO_CODEC_ERROR;
207 }
Erik Språng08127a92016-11-16 16:41:30 +0100208 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000209 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
210 }
211 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100212 if (codec_.maxBitrate > 0 &&
213 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
214 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000215 }
Erik Språng08127a92016-11-16 16:41:30 +0100216
217 // TODO(sprang): Actually use BitrateAllocation layer info.
218 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
219 codec_.maxFramerate = frame_rate;
220 spatial_layer_->ConfigureBitrate(bitrate_allocation.get_sum_kbps(), 0);
asaperssona9455ab2015-07-31 06:10:09 -0700221
222 if (!SetSvcRates()) {
223 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
224 }
225
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000226 // Update encoder context
227 if (vpx_codec_enc_config_set(encoder_, config_)) {
228 return WEBRTC_VIDEO_CODEC_ERROR;
229 }
230 return WEBRTC_VIDEO_CODEC_OK;
231}
232
233int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
234 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000235 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700236 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000237 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
238 }
239 if (inst->maxFramerate < 1) {
240 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
241 }
242 // Allow zero to represent an unspecified maxBitRate
243 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
244 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
245 }
246 if (inst->width < 1 || inst->height < 1) {
247 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
248 }
249 if (number_of_cores < 1) {
250 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
251 }
hta257dc392016-10-25 09:05:06 -0700252 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700253 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
254 }
ilnik2a8c2f52017-02-15 02:23:28 -0800255 // libvpx probably does not support more than 3 spatial layers.
256 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700257 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
258 }
philipelcfc319b2015-11-10 07:17:23 -0800259
asapersson86956de2016-01-26 01:05:20 -0800260 int ret_val = Release();
261 if (ret_val < 0) {
262 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000263 }
sprang3958ed82017-08-17 08:12:10 -0700264 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000265 encoder_ = new vpx_codec_ctx_t;
266 }
sprang3958ed82017-08-17 08:12:10 -0700267 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000268 config_ = new vpx_codec_enc_cfg_t;
269 }
270 timestamp_ = 0;
271 if (&codec_ != inst) {
272 codec_ = *inst;
273 }
asaperssona9455ab2015-07-31 06:10:09 -0700274
hta257dc392016-10-25 09:05:06 -0700275 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
276 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700277 if (num_temporal_layers_ == 0)
278 num_temporal_layers_ = 1;
279
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000280 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700281 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800282 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000283 }
nisseeb44b392017-04-28 07:18:05 -0700284 encoded_image_._size =
285 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000286 encoded_image_._buffer = new uint8_t[encoded_image_._size];
287 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700288 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000289 // pointer will be set in encode. Setting align to 1, as it is meaningless
290 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700291 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
292 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000293 // Populate encoder configuration with default values.
294 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
295 return WEBRTC_VIDEO_CODEC_ERROR;
296 }
297 config_->g_w = codec_.width;
298 config_->g_h = codec_.height;
299 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
asapersson15dcb382017-06-08 02:55:08 -0700300 config_->g_error_resilient = inst->VP9().resilienceOn ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000301 // Setting the time base of the codec.
302 config_->g_timebase.num = 1;
303 config_->g_timebase.den = 90000;
304 config_->g_lag_in_frames = 0; // 0- no frame lagging
305 config_->g_threads = 1;
306 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700307 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000308 config_->rc_end_usage = VPX_CBR;
309 config_->g_pass = VPX_RC_ONE_PASS;
310 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000311 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000312 config_->rc_undershoot_pct = 50;
313 config_->rc_overshoot_pct = 50;
314 config_->rc_buf_initial_sz = 500;
315 config_->rc_buf_optimal_sz = 600;
316 config_->rc_buf_sz = 1000;
317 // Set the maximum target size of any key-frame.
318 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700319 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000320 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700321 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100322 // Needs to be set (in svc mode) to get correct periodic key frame interval
323 // (will have no effect in non-svc).
324 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000325 } else {
326 config_->kf_mode = VPX_KF_DISABLED;
327 }
hta257dc392016-10-25 09:05:06 -0700328 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000329 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800330 config_->g_threads =
331 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700332
Marco6e89b252015-07-07 14:40:38 -0700333 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700334
335 // TODO(asapersson): Check configuration of temporal switch up and increase
336 // pattern length.
hta257dc392016-10-25 09:05:06 -0700337 is_flexible_mode_ = inst->VP9().flexibleMode;
philipelcfc319b2015-11-10 07:17:23 -0800338 if (is_flexible_mode_) {
339 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
340 config_->ts_number_layers = num_temporal_layers_;
341 if (codec_.mode == kScreensharing)
342 spatial_layer_->ConfigureBitrate(inst->startBitrate, 0);
343 } else if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700344 gof_.SetGofInfoVP9(kTemporalStructureMode1);
345 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
346 config_->ts_number_layers = 1;
347 config_->ts_rate_decimator[0] = 1;
348 config_->ts_periodicity = 1;
349 config_->ts_layer_id[0] = 0;
350 } else if (num_temporal_layers_ == 2) {
351 gof_.SetGofInfoVP9(kTemporalStructureMode2);
352 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
353 config_->ts_number_layers = 2;
354 config_->ts_rate_decimator[0] = 2;
355 config_->ts_rate_decimator[1] = 1;
356 config_->ts_periodicity = 2;
357 config_->ts_layer_id[0] = 0;
358 config_->ts_layer_id[1] = 1;
359 } else if (num_temporal_layers_ == 3) {
360 gof_.SetGofInfoVP9(kTemporalStructureMode3);
361 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
362 config_->ts_number_layers = 3;
363 config_->ts_rate_decimator[0] = 4;
364 config_->ts_rate_decimator[1] = 2;
365 config_->ts_rate_decimator[2] = 1;
366 config_->ts_periodicity = 4;
367 config_->ts_layer_id[0] = 0;
368 config_->ts_layer_id[1] = 2;
369 config_->ts_layer_id[2] = 1;
370 config_->ts_layer_id[3] = 2;
371 } else {
372 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
373 }
374
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000375 return InitAndSetControlSettings(inst);
376}
377
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000378int VP9EncoderImpl::NumberOfThreads(int width,
379 int height,
380 int number_of_cores) {
381 // Keep the number of encoder threads equal to the possible number of column
382 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
383 if (width * height >= 1280 * 720 && number_of_cores > 4) {
384 return 4;
jianj23173a32017-07-12 16:11:09 -0700385 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000386 return 2;
387 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800388 // Use 2 threads for low res on ARM.
389#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
390 defined(WEBRTC_ANDROID)
391 if (width * height >= 320 * 180 && number_of_cores > 2) {
392 return 2;
393 }
394#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000395 // 1 thread less than VGA.
396 return 1;
397 }
398}
399
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000400int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100401 // Set QP-min/max per spatial and temporal layer.
402 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
403 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800404 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
405 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100406 }
asaperssona9455ab2015-07-31 06:10:09 -0700407 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800408 if (ExplicitlyConfiguredSpatialLayers()) {
409 for (int i = 0; i < num_spatial_layers_; ++i) {
410 const auto& layer = codec_.spatialLayers[i];
johannkoenig8225c402017-01-26 13:23:44 -0800411 svc_params_.scaling_factor_num[i] = layer.scaling_factor_num;
412 svc_params_.scaling_factor_den[i] = layer.scaling_factor_den;
sprangce4aef12015-11-02 07:23:20 -0800413 }
414 } else {
415 int scaling_factor_num = 256;
416 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800417 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800418 svc_params_.scaling_factor_num[i] = scaling_factor_num;
419 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800420 if (codec_.mode != kScreensharing)
421 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800422 }
asaperssona9455ab2015-07-31 06:10:09 -0700423 }
424
425 if (!SetSvcRates()) {
426 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
427 }
428
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000429 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
430 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
431 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000432 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
433 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
434 rc_max_intra_target_);
435 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700436 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700437
jianj822e5932017-07-12 16:09:58 -0700438 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700439 vpx_codec_control(
440 encoder_, VP9E_SET_SVC,
441 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
442 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
443 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800444 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700445 }
446 // Register callback for getting each spatial layer.
447 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800448 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
449 reinterpret_cast<void*>(this)};
450 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
451 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700452
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000453 // Control function to set the number of column tiles in encoding a frame, in
454 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
455 // The number tile columns will be capped by the encoder based on image size
456 // (minimum width of tile column is 256 pixels, maximum is 4096).
457 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700458
459 // Turn on row-based multithreading.
460 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700461
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700462#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
463 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700464 // Do not enable the denoiser on ARM since optimization is pending.
465 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000466 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700467 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000468#endif
jianj6bf57e32017-06-05 13:43:49 -0700469
ivica242d6382015-09-04 06:13:23 -0700470 if (codec_.mode == kScreensharing) {
471 // Adjust internal parameters to screen content.
472 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700473 }
Marco2520e722015-09-16 14:05:00 -0700474 // Enable encoder skip of static/low content blocks.
475 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000476 inited_ = true;
477 return WEBRTC_VIDEO_CODEC_OK;
478}
479
480uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
481 // Set max to the optimal buffer level (normalized by target BR),
482 // and scaled by a scale_par.
483 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
484 // This value is presented in percentage of perFrameBw:
485 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
486 // The target in % is as follows:
487 float scale_par = 0.5;
488 uint32_t target_pct =
489 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
490 // Don't go below 3 times the per frame bandwidth.
491 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800492 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000493}
494
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700495int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000496 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700497 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000498 if (!inited_) {
499 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
500 }
sprang3958ed82017-08-17 08:12:10 -0700501 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000502 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
503 }
Peter Boström49e196a2015-10-23 15:58:18 +0200504 FrameType frame_type = kVideoFrameDelta;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000505 // We only support one stream at the moment.
506 if (frame_types && frame_types->size() > 0) {
507 frame_type = (*frame_types)[0];
508 }
kwiberg352444f2016-11-28 15:58:53 -0800509 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
510 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700511
512 // Set input image for use in the callback.
513 // This was necessary since you need some information from input_image.
514 // You can save only the necessary information (such as timestamp) instead of
515 // doing this.
516 input_image_ = &input_image;
517
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000518 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
519 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000520 // Image in vpx_image_t format.
521 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000522 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
523 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
524 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
525 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
526 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
527 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000528
philipelcfc319b2015-11-10 07:17:23 -0800529 vpx_enc_frame_flags_t flags = 0;
Peter Boström49e196a2015-10-23 15:58:18 +0200530 bool send_keyframe = (frame_type == kVideoFrameKey);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000531 if (send_keyframe) {
532 // Key frame request from caller.
533 flags = VPX_EFLAG_FORCE_KF;
534 }
philipelcfc319b2015-11-10 07:17:23 -0800535
536 if (is_flexible_mode_) {
537 SuperFrameRefSettings settings;
538
539 // These structs are copied when calling vpx_codec_control,
540 // therefore it is ok for them to go out of scope.
541 vpx_svc_ref_frame_config enc_layer_conf;
542 vpx_svc_layer_id layer_id;
543
544 if (codec_.mode == kRealtimeVideo) {
545 // Real time video not yet implemented in flexible mode.
546 RTC_NOTREACHED();
547 } else {
548 settings = spatial_layer_->GetSuperFrameSettings(input_image.timestamp(),
549 send_keyframe);
550 }
551 enc_layer_conf = GenerateRefsAndFlags(settings);
552 layer_id.temporal_layer_id = 0;
553 layer_id.spatial_layer_id = settings.start_layer;
554 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
555 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
556 }
557
sprang3958ed82017-08-17 08:12:10 -0700558 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000559 uint32_t duration = 90000 / codec_.maxFramerate;
560 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
561 VPX_DL_REALTIME)) {
562 return WEBRTC_VIDEO_CODEC_ERROR;
563 }
564 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700565
566 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000567}
568
569void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800570 const vpx_codec_cx_pkt& pkt,
571 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -0700572 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000573 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700574 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800575 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Åsa Perssonff24c042015-12-04 10:58:08 +0100576 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700577 vp9_info->inter_pic_predicted =
578 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700579 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
580 vp9_info->ss_data_available =
581 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
582 ? true
583 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700584
585 vpx_svc_layer_id_t layer_id = {0};
586 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
587
sprang3958ed82017-08-17 08:12:10 -0700588 RTC_CHECK_GT(num_temporal_layers_, 0);
589 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700590 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700591 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700592 vp9_info->temporal_idx = kNoTemporalIdx;
593 } else {
594 vp9_info->temporal_idx = layer_id.temporal_layer_id;
595 }
596 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700597 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700598 vp9_info->spatial_idx = kNoSpatialIdx;
599 } else {
600 vp9_info->spatial_idx = layer_id.spatial_layer_id;
601 }
602 if (layer_id.spatial_layer_id != 0) {
603 vp9_info->ss_data_available = false;
604 }
605
asaperssona9455ab2015-07-31 06:10:09 -0700606 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800607 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700608
philipelcfc319b2015-11-10 07:17:23 -0800609 bool is_first_frame = false;
610 if (is_flexible_mode_) {
611 is_first_frame =
612 layer_id.spatial_layer_id == spatial_layer_->GetStartLayer();
613 } else {
614 is_first_frame = layer_id.spatial_layer_id == 0;
615 }
616
617 if (is_first_frame) {
asaperssona9455ab2015-07-31 06:10:09 -0700618 picture_id_ = (picture_id_ + 1) & 0x7FFF;
619 // TODO(asapersson): this info has to be obtained from the encoder.
620 vp9_info->inter_layer_predicted = false;
asapersson00ac85e2015-11-11 05:30:48 -0800621 ++frames_since_kf_;
asaperssona9455ab2015-07-31 06:10:09 -0700622 } else {
623 // TODO(asapersson): this info has to be obtained from the encoder.
624 vp9_info->inter_layer_predicted = true;
625 }
626
asapersson00ac85e2015-11-11 05:30:48 -0800627 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
628 frames_since_kf_ = 0;
629 }
630
asaperssona9455ab2015-07-31 06:10:09 -0700631 vp9_info->picture_id = picture_id_;
632
633 if (!vp9_info->flexible_mode) {
634 if (layer_id.temporal_layer_id == 0 && layer_id.spatial_layer_id == 0) {
635 tl0_pic_idx_++;
636 }
637 vp9_info->tl0_pic_idx = tl0_pic_idx_;
638 }
639
ivica7f6a6fc2015-09-08 02:40:29 -0700640 // Always populate this, so that the packetizer can properly set the marker
641 // bit.
642 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800643
644 vp9_info->num_ref_pics = 0;
645 if (vp9_info->flexible_mode) {
646 vp9_info->gof_idx = kNoGofIdx;
647 vp9_info->num_ref_pics = num_ref_pics_[layer_id.spatial_layer_id];
648 for (int i = 0; i < num_ref_pics_[layer_id.spatial_layer_id]; ++i) {
649 vp9_info->p_diff[i] = p_diff_[layer_id.spatial_layer_id][i];
650 }
651 } else {
652 vp9_info->gof_idx =
653 static_cast<uint8_t>(frames_since_kf_ % gof_.num_frames_in_gof);
asapersson00ac85e2015-11-11 05:30:48 -0800654 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800655 }
philipelcfc319b2015-11-10 07:17:23 -0800656
asaperssona9455ab2015-07-31 06:10:09 -0700657 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700658 vp9_info->spatial_layer_resolution_present = true;
659 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
660 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800661 svc_params_.scaling_factor_num[i] /
662 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700663 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800664 svc_params_.scaling_factor_num[i] /
665 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700666 }
667 if (!vp9_info->flexible_mode) {
668 vp9_info->gof.CopyGofInfoVP9(gof_);
669 }
670 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000671}
672
asaperssona9455ab2015-07-31 06:10:09 -0700673int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800674 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700675
asaperssond9f641e2016-01-21 01:11:35 -0800676 if (pkt->data.frame.sz > encoded_image_._size) {
677 delete[] encoded_image_._buffer;
678 encoded_image_._size = pkt->data.frame.sz;
679 encoded_image_._buffer = new uint8_t[encoded_image_._size];
680 }
asapersson86956de2016-01-26 01:05:20 -0800681 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
682 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800683
asapersson86956de2016-01-26 01:05:20 -0800684 // No data partitioning in VP9, so 1 partition only.
685 int part_idx = 0;
686 RTPFragmentationHeader frag_info;
687 frag_info.VerifyAndAllocateFragmentationHeader(1);
688 frag_info.fragmentationOffset[part_idx] = 0;
689 frag_info.fragmentationLength[part_idx] = pkt->data.frame.sz;
asaperssona9455ab2015-07-31 06:10:09 -0700690 frag_info.fragmentationPlType[part_idx] = 0;
691 frag_info.fragmentationTimeDiff[part_idx] = 0;
philipelcfc319b2015-11-10 07:17:23 -0800692
693 vpx_svc_layer_id_t layer_id = {0};
694 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
695 if (is_flexible_mode_ && codec_.mode == kScreensharing)
696 spatial_layer_->LayerFrameEncoded(
697 static_cast<unsigned int>(encoded_image_._length),
698 layer_id.spatial_layer_id);
699
asaperssona9455ab2015-07-31 06:10:09 -0700700 // End of frame.
701 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800702 encoded_image_._frameType = kVideoFrameDelta;
asaperssona9455ab2015-07-31 06:10:09 -0700703 if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
Peter Boström49e196a2015-10-23 15:58:18 +0200704 encoded_image_._frameType = kVideoFrameKey;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000705 }
asapersson86956de2016-01-26 01:05:20 -0800706 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
707
708 CodecSpecificInfo codec_specific;
asaperssona9455ab2015-07-31 06:10:09 -0700709 PopulateCodecSpecific(&codec_specific, *pkt, input_image_->timestamp());
710
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000711 if (encoded_image_._length > 0) {
712 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
asaperssona9455ab2015-07-31 06:10:09 -0700713 encoded_image_._timeStamp = input_image_->timestamp();
714 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
Perba7dc722016-04-19 15:01:23 +0200715 encoded_image_.rotation_ = input_image_->rotation();
ilnik00d802b2017-04-11 10:34:31 -0700716 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
717 ? VideoContentType::SCREENSHARE
718 : VideoContentType::UNSPECIFIED;
Oleh Prypinbbf46c22018-01-31 10:54:06 +0000719 encoded_image_._encodedHeight = raw_->d_h;
720 encoded_image_._encodedWidth = raw_->d_w;
sprangba050a62017-08-18 02:51:12 -0700721 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
asapersson5265fed2016-04-18 02:58:47 -0700722 int qp = -1;
723 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
724 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700725
sergeyu2cb155a2016-11-04 11:39:29 -0700726 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific,
727 &frag_info);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000728 }
729 return WEBRTC_VIDEO_CODEC_OK;
730}
731
philipelcfc319b2015-11-10 07:17:23 -0800732vpx_svc_ref_frame_config VP9EncoderImpl::GenerateRefsAndFlags(
733 const SuperFrameRefSettings& settings) {
734 static const vpx_enc_frame_flags_t kAllFlags =
735 VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_LAST |
736 VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF;
737 vpx_svc_ref_frame_config sf_conf = {};
738 if (settings.is_keyframe) {
739 // Used later on to make sure we don't make any invalid references.
740 memset(buffer_updated_at_frame_, -1, sizeof(buffer_updated_at_frame_));
741 for (int layer = settings.start_layer; layer <= settings.stop_layer;
742 ++layer) {
743 num_ref_pics_[layer] = 0;
744 buffer_updated_at_frame_[settings.layer[layer].upd_buf] = frames_encoded_;
745 // When encoding a keyframe only the alt_fb_idx is used
746 // to specify which layer ends up in which buffer.
747 sf_conf.alt_fb_idx[layer] = settings.layer[layer].upd_buf;
748 }
749 } else {
750 for (int layer_idx = settings.start_layer; layer_idx <= settings.stop_layer;
751 ++layer_idx) {
752 vpx_enc_frame_flags_t layer_flags = kAllFlags;
753 num_ref_pics_[layer_idx] = 0;
754 int8_t refs[3] = {settings.layer[layer_idx].ref_buf1,
755 settings.layer[layer_idx].ref_buf2,
756 settings.layer[layer_idx].ref_buf3};
757
758 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
759 if (refs[ref_idx] == -1)
760 continue;
761
762 RTC_DCHECK_GE(refs[ref_idx], 0);
763 RTC_DCHECK_LE(refs[ref_idx], 7);
764 // Easier to remove flags from all flags rather than having to
765 // build the flags from 0.
766 switch (num_ref_pics_[layer_idx]) {
767 case 0: {
768 sf_conf.lst_fb_idx[layer_idx] = refs[ref_idx];
769 layer_flags &= ~VP8_EFLAG_NO_REF_LAST;
770 break;
771 }
772 case 1: {
773 sf_conf.gld_fb_idx[layer_idx] = refs[ref_idx];
774 layer_flags &= ~VP8_EFLAG_NO_REF_GF;
775 break;
776 }
777 case 2: {
778 sf_conf.alt_fb_idx[layer_idx] = refs[ref_idx];
779 layer_flags &= ~VP8_EFLAG_NO_REF_ARF;
780 break;
781 }
782 }
783 // Make sure we don't reference a buffer that hasn't been
784 // used at all or hasn't been used since a keyframe.
785 RTC_DCHECK_NE(buffer_updated_at_frame_[refs[ref_idx]], -1);
786
787 p_diff_[layer_idx][num_ref_pics_[layer_idx]] =
788 frames_encoded_ - buffer_updated_at_frame_[refs[ref_idx]];
789 num_ref_pics_[layer_idx]++;
790 }
791
792 bool upd_buf_same_as_a_ref = false;
793 if (settings.layer[layer_idx].upd_buf != -1) {
794 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
795 if (settings.layer[layer_idx].upd_buf == refs[ref_idx]) {
796 switch (ref_idx) {
797 case 0: {
798 layer_flags &= ~VP8_EFLAG_NO_UPD_LAST;
799 break;
800 }
801 case 1: {
802 layer_flags &= ~VP8_EFLAG_NO_UPD_GF;
803 break;
804 }
805 case 2: {
806 layer_flags &= ~VP8_EFLAG_NO_UPD_ARF;
807 break;
808 }
809 }
810 upd_buf_same_as_a_ref = true;
811 break;
812 }
813 }
814 if (!upd_buf_same_as_a_ref) {
815 // If we have three references and a buffer is specified to be
816 // updated, then that buffer must be the same as one of the
817 // three references.
818 RTC_CHECK_LT(num_ref_pics_[layer_idx], kMaxVp9RefPics);
819
820 sf_conf.alt_fb_idx[layer_idx] = settings.layer[layer_idx].upd_buf;
821 layer_flags ^= VP8_EFLAG_NO_UPD_ARF;
822 }
823
824 int updated_buffer = settings.layer[layer_idx].upd_buf;
825 buffer_updated_at_frame_[updated_buffer] = frames_encoded_;
826 sf_conf.frame_flags[layer_idx] = layer_flags;
827 }
828 }
829 }
830 ++frames_encoded_;
831 return sf_conf;
832}
833
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000834int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000835 return WEBRTC_VIDEO_CODEC_OK;
836}
837
838int VP9EncoderImpl::RegisterEncodeCompleteCallback(
839 EncodedImageCallback* callback) {
840 encoded_complete_callback_ = callback;
841 return WEBRTC_VIDEO_CODEC_OK;
842}
843
Peter Boströmb7d9a972015-12-18 16:01:11 +0100844const char* VP9EncoderImpl::ImplementationName() const {
845 return "libvpx";
846}
847
Peter Boström12996152016-05-14 02:03:18 +0200848bool VP9Decoder::IsSupported() {
849 return true;
850}
851
Magnus Jedvert46a27652017-11-13 14:10:02 +0100852std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
853 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000854}
855
856VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700857 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000858 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700859 decoder_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000860 key_frame_required_(true) {
861 memset(&codec_, 0, sizeof(codec_));
862}
863
864VP9DecoderImpl::~VP9DecoderImpl() {
865 inited_ = true; // in order to do the actual release
866 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200867 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
868 if (num_buffers_in_use > 0) {
869 // The frame buffers are reference counted and frames are exposed after
870 // decoding. There may be valid usage cases where previous frames are still
871 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100872 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
873 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200874 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000875}
876
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000877int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
sprang3958ed82017-08-17 08:12:10 -0700878 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000879 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
880 }
881 int ret_val = Release();
882 if (ret_val < 0) {
883 return ret_val;
884 }
sprang3958ed82017-08-17 08:12:10 -0700885 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000886 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000887 }
philipelcce46fc2015-12-21 03:04:49 -0800888 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000889 // Setting number of threads to a constant value (1)
890 cfg.threads = 1;
891 cfg.h = cfg.w = 0; // set after decode
892 vpx_codec_flags_t flags = 0;
893 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
894 return WEBRTC_VIDEO_CODEC_MEMORY;
895 }
896 if (&codec_ != inst) {
897 // Save VideoCodec instance for later; mainly for duplicating the decoder.
898 codec_ = *inst;
899 }
Henrik Boström9695d852015-05-06 10:42:15 +0200900
901 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
902 return WEBRTC_VIDEO_CODEC_MEMORY;
903 }
904
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000905 inited_ = true;
906 // Always start with a complete key frame.
907 key_frame_required_ = true;
908 return WEBRTC_VIDEO_CODEC_OK;
909}
910
911int VP9DecoderImpl::Decode(const EncodedImage& input_image,
912 bool missing_frames,
913 const RTPFragmentationHeader* fragmentation,
914 const CodecSpecificInfo* codec_specific_info,
915 int64_t /*render_time_ms*/) {
916 if (!inited_) {
917 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
918 }
sprang3958ed82017-08-17 08:12:10 -0700919 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000920 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
921 }
922 // Always start with a complete key frame.
923 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200924 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000925 return WEBRTC_VIDEO_CODEC_ERROR;
926 // We have a key frame - is it complete?
927 if (input_image._completeFrame) {
928 key_frame_required_ = false;
929 } else {
930 return WEBRTC_VIDEO_CODEC_ERROR;
931 }
932 }
sprang3958ed82017-08-17 08:12:10 -0700933 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000934 vpx_image_t* img;
935 uint8_t* buffer = input_image._buffer;
936 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700937 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000938 }
Henrik Boström9695d852015-05-06 10:42:15 +0200939 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
940 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800941 if (vpx_codec_decode(decoder_, buffer,
942 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000943 VPX_DL_REALTIME)) {
944 return WEBRTC_VIDEO_CODEC_ERROR;
945 }
Henrik Boström9695d852015-05-06 10:42:15 +0200946 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
947 // It may be released by libvpx during future vpx_codec_decode or
948 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000949 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -0800950 int qp;
951 vpx_codec_err_t vpx_ret =
952 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
953 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
954 int ret =
955 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000956 if (ret != 0) {
957 return ret;
958 }
959 return WEBRTC_VIDEO_CODEC_OK;
960}
961
asapersson1490f7a2016-09-23 02:09:46 -0700962int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
963 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -0800964 int64_t ntp_time_ms,
965 int qp) {
sprang3958ed82017-08-17 08:12:10 -0700966 if (img == nullptr) {
967 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000968 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
969 }
Henrik Boström9695d852015-05-06 10:42:15 +0200970
971 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -0800972 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +0200973 // vpx_codec_decode calls or vpx_codec_destroy).
974 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
975 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700976 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +0200977 // using a WrappedI420Buffer.
978 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
979 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -0800980 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
981 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
982 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
983 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +0200984 // WrappedI420Buffer's mechanism for allowing the release of its frame
985 // buffer is through a callback function. This is where we should
986 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -0800987 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +0200988
nisseca6d5d12016-06-17 05:03:04 -0700989 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
990 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -0700991 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -0700992
Oskar Sundbom6bd39022017-11-16 10:54:49 +0100993 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000994 return WEBRTC_VIDEO_CODEC_OK;
995}
996
997int VP9DecoderImpl::RegisterDecodeCompleteCallback(
998 DecodedImageCallback* callback) {
999 decode_complete_callback_ = callback;
1000 return WEBRTC_VIDEO_CODEC_OK;
1001}
1002
1003int VP9DecoderImpl::Release() {
sprang3958ed82017-08-17 08:12:10 -07001004 if (decoder_ != nullptr) {
Henrik Boström9695d852015-05-06 10:42:15 +02001005 // When a codec is destroyed libvpx will release any buffers of
1006 // |frame_buffer_pool_| it is currently using.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001007 if (vpx_codec_destroy(decoder_)) {
1008 return WEBRTC_VIDEO_CODEC_MEMORY;
1009 }
1010 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001011 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001012 }
Henrik Boström9695d852015-05-06 10:42:15 +02001013 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1014 // still referenced externally are deleted once fully released, not returning
1015 // to the pool.
1016 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001017 inited_ = false;
1018 return WEBRTC_VIDEO_CODEC_OK;
1019}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001020
1021const char* VP9DecoderImpl::ImplementationName() const {
1022 return "libvpx";
1023}
1024
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001025} // namespace webrtc