blob: 580556392b67f4ddaf69f513236dce5427b8db65 [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 Uysaler800787f2018-07-16 10:01:49 -070024#include "api/video/color_space.h"
Emircan Uysaler0823eec2018-07-13 17:10:00 -070025#include "api/video/i010_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "common_video/include/video_frame_buffer.h"
27#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkind902d582018-05-18 17:31:19 +020028#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020029#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/checks.h"
31#include "rtc_base/keep_ref_until_done.h"
32#include "rtc_base/logging.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/timeutils.h"
34#include "rtc_base/trace_event.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000035
36namespace webrtc {
37
Sergey Silkind902d582018-05-18 17:31:19 +020038namespace {
39const float kMaxScreenSharingFramerateFps = 5.0f;
Sergey Silkind902d582018-05-18 17:31:19 +020040
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}
Emircan Uysaler715cc232018-07-23 17:50:43 -070055// Helper class for extracting VP9 colorspace.
56ColorSpace ExtractVP9ColorSpace(vpx_color_space_t space_t,
57 vpx_color_range_t range_t,
58 unsigned int bit_depth) {
59 ColorSpace::PrimaryID primaries = ColorSpace::PrimaryID::kInvalid;
60 ColorSpace::TransferID transfer = ColorSpace::TransferID::kInvalid;
61 ColorSpace::MatrixID matrix = ColorSpace::MatrixID::kInvalid;
62 switch (space_t) {
63 case VPX_CS_BT_601:
64 case VPX_CS_SMPTE_170:
65 primaries = ColorSpace::PrimaryID::kSMPTE170M;
66 transfer = ColorSpace::TransferID::kSMPTE170M;
67 matrix = ColorSpace::MatrixID::kSMPTE170M;
68 break;
69 case VPX_CS_SMPTE_240:
70 primaries = ColorSpace::PrimaryID::kSMPTE240M;
71 transfer = ColorSpace::TransferID::kSMPTE240M;
72 matrix = ColorSpace::MatrixID::kSMPTE240M;
73 break;
74 case VPX_CS_BT_709:
75 primaries = ColorSpace::PrimaryID::kBT709;
76 transfer = ColorSpace::TransferID::kBT709;
77 matrix = ColorSpace::MatrixID::kBT709;
78 break;
79 case VPX_CS_BT_2020:
80 primaries = ColorSpace::PrimaryID::kBT2020;
81 switch (bit_depth) {
82 case 8:
83 transfer = ColorSpace::TransferID::kBT709;
84 break;
85 case 10:
86 transfer = ColorSpace::TransferID::kBT2020_10;
87 break;
88 default:
89 RTC_NOTREACHED();
90 break;
91 }
92 matrix = ColorSpace::MatrixID::kBT2020_NCL;
93 break;
94 case VPX_CS_SRGB:
95 primaries = ColorSpace::PrimaryID::kBT709;
96 transfer = ColorSpace::TransferID::kIEC61966_2_1;
97 matrix = ColorSpace::MatrixID::kBT709;
98 break;
99 default:
100 break;
101 }
102
103 ColorSpace::RangeID range = ColorSpace::RangeID::kInvalid;
104 switch (range_t) {
105 case VPX_CR_STUDIO_RANGE:
106 range = ColorSpace::RangeID::kLimited;
107 break;
108 case VPX_CR_FULL_RANGE:
109 range = ColorSpace::RangeID::kFull;
110 break;
111 default:
112 break;
113 }
114 return ColorSpace(primaries, transfer, matrix, range);
115}
116} // namespace
Marco6e89b252015-07-07 14:40:38 -0700117
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700118std::vector<SdpVideoFormat> SupportedVP9Codecs() {
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700119 // TODO(emircan): Add Profile 2 support after fixing browser_tests.
120 std::vector<SdpVideoFormat> supported_formats{SdpVideoFormat(
121 cricket::kVp9CodecName,
122 {{kVP9FmtpProfileId, VP9ProfileToString(VP9Profile::kProfile0)}})};
123 return supported_formats;
Peter Boström12996152016-05-14 02:03:18 +0200124}
125
Magnus Jedvert46a27652017-11-13 14:10:02 +0100126std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200127 return absl::make_unique<VP9EncoderImpl>(cricket::VideoCodec());
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700128}
129
130std::unique_ptr<VP9Encoder> VP9Encoder::Create(
131 const cricket::VideoCodec& codec) {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200132 return absl::make_unique<VP9EncoderImpl>(codec);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000133}
134
asaperssona9455ab2015-07-31 06:10:09 -0700135void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
136 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -0800137 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -0700138 enc->GetEncodedLayerFrame(pkt);
139}
140
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700141VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000142 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -0700143 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700144 profile_(
145 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000146 inited_(false),
147 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000148 cpu_speed_(3),
149 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -0700150 encoder_(nullptr),
151 config_(nullptr),
152 raw_(nullptr),
153 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200154 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200155 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -0700156 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -0800157 num_spatial_layers_(0),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200158 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200159 inter_layer_pred_(InterLayerPredMode::kOn),
Sergey Silkinae3144c2018-08-29 01:05:26 +0200160 framerate_controller_(kMaxScreenSharingFramerateFps),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200161 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000162 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -0800163 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000164}
165
166VP9EncoderImpl::~VP9EncoderImpl() {
167 Release();
168}
169
170int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100171 int ret_val = WEBRTC_VIDEO_CODEC_OK;
172
sprang3958ed82017-08-17 08:12:10 -0700173 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800174 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -0700175 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000176 }
sprang3958ed82017-08-17 08:12:10 -0700177 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100178 if (inited_) {
179 if (vpx_codec_destroy(encoder_)) {
180 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
181 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000182 }
183 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700184 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000185 }
sprang3958ed82017-08-17 08:12:10 -0700186 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000187 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700188 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000189 }
sprang3958ed82017-08-17 08:12:10 -0700190 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000191 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700192 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000193 }
194 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100195 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000196}
197
sprangce4aef12015-11-02 07:23:20 -0800198bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
199 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
200 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100201 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800202}
203
Erik Språng566124a2018-04-23 12:32:22 +0200204bool VP9EncoderImpl::SetSvcRates(
205 const VideoBitrateAllocation& bitrate_allocation) {
Sergey Silkin86684962018-03-28 19:32:37 +0200206 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200207
sprangce4aef12015-11-02 07:23:20 -0800208 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200209 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200210 const bool was_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200211 config_->ss_target_bitrate[sl_idx] =
212 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
213
214 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
215 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
216 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
217 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200218
219 const bool is_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
220 if (is_layer_enabled && !was_layer_enabled) {
221 if (inter_layer_pred_ == InterLayerPredMode::kOff ||
222 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic) {
223 // TODO(wemb:1526): remove key frame request when issue is fixed.
224 force_key_frame_ = true;
225 }
226 }
sprangce4aef12015-11-02 07:23:20 -0800227 }
228 } else {
229 float rate_ratio[VPX_MAX_LAYERS] = {0};
230 float total = 0;
Sergey Silkin908689d2018-08-20 09:28:45 +0200231 for (int i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800232 if (svc_params_.scaling_factor_num[i] <= 0 ||
233 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100234 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800235 return false;
236 }
Yves Gerey665174f2018-06-19 15:03:05 +0200237 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
238 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800239 total += rate_ratio[i];
240 }
241
Sergey Silkin908689d2018-08-20 09:28:45 +0200242 for (int i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200243 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800244 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
245 config_->rc_target_bitrate * rate_ratio[i] / total);
246 if (num_temporal_layers_ == 1) {
247 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
248 } else if (num_temporal_layers_ == 2) {
249 config_->layer_target_bitrate[i * num_temporal_layers_] =
250 config_->ss_target_bitrate[i] * 2 / 3;
251 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
252 config_->ss_target_bitrate[i];
253 } else if (num_temporal_layers_ == 3) {
254 config_->layer_target_bitrate[i * num_temporal_layers_] =
255 config_->ss_target_bitrate[i] / 2;
256 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
257 config_->layer_target_bitrate[i * num_temporal_layers_] +
258 (config_->ss_target_bitrate[i] / 4);
259 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
260 config_->ss_target_bitrate[i];
261 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100262 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
263 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800264 return false;
265 }
asaperssona9455ab2015-07-31 06:10:09 -0700266 }
267 }
Sergey Silkin908689d2018-08-20 09:28:45 +0200268
269 num_active_spatial_layers_ = 0;
270 for (int i = 0; i < num_spatial_layers_; ++i) {
271 if (config_->ss_target_bitrate[i] > 0) {
272 ++num_active_spatial_layers_;
273 }
274 }
275 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
276
asaperssona9455ab2015-07-31 06:10:09 -0700277 return true;
278}
279
Erik Språng08127a92016-11-16 16:41:30 +0100280int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200281 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100282 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000283 if (!inited_) {
284 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
285 }
286 if (encoder_->err) {
287 return WEBRTC_VIDEO_CODEC_ERROR;
288 }
Erik Språng08127a92016-11-16 16:41:30 +0100289 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000290 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
291 }
292 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100293 if (codec_.maxBitrate > 0 &&
294 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
295 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000296 }
Erik Språng08127a92016-11-16 16:41:30 +0100297
Erik Språng08127a92016-11-16 16:41:30 +0100298 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700299
Sergey Silkin86684962018-03-28 19:32:37 +0200300 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700301 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
302 }
303
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000304 // Update encoder context
305 if (vpx_codec_enc_config_set(encoder_, config_)) {
306 return WEBRTC_VIDEO_CODEC_ERROR;
307 }
308 return WEBRTC_VIDEO_CODEC_OK;
309}
310
311int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
312 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000313 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700314 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000315 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
316 }
317 if (inst->maxFramerate < 1) {
318 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
319 }
320 // Allow zero to represent an unspecified maxBitRate
321 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
322 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
323 }
324 if (inst->width < 1 || inst->height < 1) {
325 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
326 }
327 if (number_of_cores < 1) {
328 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
329 }
hta257dc392016-10-25 09:05:06 -0700330 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700331 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
332 }
ilnik2a8c2f52017-02-15 02:23:28 -0800333 // libvpx probably does not support more than 3 spatial layers.
334 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700335 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
336 }
philipelcfc319b2015-11-10 07:17:23 -0800337
asapersson86956de2016-01-26 01:05:20 -0800338 int ret_val = Release();
339 if (ret_val < 0) {
340 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000341 }
sprang3958ed82017-08-17 08:12:10 -0700342 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000343 encoder_ = new vpx_codec_ctx_t;
344 }
sprang3958ed82017-08-17 08:12:10 -0700345 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000346 config_ = new vpx_codec_enc_cfg_t;
347 }
348 timestamp_ = 0;
349 if (&codec_ != inst) {
350 codec_ = *inst;
351 }
asaperssona9455ab2015-07-31 06:10:09 -0700352
hta257dc392016-10-25 09:05:06 -0700353 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200354 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700355 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700356 if (num_temporal_layers_ == 0)
357 num_temporal_layers_ = 1;
358
Sergey Silkind902d582018-05-18 17:31:19 +0200359 // Init framerate controller.
Niels Möllere3cf3d02018-06-13 11:52:16 +0200360 if (codec_.mode == VideoCodecMode::kScreensharing) {
Sergey Silkinae3144c2018-08-29 01:05:26 +0200361 framerate_controller_.Reset();
362 framerate_controller_.SetTargetRate(kMaxScreenSharingFramerateFps);
Sergey Silkind902d582018-05-18 17:31:19 +0200363 }
364
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200365 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200366
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000367 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700368 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800369 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000370 }
nisseeb44b392017-04-28 07:18:05 -0700371 encoded_image_._size =
372 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000373 encoded_image_._buffer = new uint8_t[encoded_image_._size];
374 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000375 // Populate encoder configuration with default values.
376 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
377 return WEBRTC_VIDEO_CODEC_ERROR;
378 }
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700379
380 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
381 unsigned int bits_for_storage = 8;
382 switch (profile_) {
383 case VP9Profile::kProfile0:
384 img_fmt = VPX_IMG_FMT_I420;
385 bits_for_storage = 8;
386 config_->g_bit_depth = VPX_BITS_8;
387 config_->g_profile = 0;
388 config_->g_input_bit_depth = 8;
389 break;
390 case VP9Profile::kProfile2:
391 img_fmt = VPX_IMG_FMT_I42016;
392 bits_for_storage = 16;
393 config_->g_bit_depth = VPX_BITS_10;
394 config_->g_profile = 2;
395 config_->g_input_bit_depth = 10;
396 break;
397 }
398
399 // Creating a wrapper to the image - setting image data to nullptr. Actual
400 // pointer will be set in encode. Setting align to 1, as it is meaningless
401 // (actual memory is not allocated).
402 raw_ =
403 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
404 raw_->bit_depth = bits_for_storage;
405
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000406 config_->g_w = codec_.width;
407 config_->g_h = codec_.height;
408 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200409 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000410 // Setting the time base of the codec.
411 config_->g_timebase.num = 1;
412 config_->g_timebase.den = 90000;
413 config_->g_lag_in_frames = 0; // 0- no frame lagging
414 config_->g_threads = 1;
415 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700416 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000417 config_->rc_end_usage = VPX_CBR;
418 config_->g_pass = VPX_RC_ONE_PASS;
419 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000420 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000421 config_->rc_undershoot_pct = 50;
422 config_->rc_overshoot_pct = 50;
423 config_->rc_buf_initial_sz = 500;
424 config_->rc_buf_optimal_sz = 600;
425 config_->rc_buf_sz = 1000;
426 // Set the maximum target size of any key-frame.
427 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700428 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000429 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700430 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100431 // Needs to be set (in svc mode) to get correct periodic key frame interval
432 // (will have no effect in non-svc).
433 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000434 } else {
435 config_->kf_mode = VPX_KF_DISABLED;
436 }
hta257dc392016-10-25 09:05:06 -0700437 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000438 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800439 config_->g_threads =
440 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700441
Marco6e89b252015-07-07 14:40:38 -0700442 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700443
hta257dc392016-10-25 09:05:06 -0700444 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200445
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200446 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700447 gof_.SetGofInfoVP9(kTemporalStructureMode1);
448 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
449 config_->ts_number_layers = 1;
450 config_->ts_rate_decimator[0] = 1;
451 config_->ts_periodicity = 1;
452 config_->ts_layer_id[0] = 0;
453 } else if (num_temporal_layers_ == 2) {
454 gof_.SetGofInfoVP9(kTemporalStructureMode2);
455 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
456 config_->ts_number_layers = 2;
457 config_->ts_rate_decimator[0] = 2;
458 config_->ts_rate_decimator[1] = 1;
459 config_->ts_periodicity = 2;
460 config_->ts_layer_id[0] = 0;
461 config_->ts_layer_id[1] = 1;
462 } else if (num_temporal_layers_ == 3) {
463 gof_.SetGofInfoVP9(kTemporalStructureMode3);
464 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
465 config_->ts_number_layers = 3;
466 config_->ts_rate_decimator[0] = 4;
467 config_->ts_rate_decimator[1] = 2;
468 config_->ts_rate_decimator[2] = 1;
469 config_->ts_periodicity = 4;
470 config_->ts_layer_id[0] = 0;
471 config_->ts_layer_id[1] = 2;
472 config_->ts_layer_id[2] = 1;
473 config_->ts_layer_id[3] = 2;
474 } else {
475 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
476 }
477
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200478 inter_layer_pred_ = inst->VP9().interLayerPred;
479
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200480 ref_buf_.clear();
481
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000482 return InitAndSetControlSettings(inst);
483}
484
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000485int VP9EncoderImpl::NumberOfThreads(int width,
486 int height,
487 int number_of_cores) {
488 // Keep the number of encoder threads equal to the possible number of column
489 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
490 if (width * height >= 1280 * 720 && number_of_cores > 4) {
491 return 4;
jianj23173a32017-07-12 16:11:09 -0700492 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000493 return 2;
494 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200495// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800496#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
497 defined(WEBRTC_ANDROID)
498 if (width * height >= 320 * 180 && number_of_cores > 2) {
499 return 2;
500 }
501#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000502 // 1 thread less than VGA.
503 return 1;
504 }
505}
506
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000507int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100508 // Set QP-min/max per spatial and temporal layer.
509 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
510 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800511 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
512 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100513 }
asaperssona9455ab2015-07-31 06:10:09 -0700514 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800515 if (ExplicitlyConfiguredSpatialLayers()) {
516 for (int i = 0; i < num_spatial_layers_; ++i) {
517 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200518 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100519 const int scale_factor = codec_.width / layer.width;
520 RTC_DCHECK_GT(scale_factor, 0);
521
522 // Ensure scaler factor is integer.
523 if (scale_factor * layer.width != codec_.width) {
524 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
525 }
526
527 // Ensure scale factor is the same in both dimensions.
528 if (scale_factor * layer.height != codec_.height) {
529 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
530 }
531
532 // Ensure scale factor is power of two.
533 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
534 if (!is_pow_of_two) {
535 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
536 }
537
538 svc_params_.scaling_factor_num[i] = 1;
539 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800540 }
541 } else {
542 int scaling_factor_num = 256;
543 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800544 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800545 svc_params_.scaling_factor_num[i] = scaling_factor_num;
546 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800547 }
asaperssona9455ab2015-07-31 06:10:09 -0700548 }
549
Sergey Silkin86684962018-03-28 19:32:37 +0200550 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200551 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200552 inst->startBitrate * 1000, inst->maxFramerate);
553 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700554 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
555 }
556
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700557 const vpx_codec_err_t rv = vpx_codec_enc_init(
558 encoder_, vpx_codec_vp9_cx(), config_,
559 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
560 if (rv != VPX_CODEC_OK) {
561 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000562 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
563 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000564 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
565 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
566 rc_max_intra_target_);
567 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700568 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700569
jianj822e5932017-07-12 16:09:58 -0700570 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200571
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200572 if (is_svc_) {
573 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
574 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700575 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200576
577 if (num_spatial_layers_ > 1) {
578 switch (inter_layer_pred_) {
579 case InterLayerPredMode::kOn:
580 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
581 break;
582 case InterLayerPredMode::kOff:
583 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
584 break;
585 case InterLayerPredMode::kOnKeyPic:
586 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
587 break;
588 default:
589 RTC_NOTREACHED();
590 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200591
Sergey Silkinee203362018-05-30 11:34:08 +0200592 // Configure encoder to drop entire superframe whenever it needs to drop
593 // a layer. This mode is prefered over per-layer dropping which causes
594 // quality flickering and is not compatible with RTP non-flexible mode.
595 vpx_svc_frame_drop_t svc_drop_frame;
596 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
597 svc_drop_frame.framedrop_mode = FULL_SUPERFRAME_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200598 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200599 for (size_t i = 0; i < num_spatial_layers_; ++i) {
600 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200601 }
Sergey Silkinee203362018-05-30 11:34:08 +0200602 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200603 }
604
asaperssona9455ab2015-07-31 06:10:09 -0700605 // Register callback for getting each spatial layer.
606 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800607 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
608 reinterpret_cast<void*>(this)};
609 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
610 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700611
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000612 // Control function to set the number of column tiles in encoding a frame, in
613 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
614 // The number tile columns will be capped by the encoder based on image size
615 // (minimum width of tile column is 256 pixels, maximum is 4096).
616 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700617
618 // Turn on row-based multithreading.
619 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700620
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700621#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200622 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700623 // Do not enable the denoiser on ARM since optimization is pending.
624 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000625 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700626 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000627#endif
jianj6bf57e32017-06-05 13:43:49 -0700628
Niels Möllere3cf3d02018-06-13 11:52:16 +0200629 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700630 // Adjust internal parameters to screen content.
631 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700632 }
Marco2520e722015-09-16 14:05:00 -0700633 // Enable encoder skip of static/low content blocks.
634 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000635 inited_ = true;
636 return WEBRTC_VIDEO_CODEC_OK;
637}
638
639uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
640 // Set max to the optimal buffer level (normalized by target BR),
641 // and scaled by a scale_par.
642 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
643 // This value is presented in percentage of perFrameBw:
644 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
645 // The target in % is as follows:
646 float scale_par = 0.5;
647 uint32_t target_pct =
648 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
649 // Don't go below 3 times the per frame bandwidth.
650 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800651 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000652}
653
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700654int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000655 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700656 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000657 if (!inited_) {
658 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
659 }
sprang3958ed82017-08-17 08:12:10 -0700660 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000661 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
662 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200663
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000664 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200665 if (frame_types && !frame_types->empty()) {
666 if ((*frame_types)[0] == kVideoFrameKey) {
667 force_key_frame_ = true;
668 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000669 }
Sergey Silkind902d582018-05-18 17:31:19 +0200670
Niels Möllere3cf3d02018-06-13 11:52:16 +0200671 if (VideoCodecMode::kScreensharing == codec_.mode && !force_key_frame_) {
Sergey Silkinae3144c2018-08-29 01:05:26 +0200672 if (framerate_controller_.DropFrame(1000 * input_image.timestamp() /
673 kVideoPayloadTypeFrequency)) {
Sergey Silkind902d582018-05-18 17:31:19 +0200674 return WEBRTC_VIDEO_CODEC_OK;
675 }
676 }
677
kwiberg352444f2016-11-28 15:58:53 -0800678 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
679 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700680
681 // Set input image for use in the callback.
682 // This was necessary since you need some information from input_image.
683 // You can save only the necessary information (such as timestamp) instead of
684 // doing this.
685 input_image_ = &input_image;
686
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700687 // Keep reference to buffer until encode completes.
688 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
689 rtc::scoped_refptr<I010BufferInterface> i010_buffer;
690 switch (profile_) {
691 case VP9Profile::kProfile0: {
692 i420_buffer = input_image.video_frame_buffer()->ToI420();
693 // Image in vpx_image_t format.
694 // Input image is const. VPX's raw image is not defined as const.
695 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
696 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
697 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
698 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
699 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
700 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
701 break;
702 }
703 case VP9Profile::kProfile2: {
704 // We can inject kI010 frames directly for encode. All other formats
705 // should be converted to it.
706 switch (input_image.video_frame_buffer()->type()) {
707 case VideoFrameBuffer::Type::kI010: {
708 i010_buffer = input_image.video_frame_buffer()->GetI010();
709 break;
710 }
711 default: {
712 i010_buffer =
713 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
714 }
715 }
716 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
717 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
718 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
719 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
720 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
721 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
722 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
723 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
724 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
725 break;
726 }
727 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000728
philipelcfc319b2015-11-10 07:17:23 -0800729 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200730 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000731 flags = VPX_EFLAG_FORCE_KF;
732 }
philipelcfc319b2015-11-10 07:17:23 -0800733
sprang3958ed82017-08-17 08:12:10 -0700734 RTC_CHECK_GT(codec_.maxFramerate, 0);
Sergey Silkinae3144c2018-08-29 01:05:26 +0200735 uint32_t target_framerate_fps = codec_.mode == VideoCodecMode::kScreensharing
736 ? kMaxScreenSharingFramerateFps
737 : codec_.maxFramerate;
738 uint32_t duration = 90000 / target_framerate_fps;
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700739 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
740 duration, flags, VPX_DL_REALTIME);
741 if (rv != VPX_CODEC_OK) {
742 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
743 << "\n"
744 << "Details: " << vpx_codec_error(encoder_) << "\n"
745 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000746 return WEBRTC_VIDEO_CODEC_ERROR;
747 }
748 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700749
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200750 const bool end_of_picture = true;
751 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200752
asaperssona9455ab2015-07-31 06:10:09 -0700753 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000754}
755
756void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800757 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200758 uint32_t timestamp,
759 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700760 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000761 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700762 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800763 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200764
765 vp9_info->first_frame_in_picture = first_frame_in_picture;
Sergey Silkin738b7e92018-08-23 16:37:27 +0200766 vp9_info->flexible_mode = is_flexible_mode_;
hta257dc392016-10-25 09:05:06 -0700767 vp9_info->ss_data_available =
Sergey Silkin738b7e92018-08-23 16:37:27 +0200768 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
asaperssona9455ab2015-07-31 06:10:09 -0700769
770 vpx_svc_layer_id_t layer_id = {0};
771 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
772
sprang3958ed82017-08-17 08:12:10 -0700773 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -0500774 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700775 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700776 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700777 vp9_info->temporal_idx = kNoTemporalIdx;
778 } else {
779 vp9_info->temporal_idx = layer_id.temporal_layer_id;
780 }
“Michael23c5a992018-06-21 11:07:21 -0500781 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700782 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
Niels Moller5a998d72018-08-29 14:35:58 +0000783 vp9_info->spatial_idx = kNoSpatialIdx;
asaperssona9455ab2015-07-31 06:10:09 -0700784 } else {
Niels Moller5a998d72018-08-29 14:35:58 +0000785 vp9_info->spatial_idx = layer_id.spatial_layer_id;
asaperssona9455ab2015-07-31 06:10:09 -0700786 }
787 if (layer_id.spatial_layer_id != 0) {
788 vp9_info->ss_data_available = false;
789 }
790
asaperssona9455ab2015-07-31 06:10:09 -0700791 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800792 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700793
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200794 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
795 pics_since_key_ = 0;
796 } else if (first_frame_in_picture) {
797 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700798 }
799
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200800 const bool is_key_pic = (pics_since_key_ == 0);
801 const bool is_inter_layer_pred_allowed =
802 (inter_layer_pred_ == InterLayerPredMode::kOn ||
803 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
804
805 // Always set inter_layer_predicted to true on high layer frame if inter-layer
806 // prediction (ILP) is allowed even if encoder didn't actually use it.
807 // Setting inter_layer_predicted to false would allow receiver to decode high
808 // layer frame without decoding low layer frame. If that would happen (e.g.
809 // if low layer frame is lost) then receiver won't be able to decode next high
810 // layer frame which uses ILP.
811 vp9_info->inter_layer_predicted =
812 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
813
814 const bool is_last_layer =
“Michael23c5a992018-06-21 11:07:21 -0500815 (layer_id.spatial_layer_id + 1 == num_active_spatial_layers_);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200816 vp9_info->non_ref_for_inter_layer_pred =
817 is_last_layer ? true : !is_inter_layer_pred_allowed;
asapersson00ac85e2015-11-11 05:30:48 -0800818
ivica7f6a6fc2015-09-08 02:40:29 -0700819 // Always populate this, so that the packetizer can properly set the marker
820 // bit.
“Michael23c5a992018-06-21 11:07:21 -0500821 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800822
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200823 vp9_info->num_ref_pics = 0;
824 if (vp9_info->flexible_mode) {
825 vp9_info->gof_idx = kNoGofIdx;
826 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
827 vp9_info);
828 } else {
829 vp9_info->gof_idx =
830 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
831 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
832 vp9_info->num_ref_pics = gof_.num_ref_pics[vp9_info->gof_idx];
833 }
834
835 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
836
asaperssona9455ab2015-07-31 06:10:09 -0700837 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700838 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -0500839 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +0200840 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800841 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +0200842 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800843 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700844 }
Sergey Silkin738b7e92018-08-23 16:37:27 +0200845 if (vp9_info->flexible_mode) {
846 vp9_info->gof.num_frames_in_gof = 0;
847 } else {
asaperssona9455ab2015-07-31 06:10:09 -0700848 vp9_info->gof.CopyGofInfoVP9(gof_);
849 }
850 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000851}
852
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200853void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
854 const size_t pic_num,
855 const bool inter_layer_predicted,
856 CodecSpecificInfoVP9* vp9_info) {
857 vpx_svc_layer_id_t layer_id = {0};
858 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
859
Sergey Silkin76be2952018-08-21 12:30:33 +0200860 const bool is_key_frame =
861 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200862
863 std::vector<RefFrameBuffer> ref_buf_list;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200864
Sergey Silkin76be2952018-08-21 12:30:33 +0200865 if (is_svc_) {
866 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
867 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200868
Sergey Silkin76be2952018-08-21 12:30:33 +0200869 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
870 const size_t fb_idx =
871 enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
872 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +0200873 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
874 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
875 ref_buf_list.push_back(ref_buf_.at(fb_idx));
876 }
Sergey Silkin76be2952018-08-21 12:30:33 +0200877 }
878
879 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
880 const size_t fb_idx =
881 enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
882 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +0200883 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
884 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
885 ref_buf_list.push_back(ref_buf_.at(fb_idx));
886 }
Sergey Silkin76be2952018-08-21 12:30:33 +0200887 }
888
889 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
890 const size_t fb_idx =
891 enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
892 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
Sergey Silkin82276592018-08-27 14:54:20 +0200893 if (std::find(ref_buf_list.begin(), ref_buf_list.end(),
894 ref_buf_.at(fb_idx)) == ref_buf_list.end()) {
895 ref_buf_list.push_back(ref_buf_.at(fb_idx));
896 }
Sergey Silkin76be2952018-08-21 12:30:33 +0200897 }
898 } else if (!is_key_frame) {
899 RTC_DCHECK_EQ(num_spatial_layers_, 1);
900 RTC_DCHECK_EQ(num_temporal_layers_, 1);
901 // In non-SVC mode encoder doesn't provide reference list. Assume each frame
902 // refers previous one, which is stored in buffer 0.
903 ref_buf_list.push_back(ref_buf_.at(0));
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200904 }
905
906 size_t max_ref_temporal_layer_id = 0;
907
908 vp9_info->num_ref_pics = 0;
909 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
910 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
911 if (ref_buf.pic_num < pic_num) {
912 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
913 // RTP spec limits temporal prediction to the same spatial layer.
914 // It is safe to ignore this requirement if inter-layer prediction is
915 // enabled for all frames when all base frames are relayed to receiver.
916 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
917 }
918 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
919
920 const size_t p_diff = pic_num - ref_buf.pic_num;
921 RTC_DCHECK_LE(p_diff, 127UL);
922
923 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
924 ++vp9_info->num_ref_pics;
925
926 max_ref_temporal_layer_id =
927 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
928 } else {
929 RTC_DCHECK(inter_layer_predicted);
930 // RTP spec only allows to use previous spatial layer for inter-layer
931 // prediction.
932 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
933 }
934 }
935
936 vp9_info->temporal_up_switch =
937 (max_ref_temporal_layer_id <
938 static_cast<size_t>(layer_id.temporal_layer_id));
939}
940
941void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
942 const size_t pic_num) {
943 vpx_svc_layer_id_t layer_id = {0};
944 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
945
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200946 const bool is_key_frame =
947 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
948
949 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
950 layer_id.temporal_layer_id);
951
952 if (is_key_frame && layer_id.spatial_layer_id == 0) {
953 // Key frame updates all ref buffers.
954 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
955 ref_buf_[i] = frame_buf;
956 }
Sergey Silkin76be2952018-08-21 12:30:33 +0200957 } else if (is_svc_) {
958 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
959 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
960
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200961 if (enc_layer_conf.update_last[layer_id.spatial_layer_id]) {
962 ref_buf_[enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id]] =
963 frame_buf;
964 }
965
966 if (enc_layer_conf.update_alt_ref[layer_id.spatial_layer_id]) {
967 ref_buf_[enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id]] =
968 frame_buf;
969 }
970
971 if (enc_layer_conf.update_golden[layer_id.spatial_layer_id]) {
972 ref_buf_[enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id]] =
973 frame_buf;
974 }
Sergey Silkin76be2952018-08-21 12:30:33 +0200975 } else {
976 RTC_DCHECK_EQ(num_spatial_layers_, 1);
977 RTC_DCHECK_EQ(num_temporal_layers_, 1);
978 // In non-svc mode encoder doesn't provide reference list. Assume each frame
979 // is reference and stored in buffer 0.
980 ref_buf_[0] = frame_buf;
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200981 }
982}
983
asaperssona9455ab2015-07-31 06:10:09 -0700984int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800985 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700986
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200987 if (pkt->data.frame.sz == 0) {
988 // Ignore dropped frame.
989 return WEBRTC_VIDEO_CODEC_OK;
990 }
991
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200992 vpx_svc_layer_id_t layer_id = {0};
993 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
994
995 const bool first_frame_in_picture = encoded_image_._length == 0;
996 // Ensure we don't buffer layers of previous picture (superframe).
997 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
998
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200999 const bool end_of_picture = false;
1000 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001001
asaperssond9f641e2016-01-21 01:11:35 -08001002 if (pkt->data.frame.sz > encoded_image_._size) {
1003 delete[] encoded_image_._buffer;
1004 encoded_image_._size = pkt->data.frame.sz;
1005 encoded_image_._buffer = new uint8_t[encoded_image_._size];
1006 }
asapersson86956de2016-01-26 01:05:20 -08001007 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
1008 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -08001009
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001010 const bool is_key_frame =
1011 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
1012 // Ensure encoder issued key frame on request.
1013 RTC_DCHECK(is_key_frame || !force_key_frame_);
1014
asaperssona9455ab2015-07-31 06:10:09 -07001015 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -08001016 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001017 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +02001018 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +02001019 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001020 }
asapersson86956de2016-01-26 01:05:20 -08001021 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
1022
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001023 memset(&codec_specific_, 0, sizeof(codec_specific_));
Niels Moller5a998d72018-08-29 14:35:58 +00001024 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
1025 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -07001026
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001027 if (is_flexible_mode_) {
1028 UpdateReferenceBuffers(*pkt, pics_since_key_);
1029 }
1030
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001031 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
Niels Möller23775882018-08-16 10:24:12 +02001032 encoded_image_.SetTimestamp(input_image_->timestamp());
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001033 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
1034 encoded_image_.rotation_ = input_image_->rotation();
Niels Möllere3cf3d02018-06-13 11:52:16 +02001035 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001036 ? VideoContentType::SCREENSHARE
1037 : VideoContentType::UNSPECIFIED;
1038 encoded_image_._encodedHeight =
1039 pkt->data.frame.height[layer_id.spatial_layer_id];
1040 encoded_image_._encodedWidth =
1041 pkt->data.frame.width[layer_id.spatial_layer_id];
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +02001042 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001043 int qp = -1;
1044 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
1045 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -07001046
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001047 return WEBRTC_VIDEO_CODEC_OK;
1048}
1049
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001050void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001051 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001052 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001053
1054 // No data partitioning in VP9, so 1 partition only.
1055 int part_idx = 0;
1056 RTPFragmentationHeader frag_info;
1057 frag_info.VerifyAndAllocateFragmentationHeader(1);
1058 frag_info.fragmentationOffset[part_idx] = 0;
1059 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
1060 frag_info.fragmentationPlType[part_idx] = 0;
1061 frag_info.fragmentationTimeDiff[part_idx] = 0;
1062
1063 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
1064 &frag_info);
1065 encoded_image_._length = 0;
Sergey Silkind902d582018-05-18 17:31:19 +02001066
Sergey Silkinae3144c2018-08-29 01:05:26 +02001067 if (end_of_picture && codec_.mode == VideoCodecMode::kScreensharing) {
Sergey Silkind902d582018-05-18 17:31:19 +02001068 const uint32_t timestamp_ms =
Niels Möller23775882018-08-16 10:24:12 +02001069 1000 * encoded_image_.Timestamp() / kVideoPayloadTypeFrequency;
Sergey Silkinae3144c2018-08-29 01:05:26 +02001070 framerate_controller_.AddFrame(timestamp_ms);
Sergey Silkind902d582018-05-18 17:31:19 +02001071 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001072 }
1073}
1074
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001075int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001076 return WEBRTC_VIDEO_CODEC_OK;
1077}
1078
1079int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1080 EncodedImageCallback* callback) {
1081 encoded_complete_callback_ = callback;
1082 return WEBRTC_VIDEO_CODEC_OK;
1083}
1084
Peter Boströmb7d9a972015-12-18 16:01:11 +01001085const char* VP9EncoderImpl::ImplementationName() const {
1086 return "libvpx";
1087}
1088
Magnus Jedvert46a27652017-11-13 14:10:02 +01001089std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001090 return absl::make_unique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001091}
1092
1093VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001094 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001095 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001096 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001097 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001098
1099VP9DecoderImpl::~VP9DecoderImpl() {
1100 inited_ = true; // in order to do the actual release
1101 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001102 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1103 if (num_buffers_in_use > 0) {
1104 // The frame buffers are reference counted and frames are exposed after
1105 // decoding. There may be valid usage cases where previous frames are still
1106 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001107 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1108 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001109 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001110}
1111
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001112int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001113 int ret_val = Release();
1114 if (ret_val < 0) {
1115 return ret_val;
1116 }
sprang3958ed82017-08-17 08:12:10 -07001117 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001118 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001119 }
philipelcce46fc2015-12-21 03:04:49 -08001120 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001121 // Setting number of threads to a constant value (1)
1122 cfg.threads = 1;
1123 cfg.h = cfg.w = 0; // set after decode
1124 vpx_codec_flags_t flags = 0;
1125 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1126 return WEBRTC_VIDEO_CODEC_MEMORY;
1127 }
Henrik Boström9695d852015-05-06 10:42:15 +02001128
1129 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1130 return WEBRTC_VIDEO_CODEC_MEMORY;
1131 }
1132
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001133 inited_ = true;
1134 // Always start with a complete key frame.
1135 key_frame_required_ = true;
1136 return WEBRTC_VIDEO_CODEC_OK;
1137}
1138
1139int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1140 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001141 const CodecSpecificInfo* codec_specific_info,
1142 int64_t /*render_time_ms*/) {
1143 if (!inited_) {
1144 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1145 }
sprang3958ed82017-08-17 08:12:10 -07001146 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001147 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1148 }
1149 // Always start with a complete key frame.
1150 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +02001151 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001152 return WEBRTC_VIDEO_CODEC_ERROR;
1153 // We have a key frame - is it complete?
1154 if (input_image._completeFrame) {
1155 key_frame_required_ = false;
1156 } else {
1157 return WEBRTC_VIDEO_CODEC_ERROR;
1158 }
1159 }
sprang3958ed82017-08-17 08:12:10 -07001160 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001161 vpx_image_t* img;
1162 uint8_t* buffer = input_image._buffer;
1163 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -07001164 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001165 }
Henrik Boström9695d852015-05-06 10:42:15 +02001166 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1167 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001168 if (vpx_codec_decode(decoder_, buffer,
1169 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001170 VPX_DL_REALTIME)) {
1171 return WEBRTC_VIDEO_CODEC_ERROR;
1172 }
Henrik Boström9695d852015-05-06 10:42:15 +02001173 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1174 // It may be released by libvpx during future vpx_codec_decode or
1175 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001176 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001177 int qp;
1178 vpx_codec_err_t vpx_ret =
1179 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1180 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
1181 int ret =
Niels Möller23775882018-08-16 10:24:12 +02001182 ReturnFrame(img, input_image.Timestamp(), input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001183 if (ret != 0) {
1184 return ret;
1185 }
1186 return WEBRTC_VIDEO_CODEC_OK;
1187}
1188
asapersson1490f7a2016-09-23 02:09:46 -07001189int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
1190 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -08001191 int64_t ntp_time_ms,
1192 int qp) {
sprang3958ed82017-08-17 08:12:10 -07001193 if (img == nullptr) {
1194 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001195 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1196 }
Henrik Boström9695d852015-05-06 10:42:15 +02001197
1198 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001199 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001200 // vpx_codec_decode calls or vpx_codec_destroy).
1201 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1202 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001203
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001204 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001205 // using a Wrapped*Buffer.
1206 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1207 switch (img->bit_depth) {
1208 case 8:
1209 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001210 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1211 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1212 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1213 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001214 // WrappedI420Buffer's mechanism for allowing the release of its frame
1215 // buffer is through a callback function. This is where we should
1216 // release |img_buffer|.
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001217 rtc::KeepRefUntilDone(img_buffer));
1218 break;
1219 case 10:
1220 img_wrapped_buffer = WrapI010Buffer(
1221 img->d_w, img->d_h,
1222 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1223 img->stride[VPX_PLANE_Y] / 2,
1224 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1225 img->stride[VPX_PLANE_U] / 2,
1226 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1227 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1228 break;
1229 default:
1230 RTC_NOTREACHED();
1231 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1232 }
nisseca6d5d12016-06-17 05:03:04 -07001233
Emircan Uysaler715cc232018-07-23 17:50:43 -07001234 VideoFrame decoded_image = VideoFrame::Builder()
1235 .set_video_frame_buffer(img_wrapped_buffer)
1236 .set_timestamp_ms(0)
1237 .set_timestamp_rtp(timestamp)
1238 .set_ntp_time_ms(ntp_time_ms)
1239 .set_rotation(webrtc::kVideoRotation_0)
1240 .set_color_space(ExtractVP9ColorSpace(
1241 img->cs, img->range, img->bit_depth))
1242 .build();
Danil Chapovalov0040b662018-06-18 10:48:16 +02001243 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001244 return WEBRTC_VIDEO_CODEC_OK;
1245}
1246
1247int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1248 DecodedImageCallback* callback) {
1249 decode_complete_callback_ = callback;
1250 return WEBRTC_VIDEO_CODEC_OK;
1251}
1252
1253int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001254 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1255
sprang3958ed82017-08-17 08:12:10 -07001256 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001257 if (inited_) {
1258 // When a codec is destroyed libvpx will release any buffers of
1259 // |frame_buffer_pool_| it is currently using.
1260 if (vpx_codec_destroy(decoder_)) {
1261 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1262 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001263 }
1264 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001265 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001266 }
Henrik Boström9695d852015-05-06 10:42:15 +02001267 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1268 // still referenced externally are deleted once fully released, not returning
1269 // to the pool.
1270 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001271 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001272 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001273}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001274
1275const char* VP9DecoderImpl::ImplementationName() const {
1276 return "libvpx";
1277}
1278
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001279} // namespace webrtc