blob: b1f71fcaff8fabaae20540745d69f2e89749ffda [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
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +020014#include <algorithm>
Sergey Silkind45b3452018-05-31 16:00:24 +020015#include <limits>
marpan@webrtc.org5b883172014-11-01 06:10:48 +000016#include <vector>
17
marpan@webrtc.org5b883172014-11-01 06:10:48 +000018#include "vpx/vp8cx.h"
19#include "vpx/vp8dx.h"
Yves Gerey665174f2018-06-19 15:03:05 +020020#include "vpx/vpx_decoder.h"
21#include "vpx/vpx_encoder.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000022
Karl Wiberg918f50c2018-07-05 11:40:33 +020023#include "absl/memory/memory.h"
Emircan Uysalercb853c82018-07-13 11:41:30 -070024#include "api/video/i010_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "common_video/include/video_frame_buffer.h"
26#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkind902d582018-05-18 17:31:19 +020027#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020028#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/checks.h"
30#include "rtc_base/keep_ref_until_done.h"
31#include "rtc_base/logging.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/timeutils.h"
33#include "rtc_base/trace_event.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000034
35namespace webrtc {
36
Sergey Silkind902d582018-05-18 17:31:19 +020037namespace {
38const float kMaxScreenSharingFramerateFps = 5.0f;
39}
40
Marco6e89b252015-07-07 14:40:38 -070041// Only positive speeds, range for real-time coding currently is: 5 - 8.
42// Lower means slower/better quality, higher means fastest/lower quality.
43int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070044#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080045 return 8;
46#else
Marco6e89b252015-07-07 14:40:38 -070047 // For smaller resolutions, use lower speed setting (get some coding gain at
48 // the cost of increased encoding complexity).
49 if (width * height <= 352 * 288)
50 return 5;
51 else
52 return 7;
Marco002f0d02015-12-17 09:49:31 -080053#endif
Marco6e89b252015-07-07 14:40:38 -070054}
55
Emircan Uysaler98badbc2018-06-28 10:59:02 -070056std::vector<SdpVideoFormat> SupportedVP9Codecs() {
Emircan Uysalercb853c82018-07-13 11:41:30 -070057 // Profile 2 might not be available on some platforms until
58 // https://bugs.chromium.org/p/webm/issues/detail?id=1544 is solved.
59 static bool vpx_supports_high_bit_depth =
60 (vpx_codec_get_caps(vpx_codec_vp9_cx()) & VPX_CODEC_CAP_HIGHBITDEPTH) !=
61 0 &&
62 (vpx_codec_get_caps(vpx_codec_vp9_dx()) & VPX_CODEC_CAP_HIGHBITDEPTH) !=
63 0;
64
65 std::vector<SdpVideoFormat> supported_formats{SdpVideoFormat(
66 cricket::kVp9CodecName,
67 {{kVP9FmtpProfileId, VP9ProfileToString(VP9Profile::kProfile0)}})};
68 if (vpx_supports_high_bit_depth) {
69 supported_formats.push_back(SdpVideoFormat(
70 cricket::kVp9CodecName,
71 {{kVP9FmtpProfileId, VP9ProfileToString(VP9Profile::kProfile2)}}));
72 }
73 return supported_formats;
Peter Boström12996152016-05-14 02:03:18 +020074}
75
Magnus Jedvert46a27652017-11-13 14:10:02 +010076std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +020077 return absl::make_unique<VP9EncoderImpl>(cricket::VideoCodec());
Emircan Uysaler98badbc2018-06-28 10:59:02 -070078}
79
80std::unique_ptr<VP9Encoder> VP9Encoder::Create(
81 const cricket::VideoCodec& codec) {
Karl Wiberg918f50c2018-07-05 11:40:33 +020082 return absl::make_unique<VP9EncoderImpl>(codec);
marpan@webrtc.org5b883172014-11-01 06:10:48 +000083}
84
asaperssona9455ab2015-07-31 06:10:09 -070085void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
86 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -080087 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -070088 enc->GetEncodedLayerFrame(pkt);
89}
90
Emircan Uysaler98badbc2018-06-28 10:59:02 -070091VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +000092 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -070093 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -070094 profile_(
95 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000096 inited_(false),
97 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000098 cpu_speed_(3),
99 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -0700100 encoder_(nullptr),
101 config_(nullptr),
102 raw_(nullptr),
103 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200104 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200105 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -0700106 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -0800107 num_spatial_layers_(0),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200108 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200109 inter_layer_pred_(InterLayerPredMode::kOn),
Sergey Silkind902d582018-05-18 17:31:19 +0200110 output_framerate_(1000.0, 1000.0),
111 last_encoded_frame_rtp_timestamp_(0),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200112 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000113 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -0800114 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000115}
116
117VP9EncoderImpl::~VP9EncoderImpl() {
118 Release();
119}
120
121int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100122 int ret_val = WEBRTC_VIDEO_CODEC_OK;
123
sprang3958ed82017-08-17 08:12:10 -0700124 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800125 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -0700126 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000127 }
sprang3958ed82017-08-17 08:12:10 -0700128 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100129 if (inited_) {
130 if (vpx_codec_destroy(encoder_)) {
131 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
132 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000133 }
134 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700135 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000136 }
sprang3958ed82017-08-17 08:12:10 -0700137 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000138 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700139 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000140 }
sprang3958ed82017-08-17 08:12:10 -0700141 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000142 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700143 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000144 }
145 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100146 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000147}
148
sprangce4aef12015-11-02 07:23:20 -0800149bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
150 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
151 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100152 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800153}
154
Erik Språng566124a2018-04-23 12:32:22 +0200155bool VP9EncoderImpl::SetSvcRates(
156 const VideoBitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700157 uint8_t i = 0;
158
Sergey Silkin86684962018-03-28 19:32:37 +0200159 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200160
“Michael23c5a992018-06-21 11:07:21 -0500161 num_active_spatial_layers_ = 0;
162 for (i = 0; i < num_spatial_layers_; ++i)
163 num_active_spatial_layers_ += bitrate_allocation.IsSpatialLayerUsed(i);
164 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
165 RTC_DCHECK_LE(num_active_spatial_layers_, num_spatial_layers_);
166
sprangce4aef12015-11-02 07:23:20 -0800167 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200168 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200169 const bool was_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200170 config_->ss_target_bitrate[sl_idx] =
171 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
172
173 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
174 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
175 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
176 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200177
178 const bool is_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
179 if (is_layer_enabled && !was_layer_enabled) {
180 if (inter_layer_pred_ == InterLayerPredMode::kOff ||
181 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic) {
182 // TODO(wemb:1526): remove key frame request when issue is fixed.
183 force_key_frame_ = true;
184 }
185 }
sprangce4aef12015-11-02 07:23:20 -0800186 }
187 } else {
188 float rate_ratio[VPX_MAX_LAYERS] = {0};
189 float total = 0;
“Michael67c8bcf2018-06-27 04:24:13 -0500190 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800191 if (svc_params_.scaling_factor_num[i] <= 0 ||
192 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100193 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800194 return false;
195 }
Yves Gerey665174f2018-06-19 15:03:05 +0200196 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
197 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800198 total += rate_ratio[i];
199 }
200
“Michael67c8bcf2018-06-27 04:24:13 -0500201 for (i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200202 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800203 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
204 config_->rc_target_bitrate * rate_ratio[i] / total);
205 if (num_temporal_layers_ == 1) {
206 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
207 } else if (num_temporal_layers_ == 2) {
208 config_->layer_target_bitrate[i * num_temporal_layers_] =
209 config_->ss_target_bitrate[i] * 2 / 3;
210 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
211 config_->ss_target_bitrate[i];
212 } else if (num_temporal_layers_ == 3) {
213 config_->layer_target_bitrate[i * num_temporal_layers_] =
214 config_->ss_target_bitrate[i] / 2;
215 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
216 config_->layer_target_bitrate[i * num_temporal_layers_] +
217 (config_->ss_target_bitrate[i] / 4);
218 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
219 config_->ss_target_bitrate[i];
220 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100221 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
222 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800223 return false;
224 }
asaperssona9455ab2015-07-31 06:10:09 -0700225 }
226 }
asaperssona9455ab2015-07-31 06:10:09 -0700227 return true;
228}
229
Erik Språng08127a92016-11-16 16:41:30 +0100230int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200231 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100232 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000233 if (!inited_) {
234 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
235 }
236 if (encoder_->err) {
237 return WEBRTC_VIDEO_CODEC_ERROR;
238 }
Erik Språng08127a92016-11-16 16:41:30 +0100239 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000240 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
241 }
242 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100243 if (codec_.maxBitrate > 0 &&
244 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
245 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000246 }
Erik Språng08127a92016-11-16 16:41:30 +0100247
Erik Språng08127a92016-11-16 16:41:30 +0100248 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700249
Sergey Silkin86684962018-03-28 19:32:37 +0200250 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700251 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
252 }
253
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000254 // Update encoder context
255 if (vpx_codec_enc_config_set(encoder_, config_)) {
256 return WEBRTC_VIDEO_CODEC_ERROR;
257 }
258 return WEBRTC_VIDEO_CODEC_OK;
259}
260
261int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
262 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000263 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700264 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000265 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
266 }
267 if (inst->maxFramerate < 1) {
268 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
269 }
270 // Allow zero to represent an unspecified maxBitRate
271 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
272 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
273 }
274 if (inst->width < 1 || inst->height < 1) {
275 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
276 }
277 if (number_of_cores < 1) {
278 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
279 }
hta257dc392016-10-25 09:05:06 -0700280 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700281 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
282 }
ilnik2a8c2f52017-02-15 02:23:28 -0800283 // libvpx probably does not support more than 3 spatial layers.
284 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700285 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
286 }
philipelcfc319b2015-11-10 07:17:23 -0800287
asapersson86956de2016-01-26 01:05:20 -0800288 int ret_val = Release();
289 if (ret_val < 0) {
290 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000291 }
sprang3958ed82017-08-17 08:12:10 -0700292 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000293 encoder_ = new vpx_codec_ctx_t;
294 }
sprang3958ed82017-08-17 08:12:10 -0700295 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000296 config_ = new vpx_codec_enc_cfg_t;
297 }
298 timestamp_ = 0;
299 if (&codec_ != inst) {
300 codec_ = *inst;
301 }
asaperssona9455ab2015-07-31 06:10:09 -0700302
hta257dc392016-10-25 09:05:06 -0700303 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200304 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700305 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700306 if (num_temporal_layers_ == 0)
307 num_temporal_layers_ = 1;
308
Sergey Silkind902d582018-05-18 17:31:19 +0200309 // Init framerate controller.
310 output_framerate_.Reset();
Niels Möllere3cf3d02018-06-13 11:52:16 +0200311 if (codec_.mode == VideoCodecMode::kScreensharing) {
Sergey Silkind902d582018-05-18 17:31:19 +0200312 target_framerate_fps_ = kMaxScreenSharingFramerateFps;
313 } else {
314 target_framerate_fps_.reset();
315 }
316
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200317 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
318 // Flexible mode requires SVC to be enabled since libvpx API only allows
319 // to get reference list in SVC mode.
320 RTC_DCHECK(!inst->VP9().flexibleMode || is_svc_);
321
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000322 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700323 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800324 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000325 }
nisseeb44b392017-04-28 07:18:05 -0700326 encoded_image_._size =
327 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000328 encoded_image_._buffer = new uint8_t[encoded_image_._size];
329 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000330 // Populate encoder configuration with default values.
331 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
332 return WEBRTC_VIDEO_CODEC_ERROR;
333 }
Emircan Uysalercb853c82018-07-13 11:41:30 -0700334
335 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
336 unsigned int bits_for_storage = 8;
337 switch (profile_) {
338 case VP9Profile::kProfile0:
339 img_fmt = VPX_IMG_FMT_I420;
340 bits_for_storage = 8;
341 config_->g_bit_depth = VPX_BITS_8;
342 config_->g_profile = 0;
343 config_->g_input_bit_depth = 8;
344 break;
345 case VP9Profile::kProfile2:
346 img_fmt = VPX_IMG_FMT_I42016;
347 bits_for_storage = 16;
348 config_->g_bit_depth = VPX_BITS_10;
349 config_->g_profile = 2;
350 config_->g_input_bit_depth = 10;
351 break;
352 }
353
354 // Creating a wrapper to the image - setting image data to nullptr. Actual
355 // pointer will be set in encode. Setting align to 1, as it is meaningless
356 // (actual memory is not allocated).
357 raw_ =
358 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
359 raw_->bit_depth = bits_for_storage;
360
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000361 config_->g_w = codec_.width;
362 config_->g_h = codec_.height;
363 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200364 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000365 // Setting the time base of the codec.
366 config_->g_timebase.num = 1;
367 config_->g_timebase.den = 90000;
368 config_->g_lag_in_frames = 0; // 0- no frame lagging
369 config_->g_threads = 1;
370 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700371 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000372 config_->rc_end_usage = VPX_CBR;
373 config_->g_pass = VPX_RC_ONE_PASS;
374 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000375 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000376 config_->rc_undershoot_pct = 50;
377 config_->rc_overshoot_pct = 50;
378 config_->rc_buf_initial_sz = 500;
379 config_->rc_buf_optimal_sz = 600;
380 config_->rc_buf_sz = 1000;
381 // Set the maximum target size of any key-frame.
382 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700383 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000384 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700385 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100386 // Needs to be set (in svc mode) to get correct periodic key frame interval
387 // (will have no effect in non-svc).
388 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000389 } else {
390 config_->kf_mode = VPX_KF_DISABLED;
391 }
hta257dc392016-10-25 09:05:06 -0700392 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000393 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800394 config_->g_threads =
395 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700396
Marco6e89b252015-07-07 14:40:38 -0700397 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700398
399 // TODO(asapersson): Check configuration of temporal switch up and increase
400 // pattern length.
hta257dc392016-10-25 09:05:06 -0700401 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200402
403 // TODO(ssilkin): Only non-flexible mode is supported for now.
404 RTC_DCHECK(!is_flexible_mode_);
405
406 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700407 gof_.SetGofInfoVP9(kTemporalStructureMode1);
408 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
409 config_->ts_number_layers = 1;
410 config_->ts_rate_decimator[0] = 1;
411 config_->ts_periodicity = 1;
412 config_->ts_layer_id[0] = 0;
413 } else if (num_temporal_layers_ == 2) {
414 gof_.SetGofInfoVP9(kTemporalStructureMode2);
415 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
416 config_->ts_number_layers = 2;
417 config_->ts_rate_decimator[0] = 2;
418 config_->ts_rate_decimator[1] = 1;
419 config_->ts_periodicity = 2;
420 config_->ts_layer_id[0] = 0;
421 config_->ts_layer_id[1] = 1;
422 } else if (num_temporal_layers_ == 3) {
423 gof_.SetGofInfoVP9(kTemporalStructureMode3);
424 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
425 config_->ts_number_layers = 3;
426 config_->ts_rate_decimator[0] = 4;
427 config_->ts_rate_decimator[1] = 2;
428 config_->ts_rate_decimator[2] = 1;
429 config_->ts_periodicity = 4;
430 config_->ts_layer_id[0] = 0;
431 config_->ts_layer_id[1] = 2;
432 config_->ts_layer_id[2] = 1;
433 config_->ts_layer_id[3] = 2;
434 } else {
435 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
436 }
437
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200438 inter_layer_pred_ = inst->VP9().interLayerPred;
439
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200440 ref_buf_.clear();
441
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000442 return InitAndSetControlSettings(inst);
443}
444
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000445int VP9EncoderImpl::NumberOfThreads(int width,
446 int height,
447 int number_of_cores) {
448 // Keep the number of encoder threads equal to the possible number of column
449 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
450 if (width * height >= 1280 * 720 && number_of_cores > 4) {
451 return 4;
jianj23173a32017-07-12 16:11:09 -0700452 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000453 return 2;
454 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200455// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800456#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
457 defined(WEBRTC_ANDROID)
458 if (width * height >= 320 * 180 && number_of_cores > 2) {
459 return 2;
460 }
461#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000462 // 1 thread less than VGA.
463 return 1;
464 }
465}
466
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000467int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100468 // Set QP-min/max per spatial and temporal layer.
469 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
470 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800471 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
472 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100473 }
asaperssona9455ab2015-07-31 06:10:09 -0700474 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800475 if (ExplicitlyConfiguredSpatialLayers()) {
476 for (int i = 0; i < num_spatial_layers_; ++i) {
477 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200478 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100479 const int scale_factor = codec_.width / layer.width;
480 RTC_DCHECK_GT(scale_factor, 0);
481
482 // Ensure scaler factor is integer.
483 if (scale_factor * layer.width != codec_.width) {
484 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
485 }
486
487 // Ensure scale factor is the same in both dimensions.
488 if (scale_factor * layer.height != codec_.height) {
489 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
490 }
491
492 // Ensure scale factor is power of two.
493 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
494 if (!is_pow_of_two) {
495 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
496 }
497
498 svc_params_.scaling_factor_num[i] = 1;
499 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800500 }
501 } else {
502 int scaling_factor_num = 256;
503 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800504 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800505 svc_params_.scaling_factor_num[i] = scaling_factor_num;
506 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800507 }
asaperssona9455ab2015-07-31 06:10:09 -0700508 }
509
Sergey Silkin86684962018-03-28 19:32:37 +0200510 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200511 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200512 inst->startBitrate * 1000, inst->maxFramerate);
513 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700514 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
515 }
516
Emircan Uysalercb853c82018-07-13 11:41:30 -0700517 const vpx_codec_err_t rv = vpx_codec_enc_init(
518 encoder_, vpx_codec_vp9_cx(), config_,
519 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
520 if (rv != VPX_CODEC_OK) {
521 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000522 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
523 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000524 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
525 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
526 rc_max_intra_target_);
527 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700528 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700529
jianj822e5932017-07-12 16:09:58 -0700530 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200531
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200532 if (is_svc_) {
533 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
534 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700535 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200536
537 if (num_spatial_layers_ > 1) {
538 switch (inter_layer_pred_) {
539 case InterLayerPredMode::kOn:
540 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
541 break;
542 case InterLayerPredMode::kOff:
543 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
544 break;
545 case InterLayerPredMode::kOnKeyPic:
546 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
547 break;
548 default:
549 RTC_NOTREACHED();
550 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200551
Sergey Silkinee203362018-05-30 11:34:08 +0200552 // Configure encoder to drop entire superframe whenever it needs to drop
553 // a layer. This mode is prefered over per-layer dropping which causes
554 // quality flickering and is not compatible with RTP non-flexible mode.
555 vpx_svc_frame_drop_t svc_drop_frame;
556 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
557 svc_drop_frame.framedrop_mode = FULL_SUPERFRAME_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200558 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200559 for (size_t i = 0; i < num_spatial_layers_; ++i) {
560 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200561 }
Sergey Silkinee203362018-05-30 11:34:08 +0200562 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200563 }
564
asaperssona9455ab2015-07-31 06:10:09 -0700565 // Register callback for getting each spatial layer.
566 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800567 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
568 reinterpret_cast<void*>(this)};
569 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
570 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700571
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000572 // Control function to set the number of column tiles in encoding a frame, in
573 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
574 // The number tile columns will be capped by the encoder based on image size
575 // (minimum width of tile column is 256 pixels, maximum is 4096).
576 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700577
578 // Turn on row-based multithreading.
579 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700580
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700581#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200582 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700583 // Do not enable the denoiser on ARM since optimization is pending.
584 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000585 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700586 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000587#endif
jianj6bf57e32017-06-05 13:43:49 -0700588
Niels Möllere3cf3d02018-06-13 11:52:16 +0200589 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700590 // Adjust internal parameters to screen content.
591 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700592 }
Marco2520e722015-09-16 14:05:00 -0700593 // Enable encoder skip of static/low content blocks.
594 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000595 inited_ = true;
596 return WEBRTC_VIDEO_CODEC_OK;
597}
598
599uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
600 // Set max to the optimal buffer level (normalized by target BR),
601 // and scaled by a scale_par.
602 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
603 // This value is presented in percentage of perFrameBw:
604 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
605 // The target in % is as follows:
606 float scale_par = 0.5;
607 uint32_t target_pct =
608 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
609 // Don't go below 3 times the per frame bandwidth.
610 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800611 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000612}
613
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700614int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000615 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700616 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000617 if (!inited_) {
618 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
619 }
sprang3958ed82017-08-17 08:12:10 -0700620 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000621 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
622 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200623
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000624 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200625 if (frame_types && !frame_types->empty()) {
626 if ((*frame_types)[0] == kVideoFrameKey) {
627 force_key_frame_ = true;
628 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000629 }
Sergey Silkind902d582018-05-18 17:31:19 +0200630
Niels Möllere3cf3d02018-06-13 11:52:16 +0200631 if (VideoCodecMode::kScreensharing == codec_.mode && !force_key_frame_) {
Sergey Silkind902d582018-05-18 17:31:19 +0200632 if (DropFrame(input_image.timestamp())) {
633 return WEBRTC_VIDEO_CODEC_OK;
634 }
635 }
636
kwiberg352444f2016-11-28 15:58:53 -0800637 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
638 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700639
640 // Set input image for use in the callback.
641 // This was necessary since you need some information from input_image.
642 // You can save only the necessary information (such as timestamp) instead of
643 // doing this.
644 input_image_ = &input_image;
645
Emircan Uysalercb853c82018-07-13 11:41:30 -0700646 // Keep reference to buffer until encode completes.
647 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
648 rtc::scoped_refptr<I010BufferInterface> i010_buffer;
649 switch (profile_) {
650 case VP9Profile::kProfile0: {
651 i420_buffer = input_image.video_frame_buffer()->ToI420();
652 // Image in vpx_image_t format.
653 // Input image is const. VPX's raw image is not defined as const.
654 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
655 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
656 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
657 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
658 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
659 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
660 break;
661 }
662 case VP9Profile::kProfile2: {
663 // We can inject kI010 frames directly for encode. All other formats
664 // should be converted to it.
665 switch (input_image.video_frame_buffer()->type()) {
666 case VideoFrameBuffer::Type::kI010: {
667 i010_buffer = input_image.video_frame_buffer()->GetI010();
668 break;
669 }
670 default: {
671 i010_buffer =
672 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
673 }
674 }
675 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
676 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
677 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
678 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
679 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
680 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
681 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
682 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
683 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
684 break;
685 }
686 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000687
philipelcfc319b2015-11-10 07:17:23 -0800688 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200689 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000690 flags = VPX_EFLAG_FORCE_KF;
691 }
philipelcfc319b2015-11-10 07:17:23 -0800692
sprang3958ed82017-08-17 08:12:10 -0700693 RTC_CHECK_GT(codec_.maxFramerate, 0);
Sergey Silkind902d582018-05-18 17:31:19 +0200694 uint32_t duration =
695 90000 / target_framerate_fps_.value_or(codec_.maxFramerate);
Emircan Uysalercb853c82018-07-13 11:41:30 -0700696 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
697 duration, flags, VPX_DL_REALTIME);
698 if (rv != VPX_CODEC_OK) {
699 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
700 << "\n"
701 << "Details: " << vpx_codec_error(encoder_) << "\n"
702 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000703 return WEBRTC_VIDEO_CODEC_ERROR;
704 }
705 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700706
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200707 const bool end_of_picture = true;
708 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200709
asaperssona9455ab2015-07-31 06:10:09 -0700710 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000711}
712
713void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800714 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200715 uint32_t timestamp,
716 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700717 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000718 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700719 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800720 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200721
722 vp9_info->first_frame_in_picture = first_frame_in_picture;
hta257dc392016-10-25 09:05:06 -0700723 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
724 vp9_info->ss_data_available =
725 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
726 ? true
727 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700728
729 vpx_svc_layer_id_t layer_id = {0};
730 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
731
sprang3958ed82017-08-17 08:12:10 -0700732 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -0500733 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700734 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700735 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700736 vp9_info->temporal_idx = kNoTemporalIdx;
737 } else {
738 vp9_info->temporal_idx = layer_id.temporal_layer_id;
739 }
“Michael23c5a992018-06-21 11:07:21 -0500740 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700741 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700742 vp9_info->spatial_idx = kNoSpatialIdx;
743 } else {
744 vp9_info->spatial_idx = layer_id.spatial_layer_id;
745 }
746 if (layer_id.spatial_layer_id != 0) {
747 vp9_info->ss_data_available = false;
748 }
749
asaperssona9455ab2015-07-31 06:10:09 -0700750 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800751 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700752
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200753 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
754 pics_since_key_ = 0;
755 } else if (first_frame_in_picture) {
756 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700757 }
758
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200759 const bool is_key_pic = (pics_since_key_ == 0);
760 const bool is_inter_layer_pred_allowed =
761 (inter_layer_pred_ == InterLayerPredMode::kOn ||
762 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
763
764 // Always set inter_layer_predicted to true on high layer frame if inter-layer
765 // prediction (ILP) is allowed even if encoder didn't actually use it.
766 // Setting inter_layer_predicted to false would allow receiver to decode high
767 // layer frame without decoding low layer frame. If that would happen (e.g.
768 // if low layer frame is lost) then receiver won't be able to decode next high
769 // layer frame which uses ILP.
770 vp9_info->inter_layer_predicted =
771 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
772
773 const bool is_last_layer =
“Michael23c5a992018-06-21 11:07:21 -0500774 (layer_id.spatial_layer_id + 1 == num_active_spatial_layers_);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200775 vp9_info->non_ref_for_inter_layer_pred =
776 is_last_layer ? true : !is_inter_layer_pred_allowed;
asapersson00ac85e2015-11-11 05:30:48 -0800777
ivica7f6a6fc2015-09-08 02:40:29 -0700778 // Always populate this, so that the packetizer can properly set the marker
779 // bit.
“Michael23c5a992018-06-21 11:07:21 -0500780 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800781
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200782 RTC_DCHECK(!vp9_info->flexible_mode);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200783
784 vp9_info->num_ref_pics = 0;
785 if (vp9_info->flexible_mode) {
786 vp9_info->gof_idx = kNoGofIdx;
787 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
788 vp9_info);
789 } else {
790 vp9_info->gof_idx =
791 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
792 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
793 vp9_info->num_ref_pics = gof_.num_ref_pics[vp9_info->gof_idx];
794 }
795
796 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
797
asaperssona9455ab2015-07-31 06:10:09 -0700798 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700799 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -0500800 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +0200801 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800802 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +0200803 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800804 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700805 }
806 if (!vp9_info->flexible_mode) {
807 vp9_info->gof.CopyGofInfoVP9(gof_);
808 }
809 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000810}
811
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200812void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
813 const size_t pic_num,
814 const bool inter_layer_predicted,
815 CodecSpecificInfoVP9* vp9_info) {
816 vpx_svc_layer_id_t layer_id = {0};
817 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
818
819 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
820 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
821
822 std::vector<RefFrameBuffer> ref_buf_list;
823 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
824 const size_t fb_idx = enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
825 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
826 ref_buf_list.push_back(ref_buf_.at(fb_idx));
827 }
828
829 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
830 const size_t fb_idx = enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
831 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
832 ref_buf_list.push_back(ref_buf_.at(fb_idx));
833 }
834
835 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
836 const size_t fb_idx = enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
837 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
838 ref_buf_list.push_back(ref_buf_.at(fb_idx));
839 }
840
841 size_t max_ref_temporal_layer_id = 0;
842
843 vp9_info->num_ref_pics = 0;
844 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
845 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
846 if (ref_buf.pic_num < pic_num) {
847 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
848 // RTP spec limits temporal prediction to the same spatial layer.
849 // It is safe to ignore this requirement if inter-layer prediction is
850 // enabled for all frames when all base frames are relayed to receiver.
851 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
852 }
853 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
854
855 const size_t p_diff = pic_num - ref_buf.pic_num;
856 RTC_DCHECK_LE(p_diff, 127UL);
857
858 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
859 ++vp9_info->num_ref_pics;
860
861 max_ref_temporal_layer_id =
862 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
863 } else {
864 RTC_DCHECK(inter_layer_predicted);
865 // RTP spec only allows to use previous spatial layer for inter-layer
866 // prediction.
867 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
868 }
869 }
870
871 vp9_info->temporal_up_switch =
872 (max_ref_temporal_layer_id <
873 static_cast<size_t>(layer_id.temporal_layer_id));
874}
875
876void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
877 const size_t pic_num) {
878 vpx_svc_layer_id_t layer_id = {0};
879 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
880
881 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
882 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
883
884 const bool is_key_frame =
885 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
886
887 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
888 layer_id.temporal_layer_id);
889
890 if (is_key_frame && layer_id.spatial_layer_id == 0) {
891 // Key frame updates all ref buffers.
892 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
893 ref_buf_[i] = frame_buf;
894 }
895 } else {
896 if (enc_layer_conf.update_last[layer_id.spatial_layer_id]) {
897 ref_buf_[enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id]] =
898 frame_buf;
899 }
900
901 if (enc_layer_conf.update_alt_ref[layer_id.spatial_layer_id]) {
902 ref_buf_[enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id]] =
903 frame_buf;
904 }
905
906 if (enc_layer_conf.update_golden[layer_id.spatial_layer_id]) {
907 ref_buf_[enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id]] =
908 frame_buf;
909 }
910 }
911}
912
asaperssona9455ab2015-07-31 06:10:09 -0700913int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800914 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700915
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200916 if (pkt->data.frame.sz == 0) {
917 // Ignore dropped frame.
918 return WEBRTC_VIDEO_CODEC_OK;
919 }
920
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200921 vpx_svc_layer_id_t layer_id = {0};
922 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
923
924 const bool first_frame_in_picture = encoded_image_._length == 0;
925 // Ensure we don't buffer layers of previous picture (superframe).
926 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
927
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200928 const bool end_of_picture = false;
929 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200930
asaperssond9f641e2016-01-21 01:11:35 -0800931 if (pkt->data.frame.sz > encoded_image_._size) {
932 delete[] encoded_image_._buffer;
933 encoded_image_._size = pkt->data.frame.sz;
934 encoded_image_._buffer = new uint8_t[encoded_image_._size];
935 }
asapersson86956de2016-01-26 01:05:20 -0800936 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
937 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800938
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200939 const bool is_key_frame =
940 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
941 // Ensure encoder issued key frame on request.
942 RTC_DCHECK(is_key_frame || !force_key_frame_);
943
asaperssona9455ab2015-07-31 06:10:09 -0700944 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800945 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200946 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +0200947 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200948 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000949 }
asapersson86956de2016-01-26 01:05:20 -0800950 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
951
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200952 memset(&codec_specific_, 0, sizeof(codec_specific_));
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200953 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
954 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -0700955
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200956 if (is_flexible_mode_) {
957 UpdateReferenceBuffers(*pkt, pics_since_key_);
958 }
959
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200960 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
961 encoded_image_._timeStamp = input_image_->timestamp();
962 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
963 encoded_image_.rotation_ = input_image_->rotation();
Niels Möllere3cf3d02018-06-13 11:52:16 +0200964 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200965 ? VideoContentType::SCREENSHARE
966 : VideoContentType::UNSPECIFIED;
967 encoded_image_._encodedHeight =
968 pkt->data.frame.height[layer_id.spatial_layer_id];
969 encoded_image_._encodedWidth =
970 pkt->data.frame.width[layer_id.spatial_layer_id];
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +0200971 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200972 int qp = -1;
973 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
974 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700975
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000976 return WEBRTC_VIDEO_CODEC_OK;
977}
978
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200979void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200980 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200981 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200982
983 // No data partitioning in VP9, so 1 partition only.
984 int part_idx = 0;
985 RTPFragmentationHeader frag_info;
986 frag_info.VerifyAndAllocateFragmentationHeader(1);
987 frag_info.fragmentationOffset[part_idx] = 0;
988 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
989 frag_info.fragmentationPlType[part_idx] = 0;
990 frag_info.fragmentationTimeDiff[part_idx] = 0;
991
992 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
993 &frag_info);
994 encoded_image_._length = 0;
Sergey Silkind902d582018-05-18 17:31:19 +0200995
996 if (end_of_picture) {
997 const uint32_t timestamp_ms =
998 1000 * encoded_image_._timeStamp / kVideoPayloadTypeFrequency;
999 output_framerate_.Update(1, timestamp_ms);
1000 last_encoded_frame_rtp_timestamp_ = encoded_image_._timeStamp;
1001 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001002 }
1003}
1004
Sergey Silkind902d582018-05-18 17:31:19 +02001005bool VP9EncoderImpl::DropFrame(uint32_t rtp_timestamp) {
1006 if (target_framerate_fps_) {
1007 if (rtp_timestamp < last_encoded_frame_rtp_timestamp_) {
1008 // Timestamp has wrapped around. Reset framerate statistic.
1009 output_framerate_.Reset();
1010 return false;
1011 }
1012
1013 const uint32_t timestamp_ms =
1014 1000 * rtp_timestamp / kVideoPayloadTypeFrequency;
1015 const uint32_t framerate_fps =
1016 output_framerate_.Rate(timestamp_ms).value_or(0);
1017 if (framerate_fps > *target_framerate_fps_) {
1018 return true;
1019 }
1020
1021 // Primarily check if frame interval is too short using frame timestamps,
1022 // as if they are correct they won't be affected by queuing in webrtc.
1023 const uint32_t expected_frame_interval =
1024 kVideoPayloadTypeFrequency / *target_framerate_fps_;
1025
1026 const uint32_t ts_diff = rtp_timestamp - last_encoded_frame_rtp_timestamp_;
1027 if (ts_diff < 85 * expected_frame_interval / 100) {
1028 return true;
1029 }
1030 }
1031
1032 return false;
1033}
1034
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001035int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001036 return WEBRTC_VIDEO_CODEC_OK;
1037}
1038
1039int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1040 EncodedImageCallback* callback) {
1041 encoded_complete_callback_ = callback;
1042 return WEBRTC_VIDEO_CODEC_OK;
1043}
1044
Peter Boströmb7d9a972015-12-18 16:01:11 +01001045const char* VP9EncoderImpl::ImplementationName() const {
1046 return "libvpx";
1047}
1048
Magnus Jedvert46a27652017-11-13 14:10:02 +01001049std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001050 return absl::make_unique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001051}
1052
1053VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001054 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001055 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001056 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001057 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001058
1059VP9DecoderImpl::~VP9DecoderImpl() {
1060 inited_ = true; // in order to do the actual release
1061 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001062 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1063 if (num_buffers_in_use > 0) {
1064 // The frame buffers are reference counted and frames are exposed after
1065 // decoding. There may be valid usage cases where previous frames are still
1066 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001067 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1068 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001069 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001070}
1071
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001072int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001073 int ret_val = Release();
1074 if (ret_val < 0) {
1075 return ret_val;
1076 }
sprang3958ed82017-08-17 08:12:10 -07001077 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001078 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001079 }
philipelcce46fc2015-12-21 03:04:49 -08001080 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001081 // Setting number of threads to a constant value (1)
1082 cfg.threads = 1;
1083 cfg.h = cfg.w = 0; // set after decode
1084 vpx_codec_flags_t flags = 0;
1085 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1086 return WEBRTC_VIDEO_CODEC_MEMORY;
1087 }
Henrik Boström9695d852015-05-06 10:42:15 +02001088
1089 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1090 return WEBRTC_VIDEO_CODEC_MEMORY;
1091 }
1092
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001093 inited_ = true;
1094 // Always start with a complete key frame.
1095 key_frame_required_ = true;
1096 return WEBRTC_VIDEO_CODEC_OK;
1097}
1098
1099int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1100 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001101 const CodecSpecificInfo* codec_specific_info,
1102 int64_t /*render_time_ms*/) {
1103 if (!inited_) {
1104 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1105 }
sprang3958ed82017-08-17 08:12:10 -07001106 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001107 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1108 }
1109 // Always start with a complete key frame.
1110 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +02001111 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001112 return WEBRTC_VIDEO_CODEC_ERROR;
1113 // We have a key frame - is it complete?
1114 if (input_image._completeFrame) {
1115 key_frame_required_ = false;
1116 } else {
1117 return WEBRTC_VIDEO_CODEC_ERROR;
1118 }
1119 }
sprang3958ed82017-08-17 08:12:10 -07001120 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001121 vpx_image_t* img;
1122 uint8_t* buffer = input_image._buffer;
1123 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -07001124 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001125 }
Henrik Boström9695d852015-05-06 10:42:15 +02001126 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1127 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001128 if (vpx_codec_decode(decoder_, buffer,
1129 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001130 VPX_DL_REALTIME)) {
1131 return WEBRTC_VIDEO_CODEC_ERROR;
1132 }
Henrik Boström9695d852015-05-06 10:42:15 +02001133 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1134 // It may be released by libvpx during future vpx_codec_decode or
1135 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001136 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001137 int qp;
1138 vpx_codec_err_t vpx_ret =
1139 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1140 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
1141 int ret =
1142 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001143 if (ret != 0) {
1144 return ret;
1145 }
1146 return WEBRTC_VIDEO_CODEC_OK;
1147}
1148
asapersson1490f7a2016-09-23 02:09:46 -07001149int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
1150 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -08001151 int64_t ntp_time_ms,
1152 int qp) {
sprang3958ed82017-08-17 08:12:10 -07001153 if (img == nullptr) {
1154 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001155 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1156 }
Henrik Boström9695d852015-05-06 10:42:15 +02001157
1158 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001159 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001160 // vpx_codec_decode calls or vpx_codec_destroy).
1161 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1162 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysalercb853c82018-07-13 11:41:30 -07001163
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001164 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysalercb853c82018-07-13 11:41:30 -07001165 // using a Wrapped*Buffer.
1166 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1167 switch (img->bit_depth) {
1168 case 8:
1169 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001170 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1171 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1172 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1173 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001174 // WrappedI420Buffer's mechanism for allowing the release of its frame
1175 // buffer is through a callback function. This is where we should
1176 // release |img_buffer|.
Emircan Uysalercb853c82018-07-13 11:41:30 -07001177 rtc::KeepRefUntilDone(img_buffer));
1178 break;
1179 case 10:
1180 img_wrapped_buffer = WrapI010Buffer(
1181 img->d_w, img->d_h,
1182 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1183 img->stride[VPX_PLANE_Y] / 2,
1184 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1185 img->stride[VPX_PLANE_U] / 2,
1186 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1187 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1188 break;
1189 default:
1190 RTC_NOTREACHED();
1191 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1192 }
nisseca6d5d12016-06-17 05:03:04 -07001193 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
1194 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -07001195 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -07001196
Danil Chapovalov0040b662018-06-18 10:48:16 +02001197 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001198 return WEBRTC_VIDEO_CODEC_OK;
1199}
1200
1201int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1202 DecodedImageCallback* callback) {
1203 decode_complete_callback_ = callback;
1204 return WEBRTC_VIDEO_CODEC_OK;
1205}
1206
1207int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001208 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1209
sprang3958ed82017-08-17 08:12:10 -07001210 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001211 if (inited_) {
1212 // When a codec is destroyed libvpx will release any buffers of
1213 // |frame_buffer_pool_| it is currently using.
1214 if (vpx_codec_destroy(decoder_)) {
1215 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1216 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001217 }
1218 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001219 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001220 }
Henrik Boström9695d852015-05-06 10:42:15 +02001221 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1222 // still referenced externally are deleted once fully released, not returning
1223 // to the pool.
1224 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001225 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001226 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001227}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001228
1229const char* VP9DecoderImpl::ImplementationName() const {
1230 return "libvpx";
1231}
1232
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001233} // namespace webrtc