blob: 01ca56410336d4e9867cd5a5fdd051aa48b50778 [file] [log] [blame]
pbos@webrtc.org9115cde2014-12-09 10:36:40 +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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "media/engine/simulcast_encoder_adapter.h"
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000012
Yves Gerey3e707812018-11-28 16:47:49 +010013#include <stdio.h>
14#include <string.h>
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000015#include <algorithm>
Yves Gerey3e707812018-11-28 16:47:49 +010016#include <cstdint>
Ilya Nikolaevskiyc30a1312018-08-27 11:07:48 +020017#include <string>
18#include <utility>
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000019
Mirko Bonadeid9708072019-01-25 20:26:48 +010020#include "api/scoped_refptr.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/video/i420_buffer.h"
Erik Språngf93eda12019-01-16 17:10:57 +010022#include "api/video/video_codec_constants.h"
Yves Gerey3e707812018-11-28 16:47:49 +010023#include "api/video/video_frame_buffer.h"
24#include "api/video/video_rotation.h"
Elad Alon11dfff02019-06-10 19:10:29 +020025#include "api/video_codecs/video_encoder.h"
Magnus Jedvertdf4883d2017-11-17 14:44:55 +010026#include "api/video_codecs/video_encoder_factory.h"
Yves Gerey3e707812018-11-28 16:47:49 +010027#include "modules/video_coding/include/video_error_codes.h"
Sergio Garcia Murillo43800f92018-06-21 16:16:38 +020028#include "modules/video_coding/utility/simulcast_rate_allocator.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/checks.h"
Erik Språng7f24fb92019-02-13 10:49:37 +010031#include "rtc_base/experiments/rate_control_settings.h"
Erik Språng16cb8f52019-04-12 13:59:09 +020032#include "rtc_base/logging.h"
Ilya Nikolaevskiyc30a1312018-08-27 11:07:48 +020033#include "system_wrappers/include/field_trial.h"
Mirko Bonadei65432062017-12-11 09:32:13 +010034#include "third_party/libyuv/include/libyuv/scale.h"
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000035
36namespace {
37
38const unsigned int kDefaultMinQp = 2;
39const unsigned int kDefaultMaxQp = 56;
40// Max qp for lowest spatial resolution when doing simulcast.
41const unsigned int kLowestResMaxQp = 45;
42
Ilya Nikolaevskiyc30a1312018-08-27 11:07:48 +020043absl::optional<unsigned int> GetScreenshareBoostedQpValue() {
44 std::string experiment_group =
45 webrtc::field_trial::FindFullName("WebRTC-BoostedScreenshareQp");
46 unsigned int qp;
47 if (sscanf(experiment_group.c_str(), "%u", &qp) != 1)
48 return absl::nullopt;
49 qp = std::min(qp, 63u);
50 qp = std::max(qp, 1u);
51 return qp;
52}
53
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000054uint32_t SumStreamMaxBitrate(int streams, const webrtc::VideoCodec& codec) {
55 uint32_t bitrate_sum = 0;
56 for (int i = 0; i < streams; ++i) {
57 bitrate_sum += codec.simulcastStream[i].maxBitrate;
58 }
59 return bitrate_sum;
60}
61
62int NumberOfStreams(const webrtc::VideoCodec& codec) {
63 int streams =
64 codec.numberOfSimulcastStreams < 1 ? 1 : codec.numberOfSimulcastStreams;
65 uint32_t simulcast_max_bitrate = SumStreamMaxBitrate(streams, codec);
66 if (simulcast_max_bitrate == 0) {
67 streams = 1;
68 }
69 return streams;
70}
71
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000072int VerifyCodec(const webrtc::VideoCodec* inst) {
brandtr5e171752017-05-23 03:32:16 -070073 if (inst == nullptr) {
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000074 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
75 }
76 if (inst->maxFramerate < 1) {
77 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
78 }
79 // allow zero to represent an unspecified maxBitRate
80 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
81 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
82 }
83 if (inst->width <= 1 || inst->height <= 1) {
84 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
85 }
Sergio Garcia Murillo43800f92018-06-21 16:16:38 +020086 if (inst->codecType == webrtc::kVideoCodecVP8 &&
87 inst->VP8().automaticResizeOn && inst->numberOfSimulcastStreams > 1) {
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000088 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
89 }
90 return WEBRTC_VIDEO_CODEC_OK;
91}
92
Florent Castelli1b761ca2019-01-21 14:33:02 +010093bool StreamResolutionCompare(const webrtc::SimulcastStream& a,
94 const webrtc::SimulcastStream& b) {
95 return std::tie(a.height, a.width, a.maxBitrate, a.maxFramerate) <
96 std::tie(b.height, b.width, b.maxBitrate, b.maxFramerate);
97}
98
Noah Richards41ee1ea2015-04-15 09:24:26 -070099// An EncodedImageCallback implementation that forwards on calls to a
100// SimulcastEncoderAdapter, but with the stream index it's registered with as
101// the first parameter to Encoded.
102class AdapterEncodedImageCallback : public webrtc::EncodedImageCallback {
103 public:
104 AdapterEncodedImageCallback(webrtc::SimulcastEncoderAdapter* adapter,
105 size_t stream_idx)
106 : adapter_(adapter), stream_idx_(stream_idx) {}
107
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700108 EncodedImageCallback::Result OnEncodedImage(
109 const webrtc::EncodedImage& encoded_image,
110 const webrtc::CodecSpecificInfo* codec_specific_info,
111 const webrtc::RTPFragmentationHeader* fragmentation) override {
112 return adapter_->OnEncodedImage(stream_idx_, encoded_image,
113 codec_specific_info, fragmentation);
Noah Richards41ee1ea2015-04-15 09:24:26 -0700114 }
115
116 private:
117 webrtc::SimulcastEncoderAdapter* const adapter_;
118 const size_t stream_idx_;
119};
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000120} // namespace
121
122namespace webrtc {
123
Ilya Nikolaevskiy97b4ee52018-05-28 10:24:22 +0200124SimulcastEncoderAdapter::SimulcastEncoderAdapter(VideoEncoderFactory* factory,
125 const SdpVideoFormat& format)
Magnus Jedvertdf4883d2017-11-17 14:44:55 +0100126 : inited_(0),
127 factory_(factory),
Ilya Nikolaevskiy97b4ee52018-05-28 10:24:22 +0200128 video_format_(format),
Magnus Jedvertdf4883d2017-11-17 14:44:55 +0100129 encoded_complete_callback_(nullptr),
Erik Språng7f24fb92019-02-13 10:49:37 +0100130 experimental_boosted_screenshare_qp_(GetScreenshareBoostedQpValue()),
131 boost_base_layer_quality_(RateControlSettings::ParseFromFieldTrials()
132 .Vp8BoostBaseLayerQuality()) {
Rasmus Brandtc334ce92018-02-05 13:03:25 +0100133 RTC_DCHECK(factory_);
Erik Språng75de46a2018-11-07 14:53:32 +0100134 encoder_info_.implementation_name = "SimulcastEncoderAdapter";
Magnus Jedvertdf4883d2017-11-17 14:44:55 +0100135
brandtr5e171752017-05-23 03:32:16 -0700136 // The adapter is typically created on the worker thread, but operated on
137 // the encoder task queue.
138 encoder_queue_.Detach();
139
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000140 memset(&codec_, 0, sizeof(webrtc::VideoCodec));
141}
142
143SimulcastEncoderAdapter::~SimulcastEncoderAdapter() {
brandtr5e171752017-05-23 03:32:16 -0700144 RTC_DCHECK(!Initialized());
145 DestroyStoredEncoders();
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000146}
147
148int SimulcastEncoderAdapter::Release() {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200149 RTC_DCHECK_RUN_ON(&encoder_queue_);
brandtr5e171752017-05-23 03:32:16 -0700150
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000151 while (!streaminfos_.empty()) {
magjed3f897582017-08-28 08:05:42 -0700152 std::unique_ptr<VideoEncoder> encoder =
153 std::move(streaminfos_.back().encoder);
brandtr5e171752017-05-23 03:32:16 -0700154 // Even though it seems very unlikely, there are no guarantees that the
Rasmus Brandt9cf9f752017-09-28 13:02:58 +0200155 // encoder will not call back after being Release()'d. Therefore, we first
156 // disable the callbacks here.
brandtr5e171752017-05-23 03:32:16 -0700157 encoder->RegisterEncodeCompleteCallback(nullptr);
Rasmus Brandt9cf9f752017-09-28 13:02:58 +0200158 encoder->Release();
brandtr5e171752017-05-23 03:32:16 -0700159 streaminfos_.pop_back(); // Deletes callback adapter.
magjed3f897582017-08-28 08:05:42 -0700160 stored_encoders_.push(std::move(encoder));
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000161 }
brandtr5e171752017-05-23 03:32:16 -0700162
163 // It's legal to move the encoder to another queue now.
164 encoder_queue_.Detach();
165
166 rtc::AtomicOps::ReleaseStore(&inited_, 0);
167
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000168 return WEBRTC_VIDEO_CODEC_OK;
169}
170
171int SimulcastEncoderAdapter::InitEncode(const VideoCodec* inst,
172 int number_of_cores,
173 size_t max_payload_size) {
Elad Alon11dfff02019-06-10 19:10:29 +0200174 RTC_NOTREACHED();
175 return WEBRTC_VIDEO_CODEC_ERROR;
176}
177
178// TODO(eladalon): s/inst/codec_settings/g.
179int SimulcastEncoderAdapter::InitEncode(
180 const VideoCodec* inst,
181 const VideoEncoder::Settings& settings) {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200182 RTC_DCHECK_RUN_ON(&encoder_queue_);
brandtr5e171752017-05-23 03:32:16 -0700183
Elad Alon11dfff02019-06-10 19:10:29 +0200184 if (settings.number_of_cores < 1) {
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000185 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
186 }
187
188 int ret = VerifyCodec(inst);
189 if (ret < 0) {
190 return ret;
191 }
192
193 ret = Release();
194 if (ret < 0) {
195 return ret;
196 }
197
198 int number_of_streams = NumberOfStreams(*inst);
brandtr5e171752017-05-23 03:32:16 -0700199 RTC_DCHECK_LE(number_of_streams, kMaxSimulcastStreams);
Peter Boströmd53c3892016-03-30 17:03:52 +0200200 const bool doing_simulcast = (number_of_streams > 1);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000201
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000202 codec_ = *inst;
Erik Språng82fad3d2018-03-21 09:57:23 +0100203 SimulcastRateAllocator rate_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200204 VideoBitrateAllocation allocation = rate_allocator.GetAllocation(
Erik Språng08127a92016-11-16 16:41:30 +0100205 codec_.startBitrate * 1000, codec_.maxFramerate);
206 std::vector<uint32_t> start_bitrates;
207 for (int i = 0; i < kMaxSimulcastStreams; ++i) {
208 uint32_t stream_bitrate = allocation.GetSpatialLayerSum(i) / 1000;
209 start_bitrates.push_back(stream_bitrate);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000210 }
211
Erik Språng75de46a2018-11-07 14:53:32 +0100212 encoder_info_.supports_native_handle = true;
213 encoder_info_.scaling_settings.thresholds = absl::nullopt;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000214 // Create |number_of_streams| of encoder instances and init them.
Florent Castelli1b761ca2019-01-21 14:33:02 +0100215
216 const auto minmax = std::minmax_element(
217 std::begin(codec_.simulcastStream),
218 std::begin(codec_.simulcastStream) + number_of_streams,
219 StreamResolutionCompare);
220 const auto lowest_resolution_stream_index =
221 std::distance(std::begin(codec_.simulcastStream), minmax.first);
222 const auto highest_resolution_stream_index =
223 std::distance(std::begin(codec_.simulcastStream), minmax.second);
224
225 RTC_DCHECK_LT(lowest_resolution_stream_index, number_of_streams);
226 RTC_DCHECK_LT(highest_resolution_stream_index, number_of_streams);
227
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000228 for (int i = 0; i < number_of_streams; ++i) {
229 VideoCodec stream_codec;
Erik Språng78ce6192016-09-12 16:04:43 +0200230 uint32_t start_bitrate_kbps = start_bitrates[i];
Erik Språng7d687b12018-09-12 17:04:10 +0200231 const bool send_stream = start_bitrate_kbps > 0;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000232 if (!doing_simulcast) {
233 stream_codec = codec_;
234 stream_codec.numberOfSimulcastStreams = 1;
Erik Språng75de46a2018-11-07 14:53:32 +0100235
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000236 } else {
Erik Språng78ce6192016-09-12 16:04:43 +0200237 // Cap start bitrate to the min bitrate in order to avoid strange codec
Erik Språng7d687b12018-09-12 17:04:10 +0200238 // behavior. Since sending will be false, this should not matter.
Florent Castelli1b761ca2019-01-21 14:33:02 +0100239 StreamResolution stream_resolution =
240 i == highest_resolution_stream_index
241 ? StreamResolution::HIGHEST
242 : i == lowest_resolution_stream_index ? StreamResolution::LOWEST
243 : StreamResolution::OTHER;
244
Erik Språng78ce6192016-09-12 16:04:43 +0200245 start_bitrate_kbps =
246 std::max(codec_.simulcastStream[i].minBitrate, start_bitrate_kbps);
Florent Castelli1b761ca2019-01-21 14:33:02 +0100247 PopulateStreamCodec(codec_, i, start_bitrate_kbps, stream_resolution,
248 &stream_codec);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000249 }
250
Erik Språngcc681cc2018-03-14 17:52:55 +0100251 // TODO(ronghuawu): Remove once this is handled in LibvpxVp8Encoder.
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000252 if (stream_codec.qpMax < kDefaultMinQp) {
253 stream_codec.qpMax = kDefaultMaxQp;
254 }
255
brandtr5e171752017-05-23 03:32:16 -0700256 // If an existing encoder instance exists, reuse it.
257 // TODO(brandtr): Set initial RTP state (e.g., picture_id/tl0_pic_idx) here,
258 // when we start storing that state outside the encoder wrappers.
magjed3f897582017-08-28 08:05:42 -0700259 std::unique_ptr<VideoEncoder> encoder;
brandtr5e171752017-05-23 03:32:16 -0700260 if (!stored_encoders_.empty()) {
magjed3f897582017-08-28 08:05:42 -0700261 encoder = std::move(stored_encoders_.top());
brandtr5e171752017-05-23 03:32:16 -0700262 stored_encoders_.pop();
263 } else {
Sergio Garcia Murillo43800f92018-06-21 16:16:38 +0200264 encoder = factory_->CreateVideoEncoder(SdpVideoFormat(
265 codec_.codecType == webrtc::kVideoCodecVP8 ? "VP8" : "H264"));
brandtr5e171752017-05-23 03:32:16 -0700266 }
267
Elad Alon11dfff02019-06-10 19:10:29 +0200268 ret = encoder->InitEncode(&stream_codec, settings);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000269 if (ret < 0) {
noahrice5ba75a2016-12-12 13:08:27 -0800270 // Explicitly destroy the current encoder; because we haven't registered a
271 // StreamInfo for it yet, Release won't do anything about it.
magjed3f897582017-08-28 08:05:42 -0700272 encoder.reset();
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000273 Release();
274 return ret;
275 }
Erik Språngd3438aa2018-11-08 16:56:43 +0100276
brandtr5e171752017-05-23 03:32:16 -0700277 std::unique_ptr<EncodedImageCallback> callback(
278 new AdapterEncodedImageCallback(this, i));
279 encoder->RegisterEncodeCompleteCallback(callback.get());
magjed3f897582017-08-28 08:05:42 -0700280 streaminfos_.emplace_back(std::move(encoder), std::move(callback),
281 stream_codec.width, stream_codec.height,
Erik Språng7d687b12018-09-12 17:04:10 +0200282 send_stream);
brandtr5e171752017-05-23 03:32:16 -0700283
Erik Språng75de46a2018-11-07 14:53:32 +0100284 if (!doing_simulcast) {
285 // Without simulcast, just pass through the encoder info from the one
286 // active encoder.
287 encoder_info_ = streaminfos_[0].encoder->GetEncoderInfo();
288 } else {
289 const EncoderInfo encoder_impl_info =
290 streaminfos_[i].encoder->GetEncoderInfo();
291
292 if (i == 0) {
293 // Quality scaling not enabled for simulcast.
294 encoder_info_.scaling_settings = VideoEncoder::ScalingSettings::kOff;
295
296 // Encoder name indicates names of all sub-encoders.
297 encoder_info_.implementation_name = "SimulcastEncoderAdapter (";
298 encoder_info_.implementation_name +=
299 encoder_impl_info.implementation_name;
300
301 encoder_info_.supports_native_handle =
302 encoder_impl_info.supports_native_handle;
Erik Språngd3438aa2018-11-08 16:56:43 +0100303 encoder_info_.has_trusted_rate_controller =
304 encoder_impl_info.has_trusted_rate_controller;
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100305 encoder_info_.is_hardware_accelerated =
306 encoder_impl_info.is_hardware_accelerated;
307 encoder_info_.has_internal_source =
308 encoder_impl_info.has_internal_source;
Erik Språng75de46a2018-11-07 14:53:32 +0100309 } else {
310 encoder_info_.implementation_name += ", ";
311 encoder_info_.implementation_name +=
312 encoder_impl_info.implementation_name;
313
314 // Native handle supported only if all encoders supports it.
315 encoder_info_.supports_native_handle &=
316 encoder_impl_info.supports_native_handle;
Erik Språngd3438aa2018-11-08 16:56:43 +0100317
318 // Trusted rate controller only if all encoders have it.
319 encoder_info_.has_trusted_rate_controller &=
320 encoder_impl_info.has_trusted_rate_controller;
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100321
322 // Uses hardware support if any of the encoders uses it.
323 // For example, if we are having issues with down-scaling due to
324 // pipelining delay in HW encoders we need higher encoder usage
325 // thresholds in CPU adaptation.
326 encoder_info_.is_hardware_accelerated |=
327 encoder_impl_info.is_hardware_accelerated;
328
329 // Has internal source only if all encoders have it.
330 encoder_info_.has_internal_source &=
331 encoder_impl_info.has_internal_source;
Erik Språng75de46a2018-11-07 14:53:32 +0100332 }
Erik Språngdbdd8392019-01-17 15:27:50 +0100333 encoder_info_.fps_allocation[i] = encoder_impl_info.fps_allocation[0];
brandtr5e171752017-05-23 03:32:16 -0700334 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000335 }
brandtr5e171752017-05-23 03:32:16 -0700336
Peter Boströmd53c3892016-03-30 17:03:52 +0200337 if (doing_simulcast) {
Erik Språng75de46a2018-11-07 14:53:32 +0100338 encoder_info_.implementation_name += ")";
Peter Boströmd53c3892016-03-30 17:03:52 +0200339 }
brandtr5e171752017-05-23 03:32:16 -0700340
341 // To save memory, don't store encoders that we don't use.
342 DestroyStoredEncoders();
343
344 rtc::AtomicOps::ReleaseStore(&inited_, 1);
345
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000346 return WEBRTC_VIDEO_CODEC_OK;
347}
348
349int SimulcastEncoderAdapter::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700350 const VideoFrame& input_image,
Niels Möller87e2d782019-03-07 10:18:23 +0100351 const std::vector<VideoFrameType>* frame_types) {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200352 RTC_DCHECK_RUN_ON(&encoder_queue_);
brandtr5e171752017-05-23 03:32:16 -0700353
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000354 if (!Initialized()) {
355 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
356 }
brandtr5e171752017-05-23 03:32:16 -0700357 if (encoded_complete_callback_ == nullptr) {
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000358 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
359 }
360
361 // All active streams should generate a key frame if
362 // a key frame is requested by any stream.
363 bool send_key_frame = false;
364 if (frame_types) {
365 for (size_t i = 0; i < frame_types->size(); ++i) {
Niels Möller8f7ce222019-03-21 15:43:58 +0100366 if (frame_types->at(i) == VideoFrameType::kVideoFrameKey) {
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000367 send_key_frame = true;
368 break;
369 }
370 }
371 }
372 for (size_t stream_idx = 0; stream_idx < streaminfos_.size(); ++stream_idx) {
373 if (streaminfos_[stream_idx].key_frame_request &&
374 streaminfos_[stream_idx].send_stream) {
375 send_key_frame = true;
376 break;
377 }
378 }
379
380 int src_width = input_image.width();
381 int src_height = input_image.height();
382 for (size_t stream_idx = 0; stream_idx < streaminfos_.size(); ++stream_idx) {
Peter Boström5d0379d2015-10-06 14:04:51 +0200383 // Don't encode frames in resolutions that we don't intend to send.
brandtr5e171752017-05-23 03:32:16 -0700384 if (!streaminfos_[stream_idx].send_stream) {
Peter Boström5d0379d2015-10-06 14:04:51 +0200385 continue;
brandtr5e171752017-05-23 03:32:16 -0700386 }
Peter Boström5d0379d2015-10-06 14:04:51 +0200387
Niels Möller87e2d782019-03-07 10:18:23 +0100388 std::vector<VideoFrameType> stream_frame_types;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000389 if (send_key_frame) {
Niels Möller8f7ce222019-03-21 15:43:58 +0100390 stream_frame_types.push_back(VideoFrameType::kVideoFrameKey);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000391 streaminfos_[stream_idx].key_frame_request = false;
392 } else {
Niels Möller8f7ce222019-03-21 15:43:58 +0100393 stream_frame_types.push_back(VideoFrameType::kVideoFrameDelta);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000394 }
395
396 int dst_width = streaminfos_[stream_idx].width;
397 int dst_height = streaminfos_[stream_idx].height;
398 // If scaling isn't required, because the input resolution
399 // matches the destination or the input image is empty (e.g.
400 // a keyframe request for encoders with internal camera
noahricfe3654d2016-07-01 09:05:54 -0700401 // sources) or the source image has a native handle, pass the image on
402 // directly. Otherwise, we'll scale it to match what the encoder expects
403 // (below).
404 // For texture frames, the underlying encoder is expected to be able to
405 // correctly sample/scale the source texture.
406 // TODO(perkj): ensure that works going forward, and figure out how this
407 // affects webrtc:5683.
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000408 if ((dst_width == src_width && dst_height == src_height) ||
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000409 input_image.video_frame_buffer()->type() ==
410 VideoFrameBuffer::Type::kNative) {
Niels Möllerc8d2e732019-03-06 12:00:33 +0100411 int ret = streaminfos_[stream_idx].encoder->Encode(input_image,
412 &stream_frame_types);
noahric57779102016-05-25 06:48:46 -0700413 if (ret != WEBRTC_VIDEO_CODEC_OK) {
414 return ret;
415 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000416 } else {
nisse64ec8f82016-09-27 00:17:25 -0700417 rtc::scoped_refptr<I420Buffer> dst_buffer =
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000418 I420Buffer::Create(dst_width, dst_height);
419 rtc::scoped_refptr<I420BufferInterface> src_buffer =
420 input_image.video_frame_buffer()->ToI420();
421 libyuv::I420Scale(src_buffer->DataY(), src_buffer->StrideY(),
422 src_buffer->DataU(), src_buffer->StrideU(),
423 src_buffer->DataV(), src_buffer->StrideV(), src_width,
424 src_height, dst_buffer->MutableDataY(),
425 dst_buffer->StrideY(), dst_buffer->MutableDataU(),
426 dst_buffer->StrideU(), dst_buffer->MutableDataV(),
427 dst_buffer->StrideV(), dst_width, dst_height,
nissec9c142f2016-05-17 04:05:47 -0700428 libyuv::kFilterBilinear);
nisse64ec8f82016-09-27 00:17:25 -0700429
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100430 // UpdateRect is not propagated to lower simulcast layers currently.
431 // TODO(ilnik): Consider scaling UpdateRect together with the buffer.
Ilya Nikolaevskiy4fc08552019-06-05 15:59:12 +0200432 VideoFrame frame(input_image);
433 frame.set_video_frame_buffer(dst_buffer);
434 frame.set_rotation(webrtc::kVideoRotation_0);
435 frame.set_update_rect(
436 VideoFrame::UpdateRect{0, 0, frame.width(), frame.height()});
Niels Möllerc8d2e732019-03-06 12:00:33 +0100437 int ret =
438 streaminfos_[stream_idx].encoder->Encode(frame, &stream_frame_types);
noahric57779102016-05-25 06:48:46 -0700439 if (ret != WEBRTC_VIDEO_CODEC_OK) {
440 return ret;
441 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000442 }
443 }
444
445 return WEBRTC_VIDEO_CODEC_OK;
446}
447
448int SimulcastEncoderAdapter::RegisterEncodeCompleteCallback(
449 EncodedImageCallback* callback) {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200450 RTC_DCHECK_RUN_ON(&encoder_queue_);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000451 encoded_complete_callback_ = callback;
452 return WEBRTC_VIDEO_CODEC_OK;
453}
454
Erik Språng16cb8f52019-04-12 13:59:09 +0200455void SimulcastEncoderAdapter::SetRates(
456 const RateControlParameters& parameters) {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200457 RTC_DCHECK_RUN_ON(&encoder_queue_);
brandtr5e171752017-05-23 03:32:16 -0700458
459 if (!Initialized()) {
Erik Språng16cb8f52019-04-12 13:59:09 +0200460 RTC_LOG(LS_WARNING) << "SetRates while not initialized";
461 return;
brandtr5e171752017-05-23 03:32:16 -0700462 }
sprang647bf432016-11-10 06:46:20 -0800463
Erik Språng16cb8f52019-04-12 13:59:09 +0200464 if (parameters.framerate_fps < 1.0) {
465 RTC_LOG(LS_WARNING) << "Invalid framerate: " << parameters.framerate_fps;
466 return;
brandtr5e171752017-05-23 03:32:16 -0700467 }
Erik Språng08127a92016-11-16 16:41:30 +0100468
Erik Språng16cb8f52019-04-12 13:59:09 +0200469 if (codec_.maxBitrate > 0 &&
470 parameters.bitrate.get_sum_kbps() > codec_.maxBitrate) {
471 RTC_LOG(LS_WARNING) << "Total bitrate " << parameters.bitrate.get_sum_kbps()
472 << " exceeds max bitrate: " << codec_.maxBitrate;
473 return;
brandtr5e171752017-05-23 03:32:16 -0700474 }
Erik Språng08127a92016-11-16 16:41:30 +0100475
Erik Språng16cb8f52019-04-12 13:59:09 +0200476 if (parameters.bitrate.get_sum_bps() > 0) {
sprang1369c832016-11-10 08:30:33 -0800477 // Make sure the bitrate fits the configured min bitrates. 0 is a special
478 // value that means paused, though, so leave it alone.
Erik Språng16cb8f52019-04-12 13:59:09 +0200479 if (parameters.bitrate.get_sum_kbps() < codec_.minBitrate) {
480 RTC_LOG(LS_WARNING) << "Total bitrate "
481 << parameters.bitrate.get_sum_kbps()
482 << " is lower than minimum bitrate: "
483 << codec_.minBitrate;
484 return;
brandtr5e171752017-05-23 03:32:16 -0700485 }
Erik Språng08127a92016-11-16 16:41:30 +0100486
sprang1369c832016-11-10 08:30:33 -0800487 if (codec_.numberOfSimulcastStreams > 0 &&
Erik Språng16cb8f52019-04-12 13:59:09 +0200488 parameters.bitrate.get_sum_kbps() <
489 codec_.simulcastStream[0].minBitrate) {
490 RTC_LOG(LS_WARNING) << "Total bitrate "
491 << parameters.bitrate.get_sum_kbps()
492 << " is lower than minimum bitrate of base layer: "
493 << codec_.simulcastStream[0].minBitrate;
494 return;
sprang1369c832016-11-10 08:30:33 -0800495 }
sprang1369c832016-11-10 08:30:33 -0800496 }
Erik Språng08127a92016-11-16 16:41:30 +0100497
Erik Språng16cb8f52019-04-12 13:59:09 +0200498 codec_.maxFramerate = static_cast<uint32_t>(parameters.framerate_fps + 0.5);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000499
sprang1369c832016-11-10 08:30:33 -0800500 for (size_t stream_idx = 0; stream_idx < streaminfos_.size(); ++stream_idx) {
Erik Språng08127a92016-11-16 16:41:30 +0100501 uint32_t stream_bitrate_kbps =
Erik Språng16cb8f52019-04-12 13:59:09 +0200502 parameters.bitrate.GetSpatialLayerSum(stream_idx) / 1000;
Erik Språng08127a92016-11-16 16:41:30 +0100503
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000504 // Need a key frame if we have not sent this stream before.
Erik Språng78ce6192016-09-12 16:04:43 +0200505 if (stream_bitrate_kbps > 0 && !streaminfos_[stream_idx].send_stream) {
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000506 streaminfos_[stream_idx].key_frame_request = true;
507 }
Erik Språng78ce6192016-09-12 16:04:43 +0200508 streaminfos_[stream_idx].send_stream = stream_bitrate_kbps > 0;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000509
Erik Språng08127a92016-11-16 16:41:30 +0100510 // Slice the temporal layers out of the full allocation and pass it on to
511 // the encoder handling the current simulcast stream.
Erik Språng16cb8f52019-04-12 13:59:09 +0200512 RateControlParameters stream_parameters = parameters;
513 stream_parameters.bitrate = VideoBitrateAllocation();
brandtr5e171752017-05-23 03:32:16 -0700514 for (int i = 0; i < kMaxTemporalStreams; ++i) {
Erik Språng16cb8f52019-04-12 13:59:09 +0200515 if (parameters.bitrate.HasBitrate(stream_idx, i)) {
516 stream_parameters.bitrate.SetBitrate(
517 0, i, parameters.bitrate.GetBitrate(stream_idx, i));
erikvarga@webrtc.org01f2ec32017-11-15 14:58:23 +0100518 }
brandtr5e171752017-05-23 03:32:16 -0700519 }
Minyue Li7ddef1a2019-04-11 10:50:19 +0000520
Erik Språng16cb8f52019-04-12 13:59:09 +0200521 // Assign link allocation proportionally to spatial layer allocation.
522 if (parameters.bandwidth_allocation != DataRate::Zero()) {
523 stream_parameters.bandwidth_allocation =
524 DataRate::bps((parameters.bandwidth_allocation.bps() *
525 stream_parameters.bitrate.get_sum_bps()) /
526 parameters.bitrate.get_sum_bps());
527 // Make sure we don't allocate bandwidth lower than target bitrate.
528 if (stream_parameters.bandwidth_allocation.bps() <
529 stream_parameters.bitrate.get_sum_bps()) {
530 stream_parameters.bandwidth_allocation =
531 DataRate::bps(stream_parameters.bitrate.get_sum_bps());
532 }
533 }
534
535 streaminfos_[stream_idx].encoder->SetRates(stream_parameters);
536 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000537}
538
brandtr5e171752017-05-23 03:32:16 -0700539// TODO(brandtr): Add task checker to this member function, when all encoder
540// callbacks are coming in on the encoder queue.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700541EncodedImageCallback::Result SimulcastEncoderAdapter::OnEncodedImage(
Noah Richards41ee1ea2015-04-15 09:24:26 -0700542 size_t stream_idx,
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000543 const EncodedImage& encodedImage,
544 const CodecSpecificInfo* codecSpecificInfo,
545 const RTPFragmentationHeader* fragmentation) {
Niels Möllerd3b8c632018-08-27 15:33:42 +0200546 EncodedImage stream_image(encodedImage);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000547 CodecSpecificInfo stream_codec_specific = *codecSpecificInfo;
Niels Möllerd3b8c632018-08-27 15:33:42 +0200548
549 stream_image.SetSpatialIndex(stream_idx);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000550
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700551 return encoded_complete_callback_->OnEncodedImage(
Niels Möllerd3b8c632018-08-27 15:33:42 +0200552 stream_image, &stream_codec_specific, fragmentation);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000553}
554
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000555void SimulcastEncoderAdapter::PopulateStreamCodec(
brandtr5e171752017-05-23 03:32:16 -0700556 const webrtc::VideoCodec& inst,
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000557 int stream_index,
Erik Språng78ce6192016-09-12 16:04:43 +0200558 uint32_t start_bitrate_kbps,
Florent Castelli1b761ca2019-01-21 14:33:02 +0100559 StreamResolution stream_resolution,
Erik Språng78ce6192016-09-12 16:04:43 +0200560 webrtc::VideoCodec* stream_codec) {
brandtr5e171752017-05-23 03:32:16 -0700561 *stream_codec = inst;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000562
563 // Stream specific settings.
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000564 stream_codec->numberOfSimulcastStreams = 0;
brandtr5e171752017-05-23 03:32:16 -0700565 stream_codec->width = inst.simulcastStream[stream_index].width;
566 stream_codec->height = inst.simulcastStream[stream_index].height;
567 stream_codec->maxBitrate = inst.simulcastStream[stream_index].maxBitrate;
568 stream_codec->minBitrate = inst.simulcastStream[stream_index].minBitrate;
569 stream_codec->qpMax = inst.simulcastStream[stream_index].qpMax;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000570 // Settings that are based on stream/resolution.
Florent Castelli1b761ca2019-01-21 14:33:02 +0100571 if (stream_resolution == StreamResolution::LOWEST) {
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000572 // Settings for lowest spatial resolutions.
Ilya Nikolaevskiyc30a1312018-08-27 11:07:48 +0200573 if (inst.mode == VideoCodecMode::kScreensharing) {
574 if (experimental_boosted_screenshare_qp_) {
575 stream_codec->qpMax = *experimental_boosted_screenshare_qp_;
576 }
Erik Språng7f24fb92019-02-13 10:49:37 +0100577 } else if (boost_base_layer_quality_) {
Ilya Nikolaevskiyc30a1312018-08-27 11:07:48 +0200578 stream_codec->qpMax = kLowestResMaxQp;
579 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000580 }
Sergio Garcia Murillo43800f92018-06-21 16:16:38 +0200581 if (inst.codecType == webrtc::kVideoCodecVP8) {
582 stream_codec->VP8()->numberOfTemporalLayers =
583 inst.simulcastStream[stream_index].numberOfTemporalLayers;
Florent Castelli1b761ca2019-01-21 14:33:02 +0100584 if (stream_resolution != StreamResolution::HIGHEST) {
Sergio Garcia Murillo43800f92018-06-21 16:16:38 +0200585 // For resolutions below CIF, set the codec |complexity| parameter to
586 // kComplexityHigher, which maps to cpu_used = -4.
587 int pixels_per_frame = stream_codec->width * stream_codec->height;
588 if (pixels_per_frame < 352 * 288) {
589 stream_codec->VP8()->complexity =
590 webrtc::VideoCodecComplexity::kComplexityHigher;
591 }
592 // Turn off denoising for all streams but the highest resolution.
593 stream_codec->VP8()->denoisingOn = false;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000594 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000595 }
596 // TODO(ronghuawu): what to do with targetBitrate.
597
Erik Språng78ce6192016-09-12 16:04:43 +0200598 stream_codec->startBitrate = start_bitrate_kbps;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000599}
600
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000601bool SimulcastEncoderAdapter::Initialized() const {
brandtr5e171752017-05-23 03:32:16 -0700602 return rtc::AtomicOps::AcquireLoad(&inited_) == 1;
603}
604
605void SimulcastEncoderAdapter::DestroyStoredEncoders() {
606 while (!stored_encoders_.empty()) {
brandtr5e171752017-05-23 03:32:16 -0700607 stored_encoders_.pop();
608 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000609}
610
Erik Språng9b5b0702018-11-01 14:52:30 +0100611VideoEncoder::EncoderInfo SimulcastEncoderAdapter::GetEncoderInfo() const {
Erik Språng75de46a2018-11-07 14:53:32 +0100612 return encoder_info_;
pbosecd21b42016-01-07 08:03:05 -0800613}
614
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000615} // namespace webrtc