blob: 936d816db35b0adccd61747b400c8595264706ae [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
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 "video/video_stream_encoder.h"
mflodman@webrtc.org84d17832011-12-01 17:02:23 +000012
stefan@webrtc.orgc3cc3752013-06-04 09:36:56 +000013#include <algorithm>
Evan Shrubsolecc62b162019-09-09 11:26:45 +020014#include <array>
perkj57c21f92016-06-17 07:27:16 -070015#include <limits>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020016#include <memory>
sprangc5d62e22017-04-02 23:53:04 -070017#include <numeric>
Per512ecb32016-09-23 15:52:06 +020018#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000019
Steve Antonbd631a02019-03-28 10:51:27 -070020#include "absl/algorithm/container.h"
Niels Möller4dc66c52018-10-05 14:17:58 +020021#include "api/video/encoded_image.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "api/video/i420_buffer.h"
Jiawei Ouc2ebe212018-11-08 10:02:56 -080023#include "api/video/video_bitrate_allocator_factory.h"
Evan Shrubsolecc62b162019-09-09 11:26:45 +020024#include "api/video/video_codec_constants.h"
Elad Alon370f93a2019-06-11 14:57:57 +020025#include "api/video_codecs/video_encoder.h"
Sergey Silkin8b9b5f92018-12-10 09:28:53 +010026#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/video_coding/include/video_codec_initializer.h"
Niels Möller6bb5ab92019-01-11 11:11:10 +010028#include "modules/video_coding/utility/default_video_bitrate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/arraysize.h"
30#include "rtc_base/checks.h"
Erik Språng6a7baa72019-02-26 18:31:00 +010031#include "rtc_base/experiments/alr_experiment.h"
Åsa Perssona945aee2018-04-24 16:53:25 +020032#include "rtc_base/experiments/quality_scaling_experiment.h"
Erik Språng7ca375c2019-02-06 16:20:17 +010033#include "rtc_base/experiments/rate_control_settings.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/location.h"
35#include "rtc_base/logging.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020036#include "rtc_base/strings/string_builder.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010037#include "rtc_base/system/fallthrough.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/trace_event.h"
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020040#include "system_wrappers/include/field_trial.h"
nisseea3a7982017-05-15 02:42:11 -070041
niklase@google.com470e71d2011-07-07 08:21:25 +000042namespace webrtc {
43
perkj26091b12016-09-01 01:17:40 -070044namespace {
sprangb1ca0732017-02-01 08:38:12 -080045
asapersson6ffb67d2016-09-12 00:10:45 -070046// Time interval for logging frame counts.
47const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070048const int kMinFramerateFps = 2;
perkj26091b12016-09-01 01:17:40 -070049
Sebastian Janssona3177052018-04-10 13:05:49 +020050// Time to keep a single cached pending frame in paused state.
51const int64_t kPendingFrameTimeoutMs = 1000;
52
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020053const char kInitialFramedropFieldTrial[] = "WebRTC-InitialFramedrop";
Niels Möller6bb5ab92019-01-11 11:11:10 +010054constexpr char kFrameDropperFieldTrial[] = "WebRTC-FrameDropper";
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020055
kthelgason2bc68642017-02-07 07:02:22 -080056// The maximum number of frames to drop at beginning of stream
57// to try and achieve desired bitrate.
58const int kMaxInitialFramedrop = 4;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020059// When the first change in BWE above this threshold occurs,
60// enable DropFrameDueToSize logic.
61const float kFramedropThreshold = 0.3;
kthelgason2bc68642017-02-07 07:02:22 -080062
Niels Möller6bb5ab92019-01-11 11:11:10 +010063// Averaging window spanning 90 frames at default 30fps, matching old media
64// optimization module defaults.
65const int64_t kFrameRateAvergingWindowSizeMs = (1000 / 30) * 90;
66
Erik Språngb7cb7b52019-02-26 15:52:33 +010067const size_t kDefaultPayloadSize = 1440;
68
Niels Möllerfe407b72019-09-10 10:48:48 +020069const int64_t kParameterUpdateIntervalMs = 1000;
70
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020071uint32_t abs_diff(uint32_t a, uint32_t b) {
72 return (a < b) ? b - a : a - b;
73}
74
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070075bool IsResolutionScalingEnabled(DegradationPreference degradation_preference) {
76 return degradation_preference == DegradationPreference::MAINTAIN_FRAMERATE ||
77 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070078}
79
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070080bool IsFramerateScalingEnabled(DegradationPreference degradation_preference) {
81 return degradation_preference == DegradationPreference::MAINTAIN_RESOLUTION ||
82 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070083}
84
Niels Möllerd1f7eb62018-03-28 16:40:58 +020085// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
86// pipelining encoders better (multiple input frames before something comes
87// out). This should effectively turn off CPU adaptations for systems that
88// remotely cope with the load right now.
89CpuOveruseOptions GetCpuOveruseOptions(
Niels Möller213618e2018-07-24 09:29:58 +020090 const VideoStreamEncoderSettings& settings,
Niels Möller4db138e2018-04-19 09:04:13 +020091 bool full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +020092 CpuOveruseOptions options;
93
Niels Möller4db138e2018-04-19 09:04:13 +020094 if (full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +020095 options.low_encode_usage_threshold_percent = 150;
96 options.high_encode_usage_threshold_percent = 200;
97 }
98 if (settings.experiment_cpu_load_estimator) {
99 options.filter_time_ms = 5 * rtc::kNumMillisecsPerSec;
100 }
101
102 return options;
103}
104
Sergey Silkin5ee69672019-07-02 14:18:34 +0200105bool RequiresEncoderReset(const VideoCodec& prev_send_codec,
106 const VideoCodec& new_send_codec,
107 bool was_encode_called_since_last_initialization) {
108 // Does not check max/minBitrate or maxFramerate.
109 if (new_send_codec.codecType != prev_send_codec.codecType ||
110 new_send_codec.width != prev_send_codec.width ||
111 new_send_codec.height != prev_send_codec.height ||
112 new_send_codec.qpMax != prev_send_codec.qpMax ||
Erik Språngb7cb7b52019-02-26 15:52:33 +0100113 new_send_codec.numberOfSimulcastStreams !=
Sergey Silkin5ee69672019-07-02 14:18:34 +0200114 prev_send_codec.numberOfSimulcastStreams ||
115 new_send_codec.mode != prev_send_codec.mode) {
116 return true;
117 }
118
119 if (!was_encode_called_since_last_initialization &&
120 (new_send_codec.startBitrate != prev_send_codec.startBitrate)) {
121 // If start bitrate has changed reconfigure encoder only if encoding had not
122 // yet started.
Erik Språngb7cb7b52019-02-26 15:52:33 +0100123 return true;
124 }
125
126 switch (new_send_codec.codecType) {
127 case kVideoCodecVP8:
Sergey Silkin5ee69672019-07-02 14:18:34 +0200128 if (new_send_codec.VP8() != prev_send_codec.VP8()) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100129 return true;
130 }
131 break;
132
133 case kVideoCodecVP9:
Sergey Silkin5ee69672019-07-02 14:18:34 +0200134 if (new_send_codec.VP9() != prev_send_codec.VP9()) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100135 return true;
136 }
137 break;
138
139 case kVideoCodecH264:
Sergey Silkin5ee69672019-07-02 14:18:34 +0200140 if (new_send_codec.H264() != prev_send_codec.H264()) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100141 return true;
142 }
143 break;
144
145 default:
146 break;
147 }
148
149 for (unsigned char i = 0; i < new_send_codec.numberOfSimulcastStreams; ++i) {
Sergey Silkin5ee69672019-07-02 14:18:34 +0200150 if (new_send_codec.simulcastStream[i].width !=
151 prev_send_codec.simulcastStream[i].width ||
152 new_send_codec.simulcastStream[i].height !=
153 prev_send_codec.simulcastStream[i].height ||
154 new_send_codec.simulcastStream[i].numberOfTemporalLayers !=
155 prev_send_codec.simulcastStream[i].numberOfTemporalLayers ||
156 new_send_codec.simulcastStream[i].qpMax !=
157 prev_send_codec.simulcastStream[i].qpMax ||
158 new_send_codec.simulcastStream[i].active !=
159 prev_send_codec.simulcastStream[i].active) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100160 return true;
Sergey Silkin5ee69672019-07-02 14:18:34 +0200161 }
Erik Språngb7cb7b52019-02-26 15:52:33 +0100162 }
163 return false;
164}
Erik Språng6a7baa72019-02-26 18:31:00 +0100165
166std::array<uint8_t, 2> GetExperimentGroups() {
167 std::array<uint8_t, 2> experiment_groups;
168 absl::optional<AlrExperimentSettings> experiment_settings =
169 AlrExperimentSettings::CreateFromFieldTrial(
170 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
171 if (experiment_settings) {
172 experiment_groups[0] = experiment_settings->group_id + 1;
173 } else {
174 experiment_groups[0] = 0;
175 }
176 experiment_settings = AlrExperimentSettings::CreateFromFieldTrial(
177 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
178 if (experiment_settings) {
179 experiment_groups[1] = experiment_settings->group_id + 1;
180 } else {
181 experiment_groups[1] = 0;
182 }
183 return experiment_groups;
184}
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100185
186// Limit allocation across TLs in bitrate allocation according to number of TLs
187// in EncoderInfo.
188VideoBitrateAllocation UpdateAllocationFromEncoderInfo(
189 const VideoBitrateAllocation& allocation,
190 const VideoEncoder::EncoderInfo& encoder_info) {
191 if (allocation.get_sum_bps() == 0) {
192 return allocation;
193 }
194 VideoBitrateAllocation new_allocation;
195 for (int si = 0; si < kMaxSpatialLayers; ++si) {
196 if (encoder_info.fps_allocation[si].size() == 1 &&
197 allocation.IsSpatialLayerUsed(si)) {
198 // One TL is signalled to be used by the encoder. Do not distribute
199 // bitrate allocation across TLs (use sum at ti:0).
200 new_allocation.SetBitrate(si, 0, allocation.GetSpatialLayerSum(si));
201 } else {
202 for (int ti = 0; ti < kMaxTemporalStreams; ++ti) {
203 if (allocation.HasBitrate(si, ti))
204 new_allocation.SetBitrate(si, ti, allocation.GetBitrate(si, ti));
205 }
206 }
207 }
208 return new_allocation;
209}
perkj26091b12016-09-01 01:17:40 -0700210} // namespace
211
perkja49cbd32016-09-16 07:53:41 -0700212// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700213// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
214// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700215// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700216class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700217 public:
mflodmancc3d4422017-08-03 08:27:51 -0700218 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
219 : video_stream_encoder_(video_stream_encoder),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700220 degradation_preference_(DegradationPreference::DISABLED),
Åsa Persson8c1bf952018-09-13 10:42:19 +0200221 source_(nullptr),
222 max_framerate_(std::numeric_limits<int>::max()) {}
perkja49cbd32016-09-16 07:53:41 -0700223
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700224 void SetSource(rtc::VideoSourceInterface<VideoFrame>* source,
225 const DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700226 // Called on libjingle's worker thread.
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200227 RTC_DCHECK_RUN_ON(&main_checker_);
perkja49cbd32016-09-16 07:53:41 -0700228 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700229 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700230 {
231 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700232 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700233 old_source = source_;
234 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700235 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700236 }
237
238 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700239 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700240 }
241
242 if (!source) {
243 return;
244 }
245
mflodmancc3d4422017-08-03 08:27:51 -0700246 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700247 }
248
Åsa Persson8c1bf952018-09-13 10:42:19 +0200249 void SetMaxFramerate(int max_framerate) {
250 RTC_DCHECK_GT(max_framerate, 0);
251 rtc::CritScope lock(&crit_);
252 if (max_framerate == max_framerate_)
253 return;
254
255 RTC_LOG(LS_INFO) << "Set max framerate: " << max_framerate;
256 max_framerate_ = max_framerate;
257 if (source_) {
258 source_->AddOrUpdateSink(video_stream_encoder_,
259 GetActiveSinkWantsInternal());
260 }
261 }
262
perkj803d97f2016-11-01 11:45:46 -0700263 void SetWantsRotationApplied(bool rotation_applied) {
264 rtc::CritScope lock(&crit_);
265 sink_wants_.rotation_applied = rotation_applied;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200266 if (source_) {
267 source_->AddOrUpdateSink(video_stream_encoder_,
268 GetActiveSinkWantsInternal());
269 }
sprangc5d62e22017-04-02 23:53:04 -0700270 }
271
sprangfda496a2017-06-15 04:21:07 -0700272 rtc::VideoSinkWants GetActiveSinkWants() {
273 rtc::CritScope lock(&crit_);
274 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700275 }
276
asaperssonf7e294d2017-06-13 23:25:22 -0700277 void ResetPixelFpsCount() {
278 rtc::CritScope lock(&crit_);
279 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
280 sink_wants_.target_pixel_count.reset();
281 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
282 if (source_)
Åsa Persson8c1bf952018-09-13 10:42:19 +0200283 source_->AddOrUpdateSink(video_stream_encoder_,
284 GetActiveSinkWantsInternal());
asaperssonf7e294d2017-06-13 23:25:22 -0700285 }
286
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100287 bool RequestResolutionLowerThan(int pixel_count,
288 int min_pixels_per_frame,
289 bool* min_pixels_reached) {
perkj803d97f2016-11-01 11:45:46 -0700290 // Called on the encoder task queue.
291 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700292 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700293 // This can happen since |degradation_preference_| is set on libjingle's
294 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700295 return false;
perkj803d97f2016-11-01 11:45:46 -0700296 }
asapersson13874762017-06-07 00:01:02 -0700297 // The input video frame size will have a resolution less than or equal to
298 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800299 const int pixels_wanted = (pixel_count * 3) / 5;
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100300 if (pixels_wanted >= sink_wants_.max_pixel_count) {
301 return false;
302 }
303 if (pixels_wanted < min_pixels_per_frame) {
304 *min_pixels_reached = true;
asaperssond0de2952017-04-21 01:47:31 -0700305 return false;
asapersson13874762017-06-07 00:01:02 -0700306 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100307 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
308 << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700309 sink_wants_.max_pixel_count = pixels_wanted;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200310 sink_wants_.target_pixel_count = absl::nullopt;
mflodmancc3d4422017-08-03 08:27:51 -0700311 source_->AddOrUpdateSink(video_stream_encoder_,
312 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700313 return true;
sprangc5d62e22017-04-02 23:53:04 -0700314 }
315
sprangfda496a2017-06-15 04:21:07 -0700316 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700317 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700318 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700319 int framerate_wanted = (fps * 2) / 3;
320 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700321 }
322
asapersson13874762017-06-07 00:01:02 -0700323 bool RequestHigherResolutionThan(int pixel_count) {
324 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700325 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700326 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700327 // This can happen since |degradation_preference_| is set on libjingle's
328 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700329 return false;
perkj803d97f2016-11-01 11:45:46 -0700330 }
asapersson13874762017-06-07 00:01:02 -0700331 int max_pixels_wanted = pixel_count;
332 if (max_pixels_wanted != std::numeric_limits<int>::max())
333 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700334
asapersson13874762017-06-07 00:01:02 -0700335 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
336 return false;
337
338 sink_wants_.max_pixel_count = max_pixels_wanted;
339 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700340 // Remove any constraints.
341 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700342 } else {
343 // On step down we request at most 3/5 the pixel count of the previous
344 // resolution, so in order to take "one step up" we request a resolution
345 // as close as possible to 5/3 of the current resolution. The actual pixel
346 // count selected depends on the capabilities of the source. In order to
347 // not take a too large step up, we cap the requested pixel count to be at
348 // most four time the current number of pixels.
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100349 sink_wants_.target_pixel_count = (pixel_count * 5) / 3;
sprangc5d62e22017-04-02 23:53:04 -0700350 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100351 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
352 << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700353 source_->AddOrUpdateSink(video_stream_encoder_,
354 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700355 return true;
sprangc5d62e22017-04-02 23:53:04 -0700356 }
357
sprangfda496a2017-06-15 04:21:07 -0700358 // Request upgrade in framerate. Returns the new requested frame, or -1 if
359 // no change requested. Note that maxint may be returned if limits due to
360 // adaptation requests are removed completely. In that case, consider
361 // |max_framerate_| to be the current limit (assuming the capturer complies).
362 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700363 // Called on the encoder task queue.
364 // The input frame rate will be scaled up to the last step, with rounding.
365 int framerate_wanted = fps;
366 if (fps != std::numeric_limits<int>::max())
367 framerate_wanted = (fps * 3) / 2;
368
sprangfda496a2017-06-15 04:21:07 -0700369 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700370 }
371
372 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700373 // Called on the encoder task queue.
374 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700375 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
376 return false;
377
378 const int fps_wanted = std::max(kMinFramerateFps, fps);
379 if (fps_wanted >= sink_wants_.max_framerate_fps)
380 return false;
381
Mirko Bonadei675513b2017-11-09 11:09:25 +0100382 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700383 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700384 source_->AddOrUpdateSink(video_stream_encoder_,
385 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700386 return true;
387 }
388
389 bool IncreaseFramerate(int fps) {
390 // Called on the encoder task queue.
391 rtc::CritScope lock(&crit_);
392 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
393 return false;
394
395 const int fps_wanted = std::max(kMinFramerateFps, fps);
396 if (fps_wanted <= sink_wants_.max_framerate_fps)
397 return false;
398
Mirko Bonadei675513b2017-11-09 11:09:25 +0100399 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700400 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700401 source_->AddOrUpdateSink(video_stream_encoder_,
402 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700403 return true;
perkj803d97f2016-11-01 11:45:46 -0700404 }
405
perkja49cbd32016-09-16 07:53:41 -0700406 private:
sprangfda496a2017-06-15 04:21:07 -0700407 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700408 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700409 rtc::VideoSinkWants wants = sink_wants_;
410 // Clear any constraints from the current sink wants that don't apply to
411 // the used degradation_preference.
412 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700413 case DegradationPreference::BALANCED:
sprangfda496a2017-06-15 04:21:07 -0700414 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700415 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangfda496a2017-06-15 04:21:07 -0700416 wants.max_framerate_fps = std::numeric_limits<int>::max();
417 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700418 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangfda496a2017-06-15 04:21:07 -0700419 wants.max_pixel_count = std::numeric_limits<int>::max();
420 wants.target_pixel_count.reset();
421 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700422 case DegradationPreference::DISABLED:
sprangfda496a2017-06-15 04:21:07 -0700423 wants.max_pixel_count = std::numeric_limits<int>::max();
424 wants.target_pixel_count.reset();
425 wants.max_framerate_fps = std::numeric_limits<int>::max();
426 }
Åsa Persson8c1bf952018-09-13 10:42:19 +0200427 // Limit to configured max framerate.
428 wants.max_framerate_fps = std::min(max_framerate_, wants.max_framerate_fps);
sprangfda496a2017-06-15 04:21:07 -0700429 return wants;
430 }
431
perkja49cbd32016-09-16 07:53:41 -0700432 rtc::CriticalSection crit_;
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200433 SequenceChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700434 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700435 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700436 DegradationPreference degradation_preference_ RTC_GUARDED_BY(&crit_);
danilchapa37de392017-09-09 04:17:22 -0700437 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
Åsa Persson8c1bf952018-09-13 10:42:19 +0200438 int max_framerate_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700439
440 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
441};
442
Erik Språng4c6ca302019-04-08 15:14:01 +0200443VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings()
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +0000444 : VideoEncoder::RateControlParameters(),
Florent Castellia8336d32019-09-09 13:36:55 +0200445 encoder_target(DataRate::Zero()),
446 stable_encoder_target(DataRate::Zero()) {}
Erik Språng4c6ca302019-04-08 15:14:01 +0200447
448VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings(
449 const VideoBitrateAllocation& bitrate,
450 double framerate_fps,
451 DataRate bandwidth_allocation,
Florent Castellia8336d32019-09-09 13:36:55 +0200452 DataRate encoder_target,
453 DataRate stable_encoder_target)
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +0000454 : VideoEncoder::RateControlParameters(bitrate,
455 framerate_fps,
456 bandwidth_allocation),
Florent Castellia8336d32019-09-09 13:36:55 +0200457 encoder_target(encoder_target),
458 stable_encoder_target(stable_encoder_target) {}
Erik Språng4c6ca302019-04-08 15:14:01 +0200459
460bool VideoStreamEncoder::EncoderRateSettings::operator==(
461 const EncoderRateSettings& rhs) const {
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +0000462 return bitrate == rhs.bitrate && framerate_fps == rhs.framerate_fps &&
463 bandwidth_allocation == rhs.bandwidth_allocation &&
Florent Castellia8336d32019-09-09 13:36:55 +0200464 encoder_target == rhs.encoder_target &&
465 stable_encoder_target == rhs.stable_encoder_target;
Erik Språng4c6ca302019-04-08 15:14:01 +0200466}
467
468bool VideoStreamEncoder::EncoderRateSettings::operator!=(
469 const EncoderRateSettings& rhs) const {
470 return !(*this == rhs);
471}
472
Åsa Persson0122e842017-10-16 12:19:23 +0200473VideoStreamEncoder::VideoStreamEncoder(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100474 Clock* clock,
Åsa Persson0122e842017-10-16 12:19:23 +0200475 uint32_t number_of_cores,
Niels Möller213618e2018-07-24 09:29:58 +0200476 VideoStreamEncoderObserver* encoder_stats_observer,
477 const VideoStreamEncoderSettings& settings,
Sebastian Jansson74682c12019-03-01 11:50:20 +0100478 std::unique_ptr<OveruseFrameDetector> overuse_detector,
479 TaskQueueFactory* task_queue_factory)
perkj26091b12016-09-01 01:17:40 -0700480 : shutdown_event_(true /* manual_reset */, false),
481 number_of_cores_(number_of_cores),
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200482 initial_framedrop_(0),
483 initial_framedrop_on_bwe_enabled_(
484 webrtc::field_trial::IsEnabled(kInitialFramedropFieldTrial)),
Åsa Perssona945aee2018-04-24 16:53:25 +0200485 quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
perkja49cbd32016-09-16 07:53:41 -0700486 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200487 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700488 settings_(settings),
Erik Språng7ca375c2019-02-06 16:20:17 +0100489 rate_control_settings_(RateControlSettings::ParseFromFieldTrials()),
Åsa Persson139f4dc2019-08-02 09:29:58 +0200490 quality_scaler_settings_(QualityScalerSettings::ParseFromFieldTrials()),
Niels Möller73f29cb2018-01-31 16:09:31 +0100491 overuse_detector_(std::move(overuse_detector)),
Niels Möller213618e2018-07-24 09:29:58 +0200492 encoder_stats_observer_(encoder_stats_observer),
Erik Språng6a7baa72019-02-26 18:31:00 +0100493 encoder_initialized_(false),
sprangfda496a2017-06-15 04:21:07 -0700494 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700495 pending_encoder_reconfiguration_(false),
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000496 pending_encoder_creation_(false),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200497 crop_width_(0),
498 crop_height_(0),
perkj26091b12016-09-01 01:17:40 -0700499 encoder_start_bitrate_bps_(0),
Åsa Persson139f4dc2019-08-02 09:29:58 +0200500 set_start_bitrate_bps_(0),
501 set_start_bitrate_time_ms_(0),
502 has_seen_first_bwe_drop_(false),
Pera48ddb72016-09-29 11:48:50 +0200503 max_data_payload_length_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000504 encoder_paused_and_dropped_frame_(false),
Sergey Silkin5ee69672019-07-02 14:18:34 +0200505 was_encode_called_since_last_initialization_(false),
philipele8ed8302019-07-03 11:53:48 +0200506 encoder_failed_(false),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100507 clock_(clock),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700508 degradation_preference_(DegradationPreference::DISABLED),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700509 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700510 last_captured_timestamp_(0),
511 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
512 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700513 last_frame_log_ms_(clock_->TimeInMilliseconds()),
514 captured_frame_count_(0),
515 dropped_frame_count_(0),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200516 pending_frame_post_time_us_(0),
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100517 accumulated_update_rect_{0, 0, 0, 0},
sprang1a646ee2016-12-01 06:34:11 -0800518 bitrate_observer_(nullptr),
Elad Alon8f01c4e2019-06-28 15:19:43 +0200519 fec_controller_override_(nullptr),
Niels Möller6bb5ab92019-01-11 11:11:10 +0100520 force_disable_frame_dropper_(false),
521 input_framerate_(kFrameRateAvergingWindowSizeMs, 1000),
522 pending_frame_drops_(0),
Niels Möller8f7ce222019-03-21 15:43:58 +0100523 next_frame_types_(1, VideoFrameType::kVideoFrameDelta),
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200524 frame_encode_metadata_writer_(this),
Erik Språng6a7baa72019-02-26 18:31:00 +0100525 experiment_groups_(GetExperimentGroups()),
philipelda5aa4d2019-04-26 13:37:37 +0200526 next_frame_id_(0),
Sebastian Jansson74682c12019-03-01 11:50:20 +0100527 encoder_queue_(task_queue_factory->CreateTaskQueue(
528 "EncoderQueue",
philipeld9cc8c02019-09-16 14:53:40 +0200529 TaskQueueFactory::Priority::NORMAL)),
530 encoder_switch_experiment_(ParseEncoderSwitchFieldTrial()),
531 encoder_switch_requested_(false) {
Niels Möller213618e2018-07-24 09:29:58 +0200532 RTC_DCHECK(encoder_stats_observer);
Niels Möller73f29cb2018-01-31 16:09:31 +0100533 RTC_DCHECK(overuse_detector_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100534 RTC_DCHECK_GE(number_of_cores, 1);
philipelda5aa4d2019-04-26 13:37:37 +0200535
536 for (auto& state : encoder_buffer_state_)
537 state.fill(std::numeric_limits<int64_t>::max());
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000538}
539
mflodmancc3d4422017-08-03 08:27:51 -0700540VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700541 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700542 RTC_DCHECK(shutdown_event_.Wait(0))
543 << "Must call ::Stop() before destruction.";
544}
545
mflodmancc3d4422017-08-03 08:27:51 -0700546void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700547 RTC_DCHECK_RUN_ON(&thread_checker_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700548 source_proxy_->SetSource(nullptr, DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700549 encoder_queue_.PostTask([this] {
550 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700551 overuse_detector_->StopCheckForOveruse();
Erik Språngb7cb7b52019-02-26 15:52:33 +0100552 rate_allocator_ = nullptr;
sprang1a646ee2016-12-01 06:34:11 -0800553 bitrate_observer_ = nullptr;
Erik Språng6a7baa72019-02-26 18:31:00 +0100554 ReleaseEncoder();
kthelgason876222f2016-11-29 01:44:11 -0800555 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700556 shutdown_event_.Set();
557 });
558
559 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700560}
561
Niels Möller0327c2d2018-05-21 14:09:31 +0200562void VideoStreamEncoder::SetBitrateAllocationObserver(
sprang1a646ee2016-12-01 06:34:11 -0800563 VideoBitrateAllocationObserver* bitrate_observer) {
564 RTC_DCHECK_RUN_ON(&thread_checker_);
565 encoder_queue_.PostTask([this, bitrate_observer] {
566 RTC_DCHECK_RUN_ON(&encoder_queue_);
567 RTC_DCHECK(!bitrate_observer_);
568 bitrate_observer_ = bitrate_observer;
569 });
570}
571
Elad Alon8f01c4e2019-06-28 15:19:43 +0200572void VideoStreamEncoder::SetFecControllerOverride(
573 FecControllerOverride* fec_controller_override) {
574 encoder_queue_.PostTask([this, fec_controller_override] {
575 RTC_DCHECK_RUN_ON(&encoder_queue_);
576 RTC_DCHECK(!fec_controller_override_);
577 fec_controller_override_ = fec_controller_override;
578 if (encoder_) {
579 encoder_->SetFecControllerOverride(fec_controller_override_);
580 }
581 });
582}
583
mflodmancc3d4422017-08-03 08:27:51 -0700584void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700585 rtc::VideoSourceInterface<VideoFrame>* source,
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700586 const DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700587 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700588 source_proxy_->SetSource(source, degradation_preference);
589 encoder_queue_.PostTask([this, degradation_preference] {
590 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700591 if (degradation_preference_ != degradation_preference) {
592 // Reset adaptation state, so that we're not tricked into thinking there's
593 // an already pending request of the same type.
594 last_adaptation_request_.reset();
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700595 if (degradation_preference == DegradationPreference::BALANCED ||
596 degradation_preference_ == DegradationPreference::BALANCED) {
asaperssonf7e294d2017-06-13 23:25:22 -0700597 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
598 // AdaptCounter for all modes.
599 source_proxy_->ResetPixelFpsCount();
600 adapt_counters_.clear();
601 }
sprangc5d62e22017-04-02 23:53:04 -0700602 }
sprangb1ca0732017-02-01 08:38:12 -0800603 degradation_preference_ = degradation_preference;
Niels Möller4db138e2018-04-19 09:04:13 +0200604
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000605 if (encoder_)
Erik Språng7ca375c2019-02-06 16:20:17 +0100606 ConfigureQualityScaler(encoder_->GetEncoderInfo());
Niels Möller4db138e2018-04-19 09:04:13 +0200607
Niels Möller7dc26b72017-12-06 10:27:48 +0100608 if (!IsFramerateScalingEnabled(degradation_preference) &&
609 max_framerate_ != -1) {
610 // If frame rate scaling is no longer allowed, remove any potential
611 // allowance for longer frame intervals.
612 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
613 }
perkj803d97f2016-11-01 11:45:46 -0700614 });
perkja49cbd32016-09-16 07:53:41 -0700615}
616
mflodmancc3d4422017-08-03 08:27:51 -0700617void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700618 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700619 encoder_queue_.PostTask([this, sink] {
620 RTC_DCHECK_RUN_ON(&encoder_queue_);
621 sink_ = sink;
622 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000623}
624
mflodmancc3d4422017-08-03 08:27:51 -0700625void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700626 encoder_queue_.PostTask([this, start_bitrate_bps] {
627 RTC_DCHECK_RUN_ON(&encoder_queue_);
628 encoder_start_bitrate_bps_ = start_bitrate_bps;
Åsa Persson139f4dc2019-08-02 09:29:58 +0200629 set_start_bitrate_bps_ = start_bitrate_bps;
630 set_start_bitrate_time_ms_ = clock_->TimeInMilliseconds();
perkj26091b12016-09-01 01:17:40 -0700631 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000632}
Peter Boström00b9d212016-05-19 16:59:03 +0200633
mflodmancc3d4422017-08-03 08:27:51 -0700634void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200635 size_t max_data_payload_length) {
Yves Gerey665174f2018-06-19 15:03:05 +0200636 encoder_queue_.PostTask(
Sebastian Jansson86314cf2019-09-17 20:29:59 +0200637 [this, config = std::move(config), max_data_payload_length]() mutable {
638 RTC_DCHECK_RUN_ON(&encoder_queue_);
639 RTC_DCHECK(sink_);
640 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
perkj26091b12016-09-01 01:17:40 -0700641
Sebastian Jansson86314cf2019-09-17 20:29:59 +0200642 pending_encoder_creation_ =
643 (!encoder_ || encoder_config_.video_format != config.video_format ||
644 max_data_payload_length_ != max_data_payload_length);
645 encoder_config_ = std::move(config);
646 max_data_payload_length_ = max_data_payload_length;
647 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200648
Sebastian Jansson86314cf2019-09-17 20:29:59 +0200649 // Reconfigure the encoder now if the encoder has an internal source or
650 // if the frame resolution is known. Otherwise, the reconfiguration is
651 // deferred until the next frame to minimize the number of
652 // reconfigurations. The codec configuration depends on incoming video
653 // frame size.
654 if (last_frame_info_) {
655 ReconfigureEncoder();
656 } else {
657 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
658 encoder_config_.video_format);
659 if (HasInternalSource()) {
660 last_frame_info_ = VideoFrameInfo(176, 144, false);
661 ReconfigureEncoder();
662 }
663 }
664 });
perkjfa10b552016-10-02 23:45:26 -0700665}
perkj26091b12016-09-01 01:17:40 -0700666
Sergey Silkin6456e352019-07-08 17:56:40 +0200667static absl::optional<VideoEncoder::ResolutionBitrateLimits>
668GetEncoderBitrateLimits(const VideoEncoder::EncoderInfo& encoder_info,
669 int frame_size_pixels) {
670 std::vector<VideoEncoder::ResolutionBitrateLimits> bitrate_limits =
671 encoder_info.resolution_bitrate_limits;
672
673 // Sort the list of bitrate limits by resolution.
674 sort(bitrate_limits.begin(), bitrate_limits.end(),
675 [](const VideoEncoder::ResolutionBitrateLimits& lhs,
676 const VideoEncoder::ResolutionBitrateLimits& rhs) {
677 return lhs.frame_size_pixels < rhs.frame_size_pixels;
678 });
679
680 for (size_t i = 0; i < bitrate_limits.size(); ++i) {
Sergey Silkin6b2cec12019-08-09 16:04:05 +0200681 RTC_DCHECK_GT(bitrate_limits[i].min_bitrate_bps, 0);
682 RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
683 bitrate_limits[i].min_bitrate_bps);
684 RTC_DCHECK_GT(bitrate_limits[i].max_bitrate_bps,
685 bitrate_limits[i].min_start_bitrate_bps);
Sergey Silkin6456e352019-07-08 17:56:40 +0200686 if (i > 0) {
687 // The bitrate limits aren't expected to decrease with resolution.
688 RTC_DCHECK_GE(bitrate_limits[i].min_bitrate_bps,
689 bitrate_limits[i - 1].min_bitrate_bps);
690 RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
691 bitrate_limits[i - 1].min_start_bitrate_bps);
692 RTC_DCHECK_GE(bitrate_limits[i].max_bitrate_bps,
693 bitrate_limits[i - 1].max_bitrate_bps);
694 }
695
696 if (bitrate_limits[i].frame_size_pixels >= frame_size_pixels) {
697 return absl::optional<VideoEncoder::ResolutionBitrateLimits>(
698 bitrate_limits[i]);
699 }
700 }
701
702 return absl::nullopt;
703}
704
Seth Hampsoncc7125f2018-02-02 08:46:16 -0800705// TODO(bugs.webrtc.org/8807): Currently this always does a hard
706// reconfiguration, but this isn't always necessary. Add in logic to only update
707// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
708// "soft" reconfiguration.
mflodmancc3d4422017-08-03 08:27:51 -0700709void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700710 RTC_DCHECK(pending_encoder_reconfiguration_);
philipeld9cc8c02019-09-16 14:53:40 +0200711
712 if (encoder_switch_experiment_.IsPixelCountBelowThreshold(
713 last_frame_info_->width * last_frame_info_->height) &&
714 !encoder_switch_requested_ && settings_.encoder_switch_request_callback) {
715 EncoderSwitchRequestCallback::Config conf;
716 conf.codec_name = encoder_switch_experiment_.to_codec;
717 conf.param = encoder_switch_experiment_.to_param;
718 conf.value = encoder_switch_experiment_.to_value;
719 settings_.encoder_switch_request_callback->RequestEncoderSwitch(conf);
720
721 encoder_switch_requested_ = true;
722 }
723
perkjfa10b552016-10-02 23:45:26 -0700724 std::vector<VideoStream> streams =
725 encoder_config_.video_stream_factory->CreateEncoderStreams(
726 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700727
ilnik6b826ef2017-06-16 06:53:48 -0700728 // TODO(ilnik): If configured resolution is significantly less than provided,
729 // e.g. because there are not enough SSRCs for all simulcast streams,
730 // signal new resolutions via SinkWants to video source.
731
732 // Stream dimensions may be not equal to given because of a simulcast
733 // restrictions.
Steve Antonbd631a02019-03-28 10:51:27 -0700734 auto highest_stream = absl::c_max_element(
735 streams, [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) {
Florent Castelli450b5482018-11-29 17:32:47 +0100736 return std::tie(a.width, a.height) < std::tie(b.width, b.height);
737 });
738 int highest_stream_width = static_cast<int>(highest_stream->width);
739 int highest_stream_height = static_cast<int>(highest_stream->height);
ilnik6b826ef2017-06-16 06:53:48 -0700740 // Dimension may be reduced to be, e.g. divisible by 4.
741 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
742 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
743 crop_width_ = last_frame_info_->width - highest_stream_width;
744 crop_height_ = last_frame_info_->height - highest_stream_height;
745
Sergey Silkin6456e352019-07-08 17:56:40 +0200746 bool encoder_reset_required = false;
747 if (pending_encoder_creation_) {
748 // Destroy existing encoder instance before creating a new one. Otherwise
749 // attempt to create another instance will fail if encoder factory
750 // supports only single instance of encoder of given type.
751 encoder_.reset();
752
753 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
754 encoder_config_.video_format);
755 // TODO(nisse): What to do if creating the encoder fails? Crash,
756 // or just discard incoming frames?
757 RTC_CHECK(encoder_);
758
759 encoder_->SetFecControllerOverride(fec_controller_override_);
760
761 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
762 encoder_config_.video_format);
763
764 encoder_reset_required = true;
765 }
766
767 encoder_bitrate_limits_ = GetEncoderBitrateLimits(
768 encoder_->GetEncoderInfo(),
769 last_frame_info_->width * last_frame_info_->height);
770
Sergey Silkin6b2cec12019-08-09 16:04:05 +0200771 if (streams.size() == 1 && encoder_bitrate_limits_) {
772 // Use bitrate limits recommended by encoder only if app didn't set any of
773 // them.
774 if (encoder_config_.max_bitrate_bps <= 0 &&
775 (encoder_config_.simulcast_layers.empty() ||
776 encoder_config_.simulcast_layers[0].min_bitrate_bps <= 0)) {
777 streams.back().min_bitrate_bps = encoder_bitrate_limits_->min_bitrate_bps;
778 streams.back().max_bitrate_bps = encoder_bitrate_limits_->max_bitrate_bps;
779 streams.back().target_bitrate_bps =
780 std::min(streams.back().target_bitrate_bps,
781 encoder_bitrate_limits_->max_bitrate_bps);
782 }
Sergey Silkin6456e352019-07-08 17:56:40 +0200783 }
784
Erik Språng08127a92016-11-16 16:41:30 +0100785 VideoCodec codec;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800786 if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100787 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100788 }
perkjfa10b552016-10-02 23:45:26 -0700789
“Michael277a6562018-06-01 14:09:19 -0500790 // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9.
791 if (encoder_config_.codec_type == kVideoCodecVP9) {
“Michael277a6562018-06-01 14:09:19 -0500792 // Lower max bitrate to the level codec actually can produce.
Erik Språngcf9cbf52019-09-04 14:30:57 +0200793 streams[0].max_bitrate_bps =
794 std::min(streams[0].max_bitrate_bps,
795 SvcRateAllocator::GetMaxBitrate(codec).bps<int>());
“Michael277a6562018-06-01 14:09:19 -0500796 streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000;
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100797 // target_bitrate_bps specifies the maximum padding bitrate.
“Michael277a6562018-06-01 14:09:19 -0500798 streams[0].target_bitrate_bps =
Erik Språngcf9cbf52019-09-04 14:30:57 +0200799 SvcRateAllocator::GetPaddingBitrate(codec).bps<int>();
“Michael277a6562018-06-01 14:09:19 -0500800 }
801
Ilya Nikolaevskiyfbf75a72019-09-26 17:39:26 +0200802 char log_stream_buf[4 * 1024];
803 rtc::SimpleStringBuilder log_stream(log_stream_buf);
804 log_stream << "ReconfigureEncoder:\n";
805 log_stream << "Simulcast streams:\n";
806 for (size_t i = 0; i < codec.numberOfSimulcastStreams; ++i) {
807 log_stream << i << ": " << codec.simulcastStream[i].width << "x"
808 << codec.simulcastStream[i].height
809 << " fps: " << codec.simulcastStream[i].maxFramerate
810 << " min_bps: " << codec.simulcastStream[i].minBitrate
811 << " target_bps: " << codec.simulcastStream[i].targetBitrate
812 << " max_bps: " << codec.simulcastStream[i].maxBitrate
813 << " max_qp: " << codec.simulcastStream[i].qpMax
814 << " num_tl: " << codec.simulcastStream[i].numberOfTemporalLayers
815 << " active: "
816 << (codec.simulcastStream[i].active ? "true" : "false") << "\n";
817 }
818 if (encoder_config_.codec_type == kVideoCodecVP9) {
819 size_t num_spatial_layers = codec.VP9()->numberOfSpatialLayers;
820 log_stream << "Spatial layers:\n";
821 for (size_t i = 0; i < num_spatial_layers; ++i) {
822 log_stream << i << ": " << codec.spatialLayers[i].width << "x"
823 << codec.spatialLayers[i].height
824 << " fps: " << codec.spatialLayers[i].maxFramerate
825 << " min_bps: " << codec.spatialLayers[i].minBitrate
826 << " target_bps: " << codec.spatialLayers[i].targetBitrate
827 << " max_bps: " << codec.spatialLayers[i].maxBitrate
828 << " max_qp: " << codec.spatialLayers[i].qpMax
829 << " num_tl: " << codec.spatialLayers[i].numberOfTemporalLayers
830 << " active: "
831 << (codec.spatialLayers[i].active ? "true" : "false") << "\n";
832 }
833 }
834 RTC_LOG(LS_INFO) << log_stream.str();
835
perkjfa10b552016-10-02 23:45:26 -0700836 codec.startBitrate =
837 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
838 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
839 codec.expect_encode_from_texture = last_frame_info_->is_texture;
Erik Språngd7329ca2019-02-21 21:19:53 +0100840 // Make sure the start bit rate is sane...
841 RTC_DCHECK_LE(codec.startBitrate, 1000000);
sprangfda496a2017-06-15 04:21:07 -0700842 max_framerate_ = codec.maxFramerate;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200843
844 // Inform source about max configured framerate.
845 int max_framerate = 0;
846 for (const auto& stream : streams) {
847 max_framerate = std::max(stream.max_framerate, max_framerate);
848 }
849 source_proxy_->SetMaxFramerate(max_framerate);
Stefan Holmere5904162015-03-26 11:11:06 +0100850
Erik Språngb7cb7b52019-02-26 15:52:33 +0100851 if (codec.maxBitrate == 0) {
852 // max is one bit per pixel
853 codec.maxBitrate =
854 (static_cast<int>(codec.height) * static_cast<int>(codec.width) *
855 static_cast<int>(codec.maxFramerate)) /
856 1000;
857 if (codec.startBitrate > codec.maxBitrate) {
858 // But if the user tries to set a higher start bit rate we will
859 // increase the max accordingly.
860 codec.maxBitrate = codec.startBitrate;
861 }
862 }
863
864 if (codec.startBitrate > codec.maxBitrate) {
865 codec.startBitrate = codec.maxBitrate;
866 }
867
Sergey Silkin65d9c4d2019-06-12 11:02:30 +0200868 rate_allocator_ =
869 settings_.bitrate_allocator_factory->CreateVideoBitrateAllocator(codec);
870
Erik Språngb7cb7b52019-02-26 15:52:33 +0100871 // Reset (release existing encoder) if one exists and anything except
Elad Alonfb087812019-05-02 23:25:34 +0200872 // start bitrate or max framerate has changed.
Sergey Silkin6456e352019-07-08 17:56:40 +0200873 if (!encoder_reset_required) {
874 encoder_reset_required = RequiresEncoderReset(
875 codec, send_codec_, was_encode_called_since_last_initialization_);
876 }
Erik Språngb7cb7b52019-02-26 15:52:33 +0100877 send_codec_ = codec;
878
philipeld9cc8c02019-09-16 14:53:40 +0200879 encoder_switch_experiment_.SetCodec(send_codec_.codecType);
880
Niels Möller4db138e2018-04-19 09:04:13 +0200881 // Keep the same encoder, as long as the video_format is unchanged.
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100882 // Encoder creation block is split in two since EncoderInfo needed to start
883 // CPU adaptation with the correct settings should be polled after
884 // encoder_->InitEncode().
Erik Språngb7cb7b52019-02-26 15:52:33 +0100885 bool success = true;
Sergey Silkin6456e352019-07-08 17:56:40 +0200886 if (encoder_reset_required) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100887 ReleaseEncoder();
Elad Alon370f93a2019-06-11 14:57:57 +0200888 const size_t max_data_payload_length = max_data_payload_length_ > 0
889 ? max_data_payload_length_
890 : kDefaultPayloadSize;
891 if (encoder_->InitEncode(
892 &send_codec_,
893 VideoEncoder::Settings(settings_.capabilities, number_of_cores_,
894 max_data_payload_length)) != 0) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100895 RTC_LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
896 "codec type: "
897 << CodecTypeToPayloadString(send_codec_.codecType)
898 << " (" << send_codec_.codecType << ")";
899 ReleaseEncoder();
900 success = false;
901 } else {
902 encoder_initialized_ = true;
903 encoder_->RegisterEncodeCompleteCallback(this);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200904 frame_encode_metadata_writer_.OnEncoderInit(send_codec_,
905 HasInternalSource());
Erik Språng6a7baa72019-02-26 18:31:00 +0100906 }
907
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200908 frame_encode_metadata_writer_.Reset();
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100909 last_encode_info_ms_ = absl::nullopt;
Sergey Silkin5ee69672019-07-02 14:18:34 +0200910 was_encode_called_since_last_initialization_ = false;
Erik Språngb7cb7b52019-02-26 15:52:33 +0100911 }
Erik Språngd7329ca2019-02-21 21:19:53 +0100912
913 if (success) {
Erik Språngd7329ca2019-02-21 21:19:53 +0100914 next_frame_types_.clear();
915 next_frame_types_.resize(
916 std::max(static_cast<int>(codec.numberOfSimulcastStreams), 1),
Niels Möller8f7ce222019-03-21 15:43:58 +0100917 VideoFrameType::kVideoFrameKey);
Erik Språngd7329ca2019-02-21 21:19:53 +0100918 RTC_LOG(LS_VERBOSE) << " max bitrate " << codec.maxBitrate
919 << " start bitrate " << codec.startBitrate
920 << " max frame rate " << codec.maxFramerate
921 << " max payload size " << max_data_payload_length_;
922 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100923 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
Erik Språngb7cb7b52019-02-26 15:52:33 +0100924 rate_allocator_ = nullptr;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000925 }
Peter Boström905f8e72016-03-02 16:59:56 +0100926
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100927 if (pending_encoder_creation_) {
928 overuse_detector_->StopCheckForOveruse();
929 overuse_detector_->StartCheckForOveruse(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100930 &encoder_queue_,
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100931 GetCpuOveruseOptions(
932 settings_, encoder_->GetEncoderInfo().is_hardware_accelerated),
933 this);
934 pending_encoder_creation_ = false;
935 }
936
Niels Möller6bb5ab92019-01-11 11:11:10 +0100937 int num_layers;
938 if (codec.codecType == kVideoCodecVP8) {
939 num_layers = codec.VP8()->numberOfTemporalLayers;
940 } else if (codec.codecType == kVideoCodecVP9) {
941 num_layers = codec.VP9()->numberOfTemporalLayers;
Johnny Lee1a1c52b2019-02-08 14:25:40 -0500942 } else if (codec.codecType == kVideoCodecH264) {
943 num_layers = codec.H264()->numberOfTemporalLayers;
Niels Möller6bb5ab92019-01-11 11:11:10 +0100944 } else if (codec.codecType == kVideoCodecGeneric &&
945 codec.numberOfSimulcastStreams > 0) {
946 // This is mainly for unit testing, disabling frame dropping.
947 // TODO(sprang): Add a better way to disable frame dropping.
948 num_layers = codec.simulcastStream[0].numberOfTemporalLayers;
949 } else {
950 num_layers = 1;
951 }
952
953 frame_dropper_.Reset();
954 frame_dropper_.SetRates(codec.startBitrate, max_framerate_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100955 // Force-disable frame dropper if either:
956 // * We have screensharing with layers.
957 // * "WebRTC-FrameDropper" field trial is "Disabled".
958 force_disable_frame_dropper_ =
959 field_trial::IsDisabled(kFrameDropperFieldTrial) ||
960 (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing);
961
Erik Språng7ca375c2019-02-06 16:20:17 +0100962 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
963 if (rate_control_settings_.UseEncoderBitrateAdjuster()) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200964 bitrate_adjuster_ = std::make_unique<EncoderBitrateAdjuster>(codec);
Erik Språng7ca375c2019-02-06 16:20:17 +0100965 bitrate_adjuster_->OnEncoderInfo(info);
966 }
967
Erik Språng4c6ca302019-04-08 15:14:01 +0200968 if (rate_allocator_ && last_encoder_rate_settings_) {
Niels Möller6bb5ab92019-01-11 11:11:10 +0100969 // We have a new rate allocator instance and already configured target
Erik Språng4c6ca302019-04-08 15:14:01 +0200970 // bitrate. Update the rate allocation and notify observers.
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +0200971 // We must invalidate the last_encoder_rate_settings_ to ensure
972 // the changes get propagated to all listeners.
973 EncoderRateSettings rate_settings = *last_encoder_rate_settings_;
974 last_encoder_rate_settings_.reset();
975 rate_settings.framerate_fps = GetInputFramerateFps();
976
977 SetEncoderRates(UpdateBitrateAllocationAndNotifyObserver(rate_settings));
Niels Möller6bb5ab92019-01-11 11:11:10 +0100978 }
ilnik35b7de42017-03-15 04:24:21 -0700979
Niels Möller213618e2018-07-24 09:29:58 +0200980 encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
Per512ecb32016-09-23 15:52:06 +0200981
perkjfa10b552016-10-02 23:45:26 -0700982 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100983
Pera48ddb72016-09-29 11:48:50 +0200984 sink_->OnEncoderConfigurationChanged(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100985 std::move(streams), encoder_config_.content_type,
986 encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800987
Niels Möller7dc26b72017-12-06 10:27:48 +0100988 // Get the current target framerate, ie the maximum framerate as specified by
989 // the current codec configuration, or any limit imposed by cpu adaption in
990 // maintain-resolution or balanced mode. This is used to make sure overuse
991 // detection doesn't needlessly trigger in low and/or variable framerate
992 // scenarios.
993 int target_framerate = std::min(
994 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
995 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +0200996
Erik Språng7ca375c2019-02-06 16:20:17 +0100997 ConfigureQualityScaler(info);
kthelgason2bc68642017-02-07 07:02:22 -0800998}
999
Erik Språng7ca375c2019-02-06 16:20:17 +01001000void VideoStreamEncoder::ConfigureQualityScaler(
1001 const VideoEncoder::EncoderInfo& encoder_info) {
kthelgason2bc68642017-02-07 07:02:22 -08001002 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +01001003 const auto scaling_settings = encoder_info.scaling_settings;
asapersson36e9eb42017-03-31 05:29:12 -07001004 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -07001005 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +01001006 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -07001007
asapersson36e9eb42017-03-31 05:29:12 -07001008 if (quality_scaling_allowed) {
Benjamin Wright1f4173e2019-03-13 17:59:32 -07001009 if (quality_scaler_ == nullptr) {
asapersson09f05612017-05-15 23:40:18 -07001010 // Quality scaler has not already been configured.
Niels Möller225c7872018-02-22 15:03:53 +01001011
Åsa Perssona945aee2018-04-24 16:53:25 +02001012 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 12:28:07 +02001013 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 16:53:25 +02001014 if (quality_scaling_experiment_enabled_) {
1015 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
1016 encoder_config_.codec_type);
1017 }
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001018 // Since the interface is non-public, std::make_unique can't do this
Karl Wiberg918f50c2018-07-05 11:40:33 +02001019 // upcast.
Niels Möller225c7872018-02-22 15:03:53 +01001020 AdaptationObserverInterface* observer = this;
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001021 quality_scaler_ = std::make_unique<QualityScaler>(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +01001022 &encoder_queue_, observer,
1023 experimental_thresholds ? *experimental_thresholds
1024 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001025 has_seen_first_significant_bwe_change_ = false;
1026 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 01:44:11 -08001027 }
1028 } else {
1029 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001030 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -08001031 }
asapersson09f05612017-05-15 23:40:18 -07001032
Åsa Persson12314192019-06-20 15:45:07 +02001033 if (degradation_preference_ == DegradationPreference::BALANCED &&
1034 quality_scaler_ && last_frame_info_) {
1035 absl::optional<VideoEncoder::QpThresholds> thresholds =
1036 balanced_settings_.GetQpThresholds(encoder_config_.codec_type,
1037 last_frame_info_->pixel_count());
1038 if (thresholds) {
1039 quality_scaler_->SetQpThresholds(*thresholds);
1040 }
1041 }
1042
Niels Möller213618e2018-07-24 09:29:58 +02001043 encoder_stats_observer_->OnAdaptationChanged(
1044 VideoStreamEncoderObserver::AdaptationReason::kNone,
1045 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001046}
1047
mflodmancc3d4422017-08-03 08:27:51 -07001048void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -07001049 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -07001050 VideoFrame incoming_frame = video_frame;
1051
1052 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -07001053 int64_t current_time_us = clock_->TimeInMicroseconds();
1054 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
1055 // In some cases, e.g., when the frame from decoder is fed to encoder,
1056 // the timestamp may be set to the future. As the encoding pipeline assumes
1057 // capture time to be less than present time, we should reset the capture
1058 // timestamps here. Otherwise there may be issues with RTP send stream.
1059 if (incoming_frame.timestamp_us() > current_time_us)
1060 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -07001061
1062 // Capture time may come from clock with an offset and drift from clock_.
1063 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -08001064 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -07001065 capture_ntp_time_ms = video_frame.ntp_time_ms();
1066 } else if (video_frame.render_time_ms() != 0) {
1067 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
1068 } else {
nisse1c0dea82017-01-30 02:43:18 -08001069 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -07001070 }
1071 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
1072
1073 // Convert NTP time, in ms, to RTP timestamp.
1074 const int kMsToRtpTimestamp = 90;
1075 incoming_frame.set_timestamp(
1076 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
1077
1078 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
1079 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001080 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
1081 << incoming_frame.ntp_time_ms()
1082 << " <= " << last_captured_timestamp_
1083 << ") for incoming frame. Dropping.";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001084 encoder_queue_.PostTask([this, incoming_frame]() {
1085 RTC_DCHECK_RUN_ON(&encoder_queue_);
1086 accumulated_update_rect_.Union(incoming_frame.update_rect());
1087 });
perkj26091b12016-09-01 01:17:40 -07001088 return;
1089 }
1090
asapersson6ffb67d2016-09-12 00:10:45 -07001091 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -08001092 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
1093 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -07001094 log_stats = true;
1095 }
1096
perkj26091b12016-09-01 01:17:40 -07001097 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001098
1099 int64_t post_time_us = rtc::TimeMicros();
1100 ++posted_frames_waiting_for_encode_;
1101
1102 encoder_queue_.PostTask(
1103 [this, incoming_frame, post_time_us, log_stats]() {
1104 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 09:29:58 +02001105 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
1106 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001107 ++captured_frame_count_;
1108 const int posted_frames_waiting_for_encode =
1109 posted_frames_waiting_for_encode_.fetch_sub(1);
1110 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
1111 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +02001112 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001113 } else {
1114 // There is a newer frame in flight. Do not encode this frame.
1115 RTC_LOG(LS_VERBOSE)
1116 << "Incoming frame dropped due to that the encoder is blocked.";
1117 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 09:29:58 +02001118 encoder_stats_observer_->OnFrameDropped(
1119 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001120 accumulated_update_rect_.Union(incoming_frame.update_rect());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001121 }
1122 if (log_stats) {
1123 RTC_LOG(LS_INFO) << "Number of frames: captured "
1124 << captured_frame_count_
1125 << ", dropped (due to encoder blocked) "
1126 << dropped_frame_count_ << ", interval_ms "
1127 << kFrameLogIntervalMs;
1128 captured_frame_count_ = 0;
1129 dropped_frame_count_ = 0;
1130 }
1131 });
perkj26091b12016-09-01 01:17:40 -07001132}
1133
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001134void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 09:29:58 +02001135 encoder_stats_observer_->OnFrameDropped(
1136 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001137}
1138
mflodmancc3d4422017-08-03 08:27:51 -07001139bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -07001140 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +00001141 // Pause video if paused by caller or as long as the network is down or the
1142 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -07001143 // If the pacer queue has grown too large or the network is down,
Erik Språng4c6ca302019-04-08 15:14:01 +02001144 // |last_encoder_rate_settings_->encoder_target| will be 0.
1145 return !last_encoder_rate_settings_ ||
1146 last_encoder_rate_settings_->encoder_target == DataRate::Zero();
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +00001147}
1148
mflodmancc3d4422017-08-03 08:27:51 -07001149void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -07001150 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001151 // Start trace event only on the first frame after encoder is paused.
1152 if (!encoder_paused_and_dropped_frame_) {
1153 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
1154 }
1155 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001156}
1157
mflodmancc3d4422017-08-03 08:27:51 -07001158void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -07001159 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001160 // End trace event on first frame after encoder resumes, if frame was dropped.
1161 if (encoder_paused_and_dropped_frame_) {
1162 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
1163 }
1164 encoder_paused_and_dropped_frame_ = false;
1165}
1166
Erik Språng4c6ca302019-04-08 15:14:01 +02001167VideoStreamEncoder::EncoderRateSettings
1168VideoStreamEncoder::UpdateBitrateAllocationAndNotifyObserver(
1169 const EncoderRateSettings& rate_settings) {
1170 VideoBitrateAllocation new_allocation;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001171 // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
1172 // might cap the bitrate to the min bitrate configured.
Erik Språng4c6ca302019-04-08 15:14:01 +02001173 if (rate_allocator_ && rate_settings.encoder_target > DataRate::Zero()) {
Florent Castelli8bbdb5b2019-08-02 15:16:28 +02001174 new_allocation = rate_allocator_->Allocate(VideoBitrateAllocationParameters(
Florent Castellia8336d32019-09-09 13:36:55 +02001175 rate_settings.encoder_target, rate_settings.stable_encoder_target,
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001176 rate_settings.framerate_fps));
Niels Möller6bb5ab92019-01-11 11:11:10 +01001177 }
1178
Erik Språng4c6ca302019-04-08 15:14:01 +02001179 if (bitrate_observer_ && new_allocation.get_sum_bps() > 0) {
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001180 if (encoder_ && encoder_initialized_) {
1181 // Avoid too old encoder_info_.
1182 const int64_t kMaxDiffMs = 100;
1183 const bool updated_recently =
1184 (last_encode_info_ms_ && ((clock_->TimeInMilliseconds() -
1185 *last_encode_info_ms_) < kMaxDiffMs));
1186 // Update allocation according to info from encoder.
1187 bitrate_observer_->OnBitrateAllocationUpdated(
1188 UpdateAllocationFromEncoderInfo(
Erik Språng4c6ca302019-04-08 15:14:01 +02001189 new_allocation,
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001190 updated_recently ? encoder_info_ : encoder_->GetEncoderInfo()));
1191 } else {
Erik Språng4c6ca302019-04-08 15:14:01 +02001192 bitrate_observer_->OnBitrateAllocationUpdated(new_allocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001193 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001194 }
1195
Erik Språng3d11e2f2019-04-15 14:48:30 +02001196 EncoderRateSettings new_rate_settings = rate_settings;
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001197 new_rate_settings.bitrate = new_allocation;
Erik Språng5056af02019-09-02 15:53:11 +02001198 // VideoBitrateAllocator subclasses may allocate a bitrate higher than the
1199 // target in order to sustain the min bitrate of the video codec. In this
1200 // case, make sure the bandwidth allocation is at least equal the allocation
1201 // as that is part of the document contract for that field.
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001202 new_rate_settings.bandwidth_allocation =
1203 std::max(new_rate_settings.bandwidth_allocation,
1204 DataRate::bps(new_rate_settings.bitrate.get_sum_bps()));
Erik Språng3d11e2f2019-04-15 14:48:30 +02001205
Erik Språng7ca375c2019-02-06 16:20:17 +01001206 if (bitrate_adjuster_) {
Erik Språng0e1a1f92019-02-18 18:45:13 +01001207 VideoBitrateAllocation adjusted_allocation =
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001208 bitrate_adjuster_->AdjustRateAllocation(new_rate_settings);
Erik Språng4c6ca302019-04-08 15:14:01 +02001209 RTC_LOG(LS_VERBOSE) << "Adjusting allocation, fps = "
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001210 << rate_settings.framerate_fps << ", from "
Erik Språng4c6ca302019-04-08 15:14:01 +02001211 << new_allocation.ToString() << ", to "
Erik Språng0e1a1f92019-02-18 18:45:13 +01001212 << adjusted_allocation.ToString();
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001213 new_rate_settings.bitrate = adjusted_allocation;
Erik Språng7ca375c2019-02-06 16:20:17 +01001214 }
Erik Språng4c6ca302019-04-08 15:14:01 +02001215
Evan Shrubsolecc62b162019-09-09 11:26:45 +02001216 encoder_stats_observer_->OnBitrateAllocationUpdated(
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001217 send_codec_, new_rate_settings.bitrate);
Evan Shrubsolecc62b162019-09-09 11:26:45 +02001218
Erik Språng3d11e2f2019-04-15 14:48:30 +02001219 return new_rate_settings;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001220}
1221
1222uint32_t VideoStreamEncoder::GetInputFramerateFps() {
1223 const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
Erik Språngd7329ca2019-02-21 21:19:53 +01001224 absl::optional<uint32_t> input_fps =
1225 input_framerate_.Rate(clock_->TimeInMilliseconds());
1226 if (!input_fps || *input_fps == 0) {
1227 return default_fps;
1228 }
1229 return *input_fps;
1230}
1231
1232void VideoStreamEncoder::SetEncoderRates(
Erik Språng4c6ca302019-04-08 15:14:01 +02001233 const EncoderRateSettings& rate_settings) {
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001234 RTC_DCHECK_GT(rate_settings.framerate_fps, 0.0);
1235 const bool settings_changes = !last_encoder_rate_settings_ ||
1236 rate_settings != *last_encoder_rate_settings_;
1237 if (settings_changes) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001238 last_encoder_rate_settings_ = rate_settings;
1239 }
1240
Erik Språng6a7baa72019-02-26 18:31:00 +01001241 if (!encoder_) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001242 return;
1243 }
1244
1245 // |bitrate_allocation| is 0 it means that the network is down or the send
1246 // pacer is full. We currently only report this if the encoder has an internal
1247 // source. If the encoder does not have an internal source, higher levels
1248 // are expected to not call AddVideoFrame. We do this since its unclear
1249 // how current encoder implementations behave when given a zero target
1250 // bitrate.
1251 // TODO(perkj): Make sure all known encoder implementations handle zero
1252 // target bitrate and remove this check.
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001253 if (!HasInternalSource() && rate_settings.bitrate.get_sum_bps() == 0) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001254 return;
1255 }
1256
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001257 if (settings_changes) {
1258 encoder_->SetRates(rate_settings);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001259 frame_encode_metadata_writer_.OnSetRates(
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001260 rate_settings.bitrate,
1261 static_cast<uint32_t>(rate_settings.framerate_fps + 0.5));
Erik Språng6a7baa72019-02-26 18:31:00 +01001262 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001263}
1264
Sebastian Janssona3177052018-04-10 13:05:49 +02001265void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
1266 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -07001267 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -08001268
Per21d45d22016-10-30 21:37:57 +01001269 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -07001270 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -07001271 video_frame.is_texture() != last_frame_info_->is_texture) {
1272 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +01001273 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
1274 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +01001275 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
1276 << last_frame_info_->width << "x"
1277 << last_frame_info_->height
1278 << ", texture=" << last_frame_info_->is_texture << ".";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001279 // Force full frame update, since resolution has changed.
1280 accumulated_update_rect_ =
1281 VideoFrame::UpdateRect{0, 0, video_frame.width(), video_frame.height()};
perkjfa10b552016-10-02 23:45:26 -07001282 }
1283
Niels Möller4db138e2018-04-19 09:04:13 +02001284 // We have to create then encoder before the frame drop logic,
1285 // because the latter depends on encoder_->GetScalingSettings.
1286 // According to the testcase
1287 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
1288 // from GetScalingSettings should enable or disable the frame drop.
1289
Erik Språnga8d48ab2019-02-08 14:17:40 +01001290 // Update input frame rate before we start using it. If we update it after
Erik Språngd7329ca2019-02-21 21:19:53 +01001291 // any potential frame drop we are going to artificially increase frame sizes.
1292 // Poll the rate before updating, otherwise we risk the rate being estimated
1293 // a little too high at the start of the call when then window is small.
Niels Möller6bb5ab92019-01-11 11:11:10 +01001294 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språngd7329ca2019-02-21 21:19:53 +01001295 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001296
Niels Möller4db138e2018-04-19 09:04:13 +02001297 int64_t now_ms = clock_->TimeInMilliseconds();
1298 if (pending_encoder_reconfiguration_) {
1299 ReconfigureEncoder();
1300 last_parameters_update_ms_.emplace(now_ms);
1301 } else if (!last_parameters_update_ms_ ||
1302 now_ms - *last_parameters_update_ms_ >=
Niels Möllerfe407b72019-09-10 10:48:48 +02001303 kParameterUpdateIntervalMs) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001304 if (last_encoder_rate_settings_) {
1305 // Clone rate settings before update, so that SetEncoderRates() will
1306 // actually detect the change between the input and
1307 // |last_encoder_rate_setings_|, triggering the call to SetRate() on the
1308 // encoder.
1309 EncoderRateSettings new_rate_settings = *last_encoder_rate_settings_;
Evan Shrubsoleb6a45dd2019-09-18 13:46:06 +00001310 new_rate_settings.framerate_fps = static_cast<double>(framerate_fps);
Erik Språng4c6ca302019-04-08 15:14:01 +02001311 SetEncoderRates(
1312 UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
1313 }
Niels Möller4db138e2018-04-19 09:04:13 +02001314 last_parameters_update_ms_.emplace(now_ms);
1315 }
1316
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001317 // Because pending frame will be dropped in any case, we need to
1318 // remember its updated region.
1319 if (pending_frame_) {
1320 encoder_stats_observer_->OnFrameDropped(
1321 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
1322 accumulated_update_rect_.Union(pending_frame_->update_rect());
1323 }
1324
Sebastian Janssona3177052018-04-10 13:05:49 +02001325 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001326 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 08:49:53 +01001327 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -08001328 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 08:49:53 +01001329 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
Niels Möller213618e2018-07-24 09:29:58 +02001330 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 08:49:53 +01001331 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001332 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001333 // Storing references to a native buffer risks blocking frame capture.
1334 if (video_frame.video_frame_buffer()->type() !=
1335 VideoFrameBuffer::Type::kNative) {
1336 pending_frame_ = video_frame;
1337 pending_frame_post_time_us_ = time_when_posted_us;
1338 } else {
1339 // Ensure that any previously stored frame is dropped.
1340 pending_frame_.reset();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001341 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001342 }
kthelgason2bc68642017-02-07 07:02:22 -08001343 return;
1344 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001345 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -08001346
perkj26091b12016-09-01 01:17:40 -07001347 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001348 // Storing references to a native buffer risks blocking frame capture.
1349 if (video_frame.video_frame_buffer()->type() !=
1350 VideoFrameBuffer::Type::kNative) {
1351 if (pending_frame_)
1352 TraceFrameDropStart();
1353 pending_frame_ = video_frame;
1354 pending_frame_post_time_us_ = time_when_posted_us;
1355 } else {
1356 // Ensure that any previously stored frame is dropped.
1357 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +02001358 TraceFrameDropStart();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001359 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001360 }
perkj26091b12016-09-01 01:17:40 -07001361 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001362 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001363
1364 pending_frame_.reset();
Niels Möller6bb5ab92019-01-11 11:11:10 +01001365
1366 frame_dropper_.Leak(framerate_fps);
1367 // Frame dropping is enabled iff frame dropping is not force-disabled, and
1368 // rate controller is not trusted.
1369 const bool frame_dropping_enabled =
1370 !force_disable_frame_dropper_ &&
1371 !encoder_info_.has_trusted_rate_controller;
1372 frame_dropper_.Enable(frame_dropping_enabled);
1373 if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001374 RTC_LOG(LS_VERBOSE)
1375 << "Drop Frame: "
1376 << "target bitrate "
1377 << (last_encoder_rate_settings_
1378 ? last_encoder_rate_settings_->encoder_target.bps()
1379 : 0)
1380 << ", input frame rate " << framerate_fps;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001381 OnDroppedFrame(
1382 EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001383 accumulated_update_rect_.Union(video_frame.update_rect());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001384 return;
1385 }
1386
Sebastian Janssona3177052018-04-10 13:05:49 +02001387 EncodeVideoFrame(video_frame, time_when_posted_us);
1388}
1389
1390void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
1391 int64_t time_when_posted_us) {
1392 RTC_DCHECK_RUN_ON(&encoder_queue_);
philipele8ed8302019-07-03 11:53:48 +02001393
1394 // If the encoder fail we can't continue to encode frames. When this happens
1395 // the WebrtcVideoSender is notified and the whole VideoSendStream is
1396 // recreated.
1397 if (encoder_failed_)
1398 return;
1399
perkj26091b12016-09-01 01:17:40 -07001400 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +00001401
Ilya Nikolaevskiyabd9e0f2019-09-25 16:05:47 +02001402 // Encoder metadata needs to be updated before encode complete callback.
1403 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
1404 if (info.implementation_name != encoder_info_.implementation_name) {
1405 encoder_stats_observer_->OnEncoderImplementationChanged(
1406 info.implementation_name);
1407 if (bitrate_adjuster_) {
1408 // Encoder implementation changed, reset overshoot detector states.
1409 bitrate_adjuster_->Reset();
1410 }
1411 }
1412
1413 if (bitrate_adjuster_) {
1414 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1415 if (info.fps_allocation[si] != encoder_info_.fps_allocation[si]) {
1416 bitrate_adjuster_->OnEncoderInfo(info);
1417 break;
1418 }
1419 }
1420 }
1421 encoder_info_ = info;
1422 last_encode_info_ms_ = clock_->TimeInMilliseconds();
1423
ilnik6b826ef2017-06-16 06:53:48 -07001424 VideoFrame out_frame(video_frame);
Ilya Nikolaevskiyabd9e0f2019-09-25 16:05:47 +02001425
1426 const VideoFrameBuffer::Type buffer_type =
1427 out_frame.video_frame_buffer()->type();
1428 const bool is_buffer_type_supported =
1429 buffer_type == VideoFrameBuffer::Type::kI420 ||
1430 (buffer_type == VideoFrameBuffer::Type::kNative &&
1431 info.supports_native_handle);
1432
1433 if (!is_buffer_type_supported) {
1434 // This module only supports software encoding.
1435 rtc::scoped_refptr<I420BufferInterface> converted_buffer(
1436 out_frame.video_frame_buffer()->ToI420());
1437
1438 if (!converted_buffer) {
1439 RTC_LOG(LS_ERROR) << "Frame conversion failed, dropping frame.";
1440 return;
1441 }
1442
1443 VideoFrame::UpdateRect update_rect = out_frame.update_rect();
1444 if (!update_rect.IsEmpty() &&
1445 out_frame.video_frame_buffer()->GetI420() == nullptr) {
1446 // UpdatedRect is reset to full update if it's not empty, and buffer was
1447 // converted, therefore we can't guarantee that pixels outside of
1448 // UpdateRect didn't change comparing to the previous frame.
1449 update_rect =
1450 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1451 }
1452
1453 out_frame.set_video_frame_buffer(converted_buffer);
1454 out_frame.set_update_rect(update_rect);
1455 }
1456
ilnik6b826ef2017-06-16 06:53:48 -07001457 // Crop frame if needed.
Ilya Nikolaevskiyabd9e0f2019-09-25 16:05:47 +02001458 if ((crop_width_ > 0 || crop_height_ > 0) &&
1459 out_frame.video_frame_buffer()->type() !=
1460 VideoFrameBuffer::Type::kNative) {
Noah Richards51db4212019-06-12 06:59:12 -07001461 // If the frame can't be converted to I420, drop it.
1462 auto i420_buffer = video_frame.video_frame_buffer()->ToI420();
1463 if (!i420_buffer) {
1464 RTC_LOG(LS_ERROR) << "Frame conversion for crop failed, dropping frame.";
1465 return;
1466 }
ilnik6b826ef2017-06-16 06:53:48 -07001467 int cropped_width = video_frame.width() - crop_width_;
1468 int cropped_height = video_frame.height() - crop_height_;
1469 rtc::scoped_refptr<I420Buffer> cropped_buffer =
1470 I420Buffer::Create(cropped_width, cropped_height);
1471 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
1472 // happen after SinkWants signaled correctly from ReconfigureEncoder.
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001473 VideoFrame::UpdateRect update_rect = video_frame.update_rect();
ilnik6b826ef2017-06-16 06:53:48 -07001474 if (crop_width_ < 4 && crop_height_ < 4) {
Noah Richards51db4212019-06-12 06:59:12 -07001475 cropped_buffer->CropAndScaleFrom(*i420_buffer, crop_width_ / 2,
1476 crop_height_ / 2, cropped_width,
1477 cropped_height);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001478 update_rect.offset_x -= crop_width_ / 2;
1479 update_rect.offset_y -= crop_height_ / 2;
1480 update_rect.Intersect(
1481 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height});
1482
ilnik6b826ef2017-06-16 06:53:48 -07001483 } else {
Noah Richards51db4212019-06-12 06:59:12 -07001484 cropped_buffer->ScaleFrom(*i420_buffer);
Ilya Nikolaevskiy1c90cab2019-03-07 15:30:58 +01001485 if (!update_rect.IsEmpty()) {
1486 // Since we can't reason about pixels after scaling, we invalidate whole
1487 // picture, if anything changed.
1488 update_rect =
1489 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height};
1490 }
ilnik6b826ef2017-06-16 06:53:48 -07001491 }
Ilya Nikolaevskiy4fc08552019-06-05 15:59:12 +02001492 out_frame.set_video_frame_buffer(cropped_buffer);
1493 out_frame.set_update_rect(update_rect);
ilnik6b826ef2017-06-16 06:53:48 -07001494 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001495 // Since accumulated_update_rect_ is constructed before cropping,
1496 // we can't trust it. If any changes were pending, we invalidate whole
1497 // frame here.
1498 if (!accumulated_update_rect_.IsEmpty()) {
1499 accumulated_update_rect_ =
1500 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1501 }
1502 }
1503
1504 if (!accumulated_update_rect_.IsEmpty()) {
1505 accumulated_update_rect_.Union(out_frame.update_rect());
1506 accumulated_update_rect_.Intersect(
1507 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()});
1508 out_frame.set_update_rect(accumulated_update_rect_);
1509 accumulated_update_rect_.MakeEmptyUpdate();
ilnik6b826ef2017-06-16 06:53:48 -07001510 }
1511
Magnus Jedvert26679d62015-04-07 14:07:41 +02001512 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +00001513 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +00001514
Niels Möller7dc26b72017-12-06 10:27:48 +01001515 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -07001516
Ilya Nikolaevskiyabd9e0f2019-09-25 16:05:47 +02001517 RTC_DCHECK_LE(send_codec_.width, out_frame.width());
1518 RTC_DCHECK_LE(send_codec_.height, out_frame.height());
1519 // Native frames should be scaled by the client.
1520 // For internal encoders we scale everything in one place here.
1521 RTC_DCHECK((out_frame.video_frame_buffer()->type() ==
1522 VideoFrameBuffer::Type::kNative) ||
1523 (send_codec_.width == out_frame.width() &&
1524 send_codec_.height == out_frame.height()));
Erik Språng6a7baa72019-02-26 18:31:00 +01001525
1526 TRACE_EVENT1("webrtc", "VCMGenericEncoder::Encode", "timestamp",
1527 out_frame.timestamp());
1528
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001529 frame_encode_metadata_writer_.OnEncodeStarted(out_frame);
Erik Språng6a7baa72019-02-26 18:31:00 +01001530
Niels Möllerc8d2e732019-03-06 12:00:33 +01001531 const int32_t encode_status = encoder_->Encode(out_frame, &next_frame_types_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001532 was_encode_called_since_last_initialization_ = true;
Erik Språng6a7baa72019-02-26 18:31:00 +01001533
Erik Språngd7329ca2019-02-21 21:19:53 +01001534 if (encode_status < 0) {
philipele8ed8302019-07-03 11:53:48 +02001535 if (encode_status == WEBRTC_VIDEO_CODEC_ENCODER_FAILURE) {
1536 RTC_LOG(LS_ERROR) << "Encoder failed, failing encoder format: "
1537 << encoder_config_.video_format.ToString();
philipeld9cc8c02019-09-16 14:53:40 +02001538 if (settings_.encoder_switch_request_callback) {
philipele8ed8302019-07-03 11:53:48 +02001539 encoder_failed_ = true;
philipeld9cc8c02019-09-16 14:53:40 +02001540 settings_.encoder_switch_request_callback->RequestEncoderFallback();
philipele8ed8302019-07-03 11:53:48 +02001541 } else {
1542 RTC_LOG(LS_ERROR)
1543 << "Encoder failed but no encoder fallback callback is registered";
1544 }
1545 } else {
1546 RTC_LOG(LS_ERROR) << "Failed to encode frame. Error code: "
1547 << encode_status;
1548 }
1549
Erik Språngd7329ca2019-02-21 21:19:53 +01001550 return;
1551 }
1552
1553 for (auto& it : next_frame_types_) {
Niels Möller8f7ce222019-03-21 15:43:58 +01001554 it = VideoFrameType::kVideoFrameDelta;
Erik Språngd7329ca2019-02-21 21:19:53 +01001555 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001556}
niklase@google.com470e71d2011-07-07 08:21:25 +00001557
mflodmancc3d4422017-08-03 08:27:51 -07001558void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -07001559 if (!encoder_queue_.IsCurrent()) {
1560 encoder_queue_.PostTask([this] { SendKeyFrame(); });
1561 return;
1562 }
1563 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +01001564 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Erik Språngd7329ca2019-02-21 21:19:53 +01001565 RTC_DCHECK(!next_frame_types_.empty());
Sergey Silkine62a08a2019-05-13 13:45:39 +02001566
1567 // TODO(webrtc:10615): Map keyframe request to spatial layer.
1568 std::fill(next_frame_types_.begin(), next_frame_types_.end(),
1569 VideoFrameType::kVideoFrameKey);
1570
Erik Språngd7329ca2019-02-21 21:19:53 +01001571 if (HasInternalSource()) {
1572 // Try to request the frame if we have an external encoder with
1573 // internal source since AddVideoFrame never will be called.
Erik Språng6a7baa72019-02-26 18:31:00 +01001574
1575 // TODO(nisse): Used only with internal source. Delete as soon as
1576 // that feature is removed. The only implementation I've been able
1577 // to find ignores what's in the frame. With one exception: It seems
1578 // a few test cases, e.g.,
1579 // VideoSendStreamTest.VideoSendStreamStopSetEncoderRateToZero, set
1580 // internal_source to true and use FakeEncoder. And the latter will
1581 // happily encode this 1x1 frame and pass it on down the pipeline.
1582 if (encoder_->Encode(VideoFrame::Builder()
1583 .set_video_frame_buffer(I420Buffer::Create(1, 1))
1584 .set_rotation(kVideoRotation_0)
1585 .set_timestamp_us(0)
1586 .build(),
Erik Språng6a7baa72019-02-26 18:31:00 +01001587 &next_frame_types_) == WEBRTC_VIDEO_CODEC_OK) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001588 // Try to remove just-performed keyframe request, if stream still exists.
Sergey Silkine62a08a2019-05-13 13:45:39 +02001589 std::fill(next_frame_types_.begin(), next_frame_types_.end(),
1590 VideoFrameType::kVideoFrameDelta);
Erik Språngd7329ca2019-02-21 21:19:53 +01001591 }
1592 }
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00001593}
1594
Elad Alonb6ef99b2019-04-10 16:37:07 +02001595void VideoStreamEncoder::OnLossNotification(
1596 const VideoEncoder::LossNotification& loss_notification) {
1597 if (!encoder_queue_.IsCurrent()) {
1598 encoder_queue_.PostTask(
1599 [this, loss_notification] { OnLossNotification(loss_notification); });
1600 return;
1601 }
1602
1603 RTC_DCHECK_RUN_ON(&encoder_queue_);
1604 if (encoder_) {
1605 encoder_->OnLossNotification(loss_notification);
1606 }
1607}
1608
mflodmancc3d4422017-08-03 08:27:51 -07001609EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001610 const EncodedImage& encoded_image,
1611 const CodecSpecificInfo* codec_specific_info,
1612 const RTPFragmentationHeader* fragmentation) {
Erik Språng6a7baa72019-02-26 18:31:00 +01001613 TRACE_EVENT_INSTANT1("webrtc", "VCMEncodedFrameCallback::Encoded",
1614 "timestamp", encoded_image.Timestamp());
1615 const size_t spatial_idx = encoded_image.SpatialIndex().value_or(0);
1616 EncodedImage image_copy(encoded_image);
1617
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001618 frame_encode_metadata_writer_.FillTimingInfo(spatial_idx, &image_copy);
Erik Språng6a7baa72019-02-26 18:31:00 +01001619
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001620 std::unique_ptr<RTPFragmentationHeader> fragmentation_copy =
1621 frame_encode_metadata_writer_.UpdateBitstream(codec_specific_info,
1622 fragmentation, &image_copy);
1623
Erik Språng6a7baa72019-02-26 18:31:00 +01001624 // Piggyback ALR experiment group id and simulcast id into the content type.
1625 const uint8_t experiment_id =
1626 experiment_groups_[videocontenttypehelpers::IsScreenshare(
1627 image_copy.content_type_)];
1628
1629 // TODO(ilnik): This will force content type extension to be present even
1630 // for realtime video. At the expense of miniscule overhead we will get
1631 // sliced receive statistics.
1632 RTC_CHECK(videocontenttypehelpers::SetExperimentId(&image_copy.content_type_,
1633 experiment_id));
1634 // We count simulcast streams from 1 on the wire. That's why we set simulcast
1635 // id in content type to +1 of that is actual simulcast index. This is because
1636 // value 0 on the wire is reserved for 'no simulcast stream specified'.
1637 RTC_CHECK(videocontenttypehelpers::SetSimulcastId(
1638 &image_copy.content_type_, static_cast<uint8_t>(spatial_idx + 1)));
1639
perkj26091b12016-09-01 01:17:40 -07001640 // Encoded is called on whatever thread the real encoder implementation run
1641 // on. In the case of hardware encoders, there might be several encoders
1642 // running in parallel on different threads.
Erik Språng6a7baa72019-02-26 18:31:00 +01001643 encoder_stats_observer_->OnSendEncodedImage(image_copy, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -07001644
philipelda5aa4d2019-04-26 13:37:37 +02001645 // The simulcast id is signaled in the SpatialIndex. This makes it impossible
1646 // to do simulcast for codecs that actually support spatial layers since we
1647 // can't distinguish between an actual spatial layer and a simulcast stream.
1648 // TODO(bugs.webrtc.org/10520): Signal the simulcast id explicitly.
1649 int simulcast_id = 0;
1650 if (codec_specific_info &&
1651 (codec_specific_info->codecType == kVideoCodecVP8 ||
1652 codec_specific_info->codecType == kVideoCodecH264 ||
1653 codec_specific_info->codecType == kVideoCodecGeneric)) {
1654 simulcast_id = encoded_image.SpatialIndex().value_or(0);
1655 }
1656
1657 std::unique_ptr<CodecSpecificInfo> codec_info_copy;
1658 {
1659 rtc::CritScope cs(&encoded_image_lock_);
1660
1661 if (codec_specific_info && codec_specific_info->generic_frame_info) {
1662 codec_info_copy =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001663 std::make_unique<CodecSpecificInfo>(*codec_specific_info);
philipelda5aa4d2019-04-26 13:37:37 +02001664 GenericFrameInfo& generic_info = *codec_info_copy->generic_frame_info;
1665 generic_info.frame_id = next_frame_id_++;
1666
1667 if (encoder_buffer_state_.size() <= static_cast<size_t>(simulcast_id)) {
1668 RTC_LOG(LS_ERROR) << "At most " << encoder_buffer_state_.size()
1669 << " simulcast streams supported.";
1670 } else {
1671 std::array<int64_t, kMaxEncoderBuffers>& state =
1672 encoder_buffer_state_[simulcast_id];
1673 for (const CodecBufferUsage& buffer : generic_info.encoder_buffers) {
1674 if (state.size() <= static_cast<size_t>(buffer.id)) {
1675 RTC_LOG(LS_ERROR)
1676 << "At most " << state.size() << " encoder buffers supported.";
1677 break;
1678 }
1679
1680 if (buffer.referenced) {
1681 int64_t diff = generic_info.frame_id - state[buffer.id];
1682 if (diff <= 0) {
1683 RTC_LOG(LS_ERROR) << "Invalid frame diff: " << diff << ".";
1684 } else if (absl::c_find(generic_info.frame_diffs, diff) ==
1685 generic_info.frame_diffs.end()) {
1686 generic_info.frame_diffs.push_back(diff);
1687 }
1688 }
1689
1690 if (buffer.updated)
1691 state[buffer.id] = generic_info.frame_id;
1692 }
1693 }
1694 }
1695 }
1696
1697 EncodedImageCallback::Result result = sink_->OnEncodedImage(
1698 image_copy, codec_info_copy ? codec_info_copy.get() : codec_specific_info,
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001699 fragmentation_copy ? fragmentation_copy.get() : fragmentation);
perkjbc75d972016-05-02 06:31:25 -07001700
Erik Språng7ca375c2019-02-06 16:20:17 +01001701 // We are only interested in propagating the meta-data about the image, not
1702 // encoded data itself, to the post encode function. Since we cannot be sure
1703 // the pointer will still be valid when run on the task queue, set it to null.
Erik Språng6a7baa72019-02-26 18:31:00 +01001704 image_copy.set_buffer(nullptr, 0);
Niels Möller83dbeac2017-12-14 16:39:44 +01001705
Erik Språng7ca375c2019-02-06 16:20:17 +01001706 int temporal_index = 0;
1707 if (codec_specific_info) {
1708 if (codec_specific_info->codecType == kVideoCodecVP9) {
1709 temporal_index = codec_specific_info->codecSpecific.VP9.temporal_idx;
1710 } else if (codec_specific_info->codecType == kVideoCodecVP8) {
1711 temporal_index = codec_specific_info->codecSpecific.VP8.temporalIdx;
1712 }
1713 }
1714 if (temporal_index == kNoTemporalIdx) {
1715 temporal_index = 0;
Niels Möller83dbeac2017-12-14 16:39:44 +01001716 }
1717
Erik Språng982dc792019-03-13 16:33:02 +01001718 RunPostEncode(image_copy, rtc::TimeMicros(), temporal_index);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001719
1720 if (result.error == Result::OK) {
1721 // In case of an internal encoder running on a separate thread, the
1722 // decision to drop a frame might be a frame late and signaled via
1723 // atomic flag. This is because we can't easily wait for the worker thread
1724 // without risking deadlocks, eg during shutdown when the worker thread
1725 // might be waiting for the internal encoder threads to stop.
1726 if (pending_frame_drops_.load() > 0) {
1727 int pending_drops = pending_frame_drops_.fetch_sub(1);
1728 RTC_DCHECK_GT(pending_drops, 0);
1729 result.drop_next_frame = true;
1730 }
1731 }
perkj803d97f2016-11-01 11:45:46 -07001732
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001733 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001734}
1735
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001736void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
1737 switch (reason) {
1738 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 09:29:58 +02001739 encoder_stats_observer_->OnFrameDropped(
1740 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001741 encoder_queue_.PostTask([this] {
1742 RTC_DCHECK_RUN_ON(&encoder_queue_);
1743 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +02001744 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001745 });
1746 break;
1747 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 09:29:58 +02001748 encoder_stats_observer_->OnFrameDropped(
1749 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 16:53:25 +02001750 encoder_queue_.PostTask([this] {
1751 RTC_DCHECK_RUN_ON(&encoder_queue_);
1752 if (quality_scaler_)
1753 quality_scaler_->ReportDroppedFrameByEncoder();
1754 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001755 break;
1756 }
kthelgason876222f2016-11-29 01:44:11 -08001757}
1758
Erik Språng610c7632019-03-06 15:37:33 +01001759void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate,
Florent Castellia8336d32019-09-09 13:36:55 +02001760 DataRate stable_target_bitrate,
Erik Språng4c6ca302019-04-08 15:14:01 +02001761 DataRate link_allocation,
mflodmancc3d4422017-08-03 08:27:51 -07001762 uint8_t fraction_lost,
1763 int64_t round_trip_time_ms) {
Sebastian Jansson5a000162019-04-12 11:21:32 +02001764 RTC_DCHECK_GE(link_allocation, target_bitrate);
perkj26091b12016-09-01 01:17:40 -07001765 if (!encoder_queue_.IsCurrent()) {
Florent Castellia8336d32019-09-09 13:36:55 +02001766 encoder_queue_.PostTask([this, target_bitrate, stable_target_bitrate,
1767 link_allocation, fraction_lost,
1768 round_trip_time_ms] {
1769 OnBitrateUpdated(target_bitrate, stable_target_bitrate, link_allocation,
1770 fraction_lost, round_trip_time_ms);
Erik Språng610c7632019-03-06 15:37:33 +01001771 });
perkj26091b12016-09-01 01:17:40 -07001772 return;
1773 }
1774 RTC_DCHECK_RUN_ON(&encoder_queue_);
philipeld9cc8c02019-09-16 14:53:40 +02001775
1776 if (encoder_switch_experiment_.IsBitrateBelowThreshold(target_bitrate) &&
1777 settings_.encoder_switch_request_callback && !encoder_switch_requested_) {
1778 EncoderSwitchRequestCallback::Config conf;
1779 conf.codec_name = encoder_switch_experiment_.to_codec;
1780 conf.param = encoder_switch_experiment_.to_param;
1781 conf.value = encoder_switch_experiment_.to_value;
1782 settings_.encoder_switch_request_callback->RequestEncoderSwitch(conf);
1783
1784 encoder_switch_requested_ = true;
1785 }
1786
perkj26091b12016-09-01 01:17:40 -07001787 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
1788
Erik Språng610c7632019-03-06 15:37:33 +01001789 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << target_bitrate.bps()
Florent Castellia8336d32019-09-09 13:36:55 +02001790 << " stable bitrate = " << stable_target_bitrate.bps()
Erik Språng4c6ca302019-04-08 15:14:01 +02001791 << " link allocation bitrate = " << link_allocation.bps()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001792 << " packet loss " << static_cast<int>(fraction_lost)
1793 << " rtt " << round_trip_time_ms;
Åsa Persson139f4dc2019-08-02 09:29:58 +02001794
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001795 // On significant changes to BWE at the start of the call,
1796 // enable frame drops to quickly react to jumps in available bandwidth.
1797 if (encoder_start_bitrate_bps_ != 0 &&
1798 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
1799 initial_framedrop_on_bwe_enabled_ &&
Erik Språng610c7632019-03-06 15:37:33 +01001800 abs_diff(target_bitrate.bps(), encoder_start_bitrate_bps_) >=
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001801 kFramedropThreshold * encoder_start_bitrate_bps_) {
1802 // Reset initial framedrop feature when first real BW estimate arrives.
1803 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
1804 // without an actual BW estimate.
1805 initial_framedrop_ = 0;
1806 has_seen_first_significant_bwe_change_ = true;
1807 }
Åsa Persson139f4dc2019-08-02 09:29:58 +02001808 if (set_start_bitrate_bps_ > 0 && !has_seen_first_bwe_drop_ &&
1809 quality_scaler_ && quality_scaler_settings_.InitialBitrateIntervalMs() &&
1810 quality_scaler_settings_.InitialBitrateFactor()) {
1811 int64_t diff_ms = clock_->TimeInMilliseconds() - set_start_bitrate_time_ms_;
1812 if (diff_ms < quality_scaler_settings_.InitialBitrateIntervalMs().value() &&
1813 (target_bitrate.bps() <
1814 (set_start_bitrate_bps_ *
1815 quality_scaler_settings_.InitialBitrateFactor().value()))) {
1816 RTC_LOG(LS_INFO) << "Reset initial_framedrop_. Start bitrate: "
1817 << set_start_bitrate_bps_
1818 << ", target bitrate: " << target_bitrate.bps();
1819 initial_framedrop_ = 0;
1820 has_seen_first_bwe_drop_ = true;
1821 }
1822 }
perkj26091b12016-09-01 01:17:40 -07001823
Elad Aloncde8ab22019-03-20 11:56:20 +01001824 if (encoder_) {
1825 encoder_->OnPacketLossRateUpdate(static_cast<float>(fraction_lost) / 256.f);
1826 encoder_->OnRttUpdate(round_trip_time_ms);
1827 }
1828
Niels Möller6bb5ab92019-01-11 11:11:10 +01001829 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språng610c7632019-03-06 15:37:33 +01001830 frame_dropper_.SetRates((target_bitrate.bps() + 500) / 1000, framerate_fps);
Erik Språng4c6ca302019-04-08 15:14:01 +02001831 const bool video_is_suspended = target_bitrate == DataRate::Zero();
1832 const bool video_suspension_changed = video_is_suspended != EncoderPaused();
1833
Florent Castellia8336d32019-09-09 13:36:55 +02001834 EncoderRateSettings new_rate_settings{
1835 VideoBitrateAllocation(), static_cast<double>(framerate_fps),
1836 link_allocation, target_bitrate, stable_target_bitrate};
Erik Språng4c6ca302019-04-08 15:14:01 +02001837 SetEncoderRates(UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
perkj26091b12016-09-01 01:17:40 -07001838
Erik Språng610c7632019-03-06 15:37:33 +01001839 encoder_start_bitrate_bps_ = target_bitrate.bps() != 0
1840 ? target_bitrate.bps()
1841 : encoder_start_bitrate_bps_;
Peter Boströmd153a372015-11-10 15:27:12 +00001842
sprang552c7c72017-02-13 04:41:45 -08001843 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001844 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
1845 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 09:29:58 +02001846 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +02001847 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001848 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
1849 !DropDueToSize(pending_frame_->size())) {
1850 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
1851 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
1852 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
1853 pending_frame_.reset();
1854 }
1855}
1856
1857bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001858 if (initial_framedrop_ < kMaxInitialFramedrop &&
Sebastian Janssona3177052018-04-10 13:05:49 +02001859 encoder_start_bitrate_bps_ > 0) {
1860 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
1861 return pixel_count > 320 * 240;
1862 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
1863 return pixel_count > 640 * 480;
1864 }
1865 }
1866 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001867}
1868
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001869bool VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001870 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -07001871 AdaptationRequest adaptation_request = {
1872 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001873 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001874 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -07001875
sprangc5d62e22017-04-02 23:53:04 -07001876 bool downgrade_requested =
1877 last_adaptation_request_ &&
1878 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1879
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001880 bool did_adapt = true;
1881
sprangc5d62e22017-04-02 23:53:04 -07001882 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001883 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-13 23:25:22 -07001884 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001885 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-02 23:53:04 -07001886 if (downgrade_requested &&
1887 adaptation_request.input_pixel_count_ >=
1888 last_adaptation_request_->input_pixel_count_) {
1889 // Don't request lower resolution if the current resolution is not
1890 // lower than the last time we asked for the resolution to be lowered.
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001891 return true;
sprangc5d62e22017-04-02 23:53:04 -07001892 }
1893 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001894 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-02 23:53:04 -07001895 if (adaptation_request.framerate_fps_ <= 0 ||
1896 (downgrade_requested &&
1897 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1898 // If no input fps estimate available, can't determine how to scale down
1899 // framerate. Otherwise, don't request lower framerate if we don't have
1900 // a valid frame rate. Since framerate, unlike resolution, is a measure
1901 // we have to estimate, and can fluctuate naturally over time, don't
1902 // make the same kind of limitations as for resolution, but trust the
1903 // overuse detector to not trigger too often.
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001904 return true;
sprangc5d62e22017-04-02 23:53:04 -07001905 }
1906 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001907 case DegradationPreference::DISABLED:
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001908 return true;
sprang84a37592017-02-10 07:04:27 -08001909 }
sprangc5d62e22017-04-02 23:53:04 -07001910
sprangc5d62e22017-04-02 23:53:04 -07001911 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001912 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001913 // Try scale down framerate, if lower.
Åsa Persson48284b82019-07-08 10:01:12 +02001914 int fps = balanced_settings_.MinFps(encoder_config_.codec_type,
1915 last_frame_info_->pixel_count());
asaperssonf7e294d2017-06-13 23:25:22 -07001916 if (source_proxy_->RestrictFramerate(fps)) {
1917 GetAdaptCounter().IncrementFramerate(reason);
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001918 // Check if requested fps is higher (or close to) input fps.
1919 absl::optional<int> min_diff =
1920 balanced_settings_.MinFpsDiff(last_frame_info_->pixel_count());
1921 if (min_diff && adaptation_request.framerate_fps_ > 0) {
1922 int fps_diff = adaptation_request.framerate_fps_ - fps;
1923 if (fps_diff < min_diff.value()) {
1924 did_adapt = false;
1925 }
1926 }
asaperssonf7e294d2017-06-13 23:25:22 -07001927 break;
1928 }
1929 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001930 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001931 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001932 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001933 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001934 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07001935 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07001936 adaptation_request.input_pixel_count_,
Erik Språnge2fd86a2018-10-24 11:32:39 +02001937 encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001938 &min_pixels_reached)) {
1939 if (min_pixels_reached)
Niels Möller213618e2018-07-24 09:29:58 +02001940 encoder_stats_observer_->OnMinPixelLimitReached();
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001941 return true;
asaperssond0de2952017-04-21 01:47:31 -07001942 }
asaperssonf7e294d2017-06-13 23:25:22 -07001943 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001944 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001945 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001946 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001947 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001948 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1949 adaptation_request.framerate_fps_);
1950 if (requested_framerate == -1)
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001951 return true;
sprangfda496a2017-06-15 04:21:07 -07001952 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001953 overuse_detector_->OnTargetFramerateUpdated(
1954 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001955 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001956 break;
sprangfda496a2017-06-15 04:21:07 -07001957 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001958 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001959 RTC_NOTREACHED();
1960 }
1961
asaperssond0de2952017-04-21 01:47:31 -07001962 last_adaptation_request_.emplace(adaptation_request);
1963
asapersson09f05612017-05-15 23:40:18 -07001964 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001965
Mirko Bonadei675513b2017-11-09 11:09:25 +01001966 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001967 return did_adapt;
perkj26091b12016-09-01 01:17:40 -07001968}
1969
mflodmancc3d4422017-08-03 08:27:51 -07001970void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001971 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001972
1973 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1974 int num_downgrades = adapt_counter.TotalCount(reason);
1975 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001976 return;
asapersson09f05612017-05-15 23:40:18 -07001977 RTC_DCHECK_GT(num_downgrades, 0);
1978
sprangc5d62e22017-04-02 23:53:04 -07001979 AdaptationRequest adaptation_request = {
1980 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001981 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001982 AdaptationRequest::Mode::kAdaptUp};
1983
1984 bool adapt_up_requested =
1985 last_adaptation_request_ &&
1986 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001987
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001988 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-13 23:25:22 -07001989 if (adapt_up_requested &&
1990 adaptation_request.input_pixel_count_ <=
1991 last_adaptation_request_->input_pixel_count_) {
1992 // Don't request higher resolution if the current resolution is not
1993 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001994 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001995 }
sprangb1ca0732017-02-01 08:38:12 -08001996 }
sprangc5d62e22017-04-02 23:53:04 -07001997
sprangc5d62e22017-04-02 23:53:04 -07001998 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001999 case DegradationPreference::BALANCED: {
Åsa Persson4869bd62019-08-23 16:20:06 +02002000 // Check if quality should be increased based on bitrate.
2001 if (reason == kQuality &&
2002 !balanced_settings_.CanAdaptUp(last_frame_info_->pixel_count(),
2003 encoder_start_bitrate_bps_)) {
Åsa Persson1b247f12019-08-14 17:26:39 +02002004 return;
2005 }
asaperssonf7e294d2017-06-13 23:25:22 -07002006 // Try scale up framerate, if higher.
Åsa Persson48284b82019-07-08 10:01:12 +02002007 int fps = balanced_settings_.MaxFps(encoder_config_.codec_type,
2008 last_frame_info_->pixel_count());
asaperssonf7e294d2017-06-13 23:25:22 -07002009 if (source_proxy_->IncreaseFramerate(fps)) {
2010 GetAdaptCounter().DecrementFramerate(reason, fps);
2011 // Reset framerate in case of fewer fps steps down than up.
2012 if (adapt_counter.FramerateCount() == 0 &&
2013 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002014 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07002015 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
2016 }
2017 break;
2018 }
Åsa Persson30ab0152019-08-27 12:22:33 +02002019 // Check if resolution should be increased based on bitrate.
2020 if (reason == kQuality &&
2021 !balanced_settings_.CanAdaptUpResolution(
2022 last_frame_info_->pixel_count(), encoder_start_bitrate_bps_)) {
2023 return;
2024 }
asaperssonf7e294d2017-06-13 23:25:22 -07002025 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01002026 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07002027 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002028 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07002029 // Scale up resolution.
2030 int pixel_count = adaptation_request.input_pixel_count_;
2031 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002032 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07002033 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07002034 }
asapersson13874762017-06-07 00:01:02 -07002035 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
2036 return;
asaperssonf7e294d2017-06-13 23:25:22 -07002037 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07002038 break;
asapersson13874762017-06-07 00:01:02 -07002039 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002040 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07002041 // Scale up framerate.
2042 int fps = adaptation_request.framerate_fps_;
2043 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002044 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07002045 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07002046 }
sprangfda496a2017-06-15 04:21:07 -07002047
2048 const int requested_framerate =
2049 source_proxy_->RequestHigherFramerateThan(fps);
2050 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01002051 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07002052 return;
sprangfda496a2017-06-15 04:21:07 -07002053 }
Niels Möller7dc26b72017-12-06 10:27:48 +01002054 overuse_detector_->OnTargetFramerateUpdated(
2055 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07002056 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07002057 break;
asapersson13874762017-06-07 00:01:02 -07002058 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002059 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-13 23:25:22 -07002060 return;
sprangc5d62e22017-04-02 23:53:04 -07002061 }
2062
asaperssond0de2952017-04-21 01:47:31 -07002063 last_adaptation_request_.emplace(adaptation_request);
2064
asapersson09f05612017-05-15 23:40:18 -07002065 UpdateAdaptationStats(reason);
2066
Mirko Bonadei675513b2017-11-09 11:09:25 +01002067 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07002068}
2069
Niels Möller213618e2018-07-24 09:29:58 +02002070// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 08:27:51 -07002071void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07002072 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07002073 case kCpu:
Niels Möller213618e2018-07-24 09:29:58 +02002074 encoder_stats_observer_->OnAdaptationChanged(
2075 VideoStreamEncoderObserver::AdaptationReason::kCpu,
2076 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-15 23:40:18 -07002077 break;
2078 case kQuality:
Niels Möller213618e2018-07-24 09:29:58 +02002079 encoder_stats_observer_->OnAdaptationChanged(
2080 VideoStreamEncoderObserver::AdaptationReason::kQuality,
2081 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07002082 break;
2083 }
perkj26091b12016-09-01 01:17:40 -07002084}
2085
Niels Möller213618e2018-07-24 09:29:58 +02002086VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 08:27:51 -07002087 AdaptReason reason) {
Niels Möller213618e2018-07-24 09:29:58 +02002088 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 08:27:51 -07002089 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07002090 switch (reason) {
2091 case kCpu:
2092 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02002093 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002094 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02002095 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002096 break;
2097 case kQuality:
2098 if (!IsFramerateScalingEnabled(degradation_preference_) ||
2099 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02002100 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002101 }
2102 if (!IsResolutionScalingEnabled(degradation_preference_) ||
2103 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02002104 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002105 }
2106 break;
sprangc5d62e22017-04-02 23:53:04 -07002107 }
asapersson09f05612017-05-15 23:40:18 -07002108 return counts;
sprangc5d62e22017-04-02 23:53:04 -07002109}
2110
mflodmancc3d4422017-08-03 08:27:51 -07002111VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002112 return adapt_counters_[degradation_preference_];
2113}
2114
mflodmancc3d4422017-08-03 08:27:51 -07002115const VideoStreamEncoder::AdaptCounter&
2116VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002117 return adapt_counters_[degradation_preference_];
2118}
2119
Erik Språng7ca375c2019-02-06 16:20:17 +01002120void VideoStreamEncoder::RunPostEncode(EncodedImage encoded_image,
Niels Möller6bb5ab92019-01-11 11:11:10 +01002121 int64_t time_sent_us,
Erik Språng7ca375c2019-02-06 16:20:17 +01002122 int temporal_index) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01002123 if (!encoder_queue_.IsCurrent()) {
Erik Språng7ca375c2019-02-06 16:20:17 +01002124 encoder_queue_.PostTask(
2125 [this, encoded_image, time_sent_us, temporal_index] {
2126 RunPostEncode(encoded_image, time_sent_us, temporal_index);
2127 });
Niels Möller6bb5ab92019-01-11 11:11:10 +01002128 return;
2129 }
2130
2131 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +01002132
2133 absl::optional<int> encode_duration_us;
2134 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
2135 encode_duration_us =
2136 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
2137 rtc::kNumMicrosecsPerMillisec *
2138 (encoded_image.timing_.encode_finish_ms -
2139 encoded_image.timing_.encode_start_ms);
2140 }
2141
2142 // Run post encode tasks, such as overuse detection and frame rate/drop
2143 // stats for internal encoders.
2144 const size_t frame_size = encoded_image.size();
Niels Möller87e2d782019-03-07 10:18:23 +01002145 const bool keyframe =
2146 encoded_image._frameType == VideoFrameType::kVideoFrameKey;
Erik Språng7ca375c2019-02-06 16:20:17 +01002147
2148 if (frame_size > 0) {
2149 frame_dropper_.Fill(frame_size, !keyframe);
Niels Möller6bb5ab92019-01-11 11:11:10 +01002150 }
2151
Erik Språngd7329ca2019-02-21 21:19:53 +01002152 if (HasInternalSource()) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01002153 // Update frame dropper after the fact for internal sources.
2154 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
2155 frame_dropper_.Leak(GetInputFramerateFps());
2156 // Signal to encoder to drop next frame.
2157 if (frame_dropper_.DropFrame()) {
2158 pending_frame_drops_.fetch_add(1);
2159 }
2160 }
2161
Erik Språng7ca375c2019-02-06 16:20:17 +01002162 overuse_detector_->FrameSent(
2163 encoded_image.Timestamp(), time_sent_us,
2164 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec,
2165 encode_duration_us);
2166 if (quality_scaler_ && encoded_image.qp_ >= 0)
Sebastian Janssonb6789402019-03-01 15:40:49 +01002167 quality_scaler_->ReportQp(encoded_image.qp_, time_sent_us);
Erik Språng7ca375c2019-02-06 16:20:17 +01002168 if (bitrate_adjuster_) {
2169 bitrate_adjuster_->OnEncodedFrame(encoded_image, temporal_index);
2170 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01002171}
2172
Erik Språngd7329ca2019-02-21 21:19:53 +01002173bool VideoStreamEncoder::HasInternalSource() const {
2174 // TODO(sprang): Checking both info from encoder and from encoder factory
2175 // until we have deprecated and removed the encoder factory info.
2176 return codec_info_.has_internal_source || encoder_info_.has_internal_source;
2177}
2178
Erik Språng6a7baa72019-02-26 18:31:00 +01002179void VideoStreamEncoder::ReleaseEncoder() {
2180 if (!encoder_ || !encoder_initialized_) {
2181 return;
2182 }
2183 encoder_->Release();
2184 encoder_initialized_ = false;
2185 TRACE_EVENT0("webrtc", "VCMGenericEncoder::Release");
2186}
2187
asapersson09f05612017-05-15 23:40:18 -07002188// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07002189VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002190 fps_counters_.resize(kScaleReasonSize);
2191 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07002192 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07002193}
2194
mflodmancc3d4422017-08-03 08:27:51 -07002195VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07002196
mflodmancc3d4422017-08-03 08:27:51 -07002197std::string VideoStreamEncoder::AdaptCounter::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02002198 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07002199 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
2200 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
Jonas Olsson84df1c72018-09-14 16:59:32 +02002201 return ss.Release();
asapersson09f05612017-05-15 23:40:18 -07002202}
2203
Niels Möller213618e2018-07-24 09:29:58 +02002204VideoStreamEncoderObserver::AdaptationSteps
2205VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
2206 VideoStreamEncoderObserver::AdaptationSteps counts;
2207 counts.num_framerate_reductions = fps_counters_[reason];
2208 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-15 23:40:18 -07002209 return counts;
2210}
2211
mflodmancc3d4422017-08-03 08:27:51 -07002212void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002213 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07002214}
2215
mflodmancc3d4422017-08-03 08:27:51 -07002216void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002217 ++(resolution_counters_[reason]);
2218}
2219
mflodmancc3d4422017-08-03 08:27:51 -07002220void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002221 if (fps_counters_[reason] == 0) {
2222 // Balanced mode: Adapt up is in a different order, switch reason.
2223 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
2224 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
2225 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
2226 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
2227 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
2228 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
2229 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
2230 MoveCount(&resolution_counters_, reason);
2231 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
2232 }
2233 --(fps_counters_[reason]);
2234 RTC_DCHECK_GE(fps_counters_[reason], 0);
2235}
2236
mflodmancc3d4422017-08-03 08:27:51 -07002237void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002238 if (resolution_counters_[reason] == 0) {
2239 // Balanced mode: Adapt up is in a different order, switch reason.
2240 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
2241 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
2242 MoveCount(&fps_counters_, reason);
2243 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
2244 }
2245 --(resolution_counters_[reason]);
2246 RTC_DCHECK_GE(resolution_counters_[reason], 0);
2247}
2248
mflodmancc3d4422017-08-03 08:27:51 -07002249void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
2250 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07002251 DecrementFramerate(reason);
2252 // Reset if at max fps (i.e. in case of fewer steps up than down).
2253 if (cur_fps == std::numeric_limits<int>::max())
Steve Antonbd631a02019-03-28 10:51:27 -07002254 absl::c_fill(fps_counters_, 0);
asapersson09f05612017-05-15 23:40:18 -07002255}
2256
mflodmancc3d4422017-08-03 08:27:51 -07002257int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07002258 return Count(fps_counters_);
2259}
2260
mflodmancc3d4422017-08-03 08:27:51 -07002261int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07002262 return Count(resolution_counters_);
2263}
2264
mflodmancc3d4422017-08-03 08:27:51 -07002265int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002266 return fps_counters_[reason];
2267}
2268
mflodmancc3d4422017-08-03 08:27:51 -07002269int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002270 return resolution_counters_[reason];
2271}
2272
mflodmancc3d4422017-08-03 08:27:51 -07002273int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002274 return FramerateCount(reason) + ResolutionCount(reason);
2275}
2276
mflodmancc3d4422017-08-03 08:27:51 -07002277int VideoStreamEncoder::AdaptCounter::Count(
2278 const std::vector<int>& counters) const {
Steve Antonbd631a02019-03-28 10:51:27 -07002279 return absl::c_accumulate(counters, 0);
asapersson09f05612017-05-15 23:40:18 -07002280}
2281
mflodmancc3d4422017-08-03 08:27:51 -07002282void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
2283 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002284 int to_reason = (from_reason + 1) % kScaleReasonSize;
2285 ++((*counters)[to_reason]);
2286 --((*counters)[from_reason]);
2287}
2288
mflodmancc3d4422017-08-03 08:27:51 -07002289std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07002290 const std::vector<int>& counters) const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02002291 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07002292 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
2293 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07002294 }
Jonas Olsson84df1c72018-09-14 16:59:32 +02002295 return ss.Release();
sprangc5d62e22017-04-02 23:53:04 -07002296}
2297
philipeld9cc8c02019-09-16 14:53:40 +02002298bool VideoStreamEncoder::EncoderSwitchExperiment::IsBitrateBelowThreshold(
2299 const DataRate& target_bitrate) {
2300 DataRate rate =
2301 DataRate::kbps(bitrate_filter.Apply(1.0, target_bitrate.kbps()));
2302 return current_thresholds.bitrate && rate < *current_thresholds.bitrate;
2303}
2304
2305bool VideoStreamEncoder::EncoderSwitchExperiment::IsPixelCountBelowThreshold(
2306 int pixel_count) const {
2307 return current_thresholds.pixel_count &&
2308 pixel_count < *current_thresholds.pixel_count;
2309}
2310
2311void VideoStreamEncoder::EncoderSwitchExperiment::SetCodec(
2312 VideoCodecType codec) {
2313 auto it = codec_thresholds.find(codec);
2314 if (it == codec_thresholds.end()) {
2315 current_thresholds = {};
2316 } else {
2317 current_thresholds = it->second;
2318 }
2319}
2320
2321VideoStreamEncoder::EncoderSwitchExperiment
2322VideoStreamEncoder::ParseEncoderSwitchFieldTrial() const {
2323 EncoderSwitchExperiment result;
2324
2325 // Each "codec threshold" have the format
2326 // "<codec name>;<bitrate kbps>;<pixel count>", and are separated by the "|"
2327 // character.
2328 webrtc::FieldTrialOptional<std::string> codec_thresholds_string{
2329 "codec_thresholds"};
2330 webrtc::FieldTrialOptional<std::string> to_codec{"to_codec"};
2331 webrtc::FieldTrialOptional<std::string> to_param{"to_param"};
2332 webrtc::FieldTrialOptional<std::string> to_value{"to_value"};
2333 webrtc::FieldTrialOptional<double> window{"window"};
2334
2335 webrtc::ParseFieldTrial(
2336 {&codec_thresholds_string, &to_codec, &to_param, &to_value, &window},
2337 webrtc::field_trial::FindFullName(
2338 "WebRTC-NetworkCondition-EncoderSwitch"));
2339
2340 if (!codec_thresholds_string || !to_codec || !window) {
2341 return {};
2342 }
2343
2344 result.bitrate_filter.Reset(1.0 - 1.0 / *window);
2345 result.to_codec = *to_codec;
2346 result.to_param = to_param.GetOptional();
2347 result.to_value = to_value.GetOptional();
2348
2349 std::vector<std::string> codecs_thresholds;
2350 if (rtc::split(*codec_thresholds_string, '|', &codecs_thresholds) == 0) {
2351 return {};
2352 }
2353
2354 for (const std::string& codec_threshold : codecs_thresholds) {
2355 std::vector<std::string> thresholds_split;
2356 if (rtc::split(codec_threshold, ';', &thresholds_split) != 3) {
2357 return {};
2358 }
2359
2360 VideoCodecType codec = PayloadStringToCodecType(thresholds_split[0]);
2361 int bitrate_kbps;
2362 rtc::FromString(thresholds_split[1], &bitrate_kbps);
2363 int pixel_count;
2364 rtc::FromString(thresholds_split[2], &pixel_count);
2365
2366 if (bitrate_kbps > 0) {
2367 result.codec_thresholds[codec].bitrate = DataRate::kbps(bitrate_kbps);
2368 }
2369
2370 if (pixel_count > 0) {
2371 result.codec_thresholds[codec].pixel_count = pixel_count;
2372 }
2373
2374 if (!result.codec_thresholds[codec].bitrate &&
2375 !result.codec_thresholds[codec].pixel_count) {
2376 return {};
2377 }
2378 }
2379
2380 rtc::StringBuilder ss;
2381 ss << "Successfully parsed WebRTC-NetworkCondition-EncoderSwitch field "
2382 "trial."
2383 << " to_codec:" << result.to_codec
2384 << " to_param:" << result.to_param.value_or("<none>")
2385 << " to_value:" << result.to_value.value_or("<none>")
2386 << " codec_thresholds:";
2387
2388 for (auto kv : result.codec_thresholds) {
2389 std::string codec_name = CodecTypeToPayloadString(kv.first);
2390 std::string bitrate = kv.second.bitrate
2391 ? std::to_string(kv.second.bitrate->kbps())
2392 : "<none>";
2393 std::string pixels = kv.second.pixel_count
2394 ? std::to_string(*kv.second.pixel_count)
2395 : "<none>";
2396 ss << " (" << codec_name << ":" << bitrate << ":" << pixels << ")";
2397 }
2398
2399 RTC_LOG(LS_INFO) << ss.str();
2400
2401 return result;
2402}
2403
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00002404} // namespace webrtc