blob: 61a6f2fc5e7dbd85734ac542fb6c67d273ebe55d [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>
perkj57c21f92016-06-17 07:27:16 -070014#include <limits>
sprangc5d62e22017-04-02 23:53:04 -070015#include <numeric>
Per512ecb32016-09-23 15:52:06 +020016#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000017
Steve Antonbd631a02019-03-28 10:51:27 -070018#include "absl/algorithm/container.h"
Niels Möller6bb5ab92019-01-11 11:11:10 +010019#include "absl/memory/memory.h"
Niels Möller4dc66c52018-10-05 14:17:58 +020020#include "api/video/encoded_image.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/video/i420_buffer.h"
Jiawei Ouc2ebe212018-11-08 10:02:56 -080022#include "api/video/video_bitrate_allocator_factory.h"
Elad Alon370f93a2019-06-11 14:57:57 +020023#include "api/video_codecs/video_encoder.h"
Sergey Silkin8b9b5f92018-12-10 09:28:53 +010024#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/video_coding/include/video_codec_initializer.h"
26#include "modules/video_coding/include/video_coding.h"
Niels Möller6bb5ab92019-01-11 11:11:10 +010027#include "modules/video_coding/utility/default_video_bitrate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/arraysize.h"
29#include "rtc_base/checks.h"
Erik Språng6a7baa72019-02-26 18:31:00 +010030#include "rtc_base/experiments/alr_experiment.h"
Åsa Perssona945aee2018-04-24 16:53:25 +020031#include "rtc_base/experiments/quality_scaling_experiment.h"
Erik Språng7ca375c2019-02-06 16:20:17 +010032#include "rtc_base/experiments/rate_control_settings.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/location.h"
34#include "rtc_base/logging.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020035#include "rtc_base/strings/string_builder.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010036#include "rtc_base/system/fallthrough.h"
Steve Anton10542f22019-01-11 09:11:00 -080037#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/trace_event.h"
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020039#include "system_wrappers/include/field_trial.h"
nisseea3a7982017-05-15 02:42:11 -070040
niklase@google.com470e71d2011-07-07 08:21:25 +000041namespace webrtc {
42
perkj26091b12016-09-01 01:17:40 -070043namespace {
sprangb1ca0732017-02-01 08:38:12 -080044
asapersson6ffb67d2016-09-12 00:10:45 -070045// Time interval for logging frame counts.
46const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070047const int kMinFramerateFps = 2;
perkj26091b12016-09-01 01:17:40 -070048
Sebastian Janssona3177052018-04-10 13:05:49 +020049// Time to keep a single cached pending frame in paused state.
50const int64_t kPendingFrameTimeoutMs = 1000;
51
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020052const char kInitialFramedropFieldTrial[] = "WebRTC-InitialFramedrop";
Niels Möller6bb5ab92019-01-11 11:11:10 +010053constexpr char kFrameDropperFieldTrial[] = "WebRTC-FrameDropper";
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020054
kthelgason2bc68642017-02-07 07:02:22 -080055// The maximum number of frames to drop at beginning of stream
56// to try and achieve desired bitrate.
57const int kMaxInitialFramedrop = 4;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020058// When the first change in BWE above this threshold occurs,
59// enable DropFrameDueToSize logic.
60const float kFramedropThreshold = 0.3;
kthelgason2bc68642017-02-07 07:02:22 -080061
Niels Möller6bb5ab92019-01-11 11:11:10 +010062// Averaging window spanning 90 frames at default 30fps, matching old media
63// optimization module defaults.
64const int64_t kFrameRateAvergingWindowSizeMs = (1000 / 30) * 90;
65
Erik Språngb7cb7b52019-02-26 15:52:33 +010066const size_t kDefaultPayloadSize = 1440;
67
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020068uint32_t abs_diff(uint32_t a, uint32_t b) {
69 return (a < b) ? b - a : a - b;
70}
71
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070072bool IsResolutionScalingEnabled(DegradationPreference degradation_preference) {
73 return degradation_preference == DegradationPreference::MAINTAIN_FRAMERATE ||
74 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070075}
76
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070077bool IsFramerateScalingEnabled(DegradationPreference degradation_preference) {
78 return degradation_preference == DegradationPreference::MAINTAIN_RESOLUTION ||
79 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070080}
81
Niels Möllerd1f7eb62018-03-28 16:40:58 +020082// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
83// pipelining encoders better (multiple input frames before something comes
84// out). This should effectively turn off CPU adaptations for systems that
85// remotely cope with the load right now.
86CpuOveruseOptions GetCpuOveruseOptions(
Niels Möller213618e2018-07-24 09:29:58 +020087 const VideoStreamEncoderSettings& settings,
Niels Möller4db138e2018-04-19 09:04:13 +020088 bool full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +020089 CpuOveruseOptions options;
90
Niels Möller4db138e2018-04-19 09:04:13 +020091 if (full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +020092 options.low_encode_usage_threshold_percent = 150;
93 options.high_encode_usage_threshold_percent = 200;
94 }
95 if (settings.experiment_cpu_load_estimator) {
96 options.filter_time_ms = 5 * rtc::kNumMillisecsPerSec;
97 }
98
99 return options;
100}
101
Sergey Silkin5ee69672019-07-02 14:18:34 +0200102bool RequiresEncoderReset(const VideoCodec& prev_send_codec,
103 const VideoCodec& new_send_codec,
104 bool was_encode_called_since_last_initialization) {
105 // Does not check max/minBitrate or maxFramerate.
106 if (new_send_codec.codecType != prev_send_codec.codecType ||
107 new_send_codec.width != prev_send_codec.width ||
108 new_send_codec.height != prev_send_codec.height ||
109 new_send_codec.qpMax != prev_send_codec.qpMax ||
Erik Språngb7cb7b52019-02-26 15:52:33 +0100110 new_send_codec.numberOfSimulcastStreams !=
Sergey Silkin5ee69672019-07-02 14:18:34 +0200111 prev_send_codec.numberOfSimulcastStreams ||
112 new_send_codec.mode != prev_send_codec.mode) {
113 return true;
114 }
115
116 if (!was_encode_called_since_last_initialization &&
117 (new_send_codec.startBitrate != prev_send_codec.startBitrate)) {
118 // If start bitrate has changed reconfigure encoder only if encoding had not
119 // yet started.
Erik Språngb7cb7b52019-02-26 15:52:33 +0100120 return true;
121 }
122
123 switch (new_send_codec.codecType) {
124 case kVideoCodecVP8:
Sergey Silkin5ee69672019-07-02 14:18:34 +0200125 if (new_send_codec.VP8() != prev_send_codec.VP8()) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100126 return true;
127 }
128 break;
129
130 case kVideoCodecVP9:
Sergey Silkin5ee69672019-07-02 14:18:34 +0200131 if (new_send_codec.VP9() != prev_send_codec.VP9()) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100132 return true;
133 }
134 break;
135
136 case kVideoCodecH264:
Sergey Silkin5ee69672019-07-02 14:18:34 +0200137 if (new_send_codec.H264() != prev_send_codec.H264()) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100138 return true;
139 }
140 break;
141
142 default:
143 break;
144 }
145
146 for (unsigned char i = 0; i < new_send_codec.numberOfSimulcastStreams; ++i) {
Sergey Silkin5ee69672019-07-02 14:18:34 +0200147 if (new_send_codec.simulcastStream[i].width !=
148 prev_send_codec.simulcastStream[i].width ||
149 new_send_codec.simulcastStream[i].height !=
150 prev_send_codec.simulcastStream[i].height ||
151 new_send_codec.simulcastStream[i].numberOfTemporalLayers !=
152 prev_send_codec.simulcastStream[i].numberOfTemporalLayers ||
153 new_send_codec.simulcastStream[i].qpMax !=
154 prev_send_codec.simulcastStream[i].qpMax ||
155 new_send_codec.simulcastStream[i].active !=
156 prev_send_codec.simulcastStream[i].active) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100157 return true;
Sergey Silkin5ee69672019-07-02 14:18:34 +0200158 }
Erik Språngb7cb7b52019-02-26 15:52:33 +0100159 }
160 return false;
161}
Erik Språng6a7baa72019-02-26 18:31:00 +0100162
163std::array<uint8_t, 2> GetExperimentGroups() {
164 std::array<uint8_t, 2> experiment_groups;
165 absl::optional<AlrExperimentSettings> experiment_settings =
166 AlrExperimentSettings::CreateFromFieldTrial(
167 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
168 if (experiment_settings) {
169 experiment_groups[0] = experiment_settings->group_id + 1;
170 } else {
171 experiment_groups[0] = 0;
172 }
173 experiment_settings = AlrExperimentSettings::CreateFromFieldTrial(
174 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
175 if (experiment_settings) {
176 experiment_groups[1] = experiment_settings->group_id + 1;
177 } else {
178 experiment_groups[1] = 0;
179 }
180 return experiment_groups;
181}
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100182
183// Limit allocation across TLs in bitrate allocation according to number of TLs
184// in EncoderInfo.
185VideoBitrateAllocation UpdateAllocationFromEncoderInfo(
186 const VideoBitrateAllocation& allocation,
187 const VideoEncoder::EncoderInfo& encoder_info) {
188 if (allocation.get_sum_bps() == 0) {
189 return allocation;
190 }
191 VideoBitrateAllocation new_allocation;
192 for (int si = 0; si < kMaxSpatialLayers; ++si) {
193 if (encoder_info.fps_allocation[si].size() == 1 &&
194 allocation.IsSpatialLayerUsed(si)) {
195 // One TL is signalled to be used by the encoder. Do not distribute
196 // bitrate allocation across TLs (use sum at ti:0).
197 new_allocation.SetBitrate(si, 0, allocation.GetSpatialLayerSum(si));
198 } else {
199 for (int ti = 0; ti < kMaxTemporalStreams; ++ti) {
200 if (allocation.HasBitrate(si, ti))
201 new_allocation.SetBitrate(si, ti, allocation.GetBitrate(si, ti));
202 }
203 }
204 }
205 return new_allocation;
206}
perkj26091b12016-09-01 01:17:40 -0700207} // namespace
208
perkja49cbd32016-09-16 07:53:41 -0700209// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700210// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
211// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700212// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700213class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700214 public:
mflodmancc3d4422017-08-03 08:27:51 -0700215 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
216 : video_stream_encoder_(video_stream_encoder),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700217 degradation_preference_(DegradationPreference::DISABLED),
Åsa Persson8c1bf952018-09-13 10:42:19 +0200218 source_(nullptr),
219 max_framerate_(std::numeric_limits<int>::max()) {}
perkja49cbd32016-09-16 07:53:41 -0700220
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700221 void SetSource(rtc::VideoSourceInterface<VideoFrame>* source,
222 const DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700223 // Called on libjingle's worker thread.
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200224 RTC_DCHECK_RUN_ON(&main_checker_);
perkja49cbd32016-09-16 07:53:41 -0700225 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700226 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700227 {
228 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700229 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700230 old_source = source_;
231 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700232 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700233 }
234
235 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700236 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700237 }
238
239 if (!source) {
240 return;
241 }
242
mflodmancc3d4422017-08-03 08:27:51 -0700243 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700244 }
245
Åsa Persson8c1bf952018-09-13 10:42:19 +0200246 void SetMaxFramerate(int max_framerate) {
247 RTC_DCHECK_GT(max_framerate, 0);
248 rtc::CritScope lock(&crit_);
249 if (max_framerate == max_framerate_)
250 return;
251
252 RTC_LOG(LS_INFO) << "Set max framerate: " << max_framerate;
253 max_framerate_ = max_framerate;
254 if (source_) {
255 source_->AddOrUpdateSink(video_stream_encoder_,
256 GetActiveSinkWantsInternal());
257 }
258 }
259
perkj803d97f2016-11-01 11:45:46 -0700260 void SetWantsRotationApplied(bool rotation_applied) {
261 rtc::CritScope lock(&crit_);
262 sink_wants_.rotation_applied = rotation_applied;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200263 if (source_) {
264 source_->AddOrUpdateSink(video_stream_encoder_,
265 GetActiveSinkWantsInternal());
266 }
sprangc5d62e22017-04-02 23:53:04 -0700267 }
268
sprangfda496a2017-06-15 04:21:07 -0700269 rtc::VideoSinkWants GetActiveSinkWants() {
270 rtc::CritScope lock(&crit_);
271 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700272 }
273
asaperssonf7e294d2017-06-13 23:25:22 -0700274 void ResetPixelFpsCount() {
275 rtc::CritScope lock(&crit_);
276 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
277 sink_wants_.target_pixel_count.reset();
278 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
279 if (source_)
Åsa Persson8c1bf952018-09-13 10:42:19 +0200280 source_->AddOrUpdateSink(video_stream_encoder_,
281 GetActiveSinkWantsInternal());
asaperssonf7e294d2017-06-13 23:25:22 -0700282 }
283
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100284 bool RequestResolutionLowerThan(int pixel_count,
285 int min_pixels_per_frame,
286 bool* min_pixels_reached) {
perkj803d97f2016-11-01 11:45:46 -0700287 // Called on the encoder task queue.
288 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700289 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700290 // This can happen since |degradation_preference_| is set on libjingle's
291 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700292 return false;
perkj803d97f2016-11-01 11:45:46 -0700293 }
asapersson13874762017-06-07 00:01:02 -0700294 // The input video frame size will have a resolution less than or equal to
295 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800296 const int pixels_wanted = (pixel_count * 3) / 5;
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100297 if (pixels_wanted >= sink_wants_.max_pixel_count) {
298 return false;
299 }
300 if (pixels_wanted < min_pixels_per_frame) {
301 *min_pixels_reached = true;
asaperssond0de2952017-04-21 01:47:31 -0700302 return false;
asapersson13874762017-06-07 00:01:02 -0700303 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100304 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
305 << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700306 sink_wants_.max_pixel_count = pixels_wanted;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200307 sink_wants_.target_pixel_count = absl::nullopt;
mflodmancc3d4422017-08-03 08:27:51 -0700308 source_->AddOrUpdateSink(video_stream_encoder_,
309 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700310 return true;
sprangc5d62e22017-04-02 23:53:04 -0700311 }
312
sprangfda496a2017-06-15 04:21:07 -0700313 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700314 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700315 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700316 int framerate_wanted = (fps * 2) / 3;
317 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700318 }
319
asapersson13874762017-06-07 00:01:02 -0700320 bool RequestHigherResolutionThan(int pixel_count) {
321 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700322 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700323 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700324 // This can happen since |degradation_preference_| is set on libjingle's
325 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700326 return false;
perkj803d97f2016-11-01 11:45:46 -0700327 }
asapersson13874762017-06-07 00:01:02 -0700328 int max_pixels_wanted = pixel_count;
329 if (max_pixels_wanted != std::numeric_limits<int>::max())
330 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700331
asapersson13874762017-06-07 00:01:02 -0700332 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
333 return false;
334
335 sink_wants_.max_pixel_count = max_pixels_wanted;
336 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700337 // Remove any constraints.
338 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700339 } else {
340 // On step down we request at most 3/5 the pixel count of the previous
341 // resolution, so in order to take "one step up" we request a resolution
342 // as close as possible to 5/3 of the current resolution. The actual pixel
343 // count selected depends on the capabilities of the source. In order to
344 // not take a too large step up, we cap the requested pixel count to be at
345 // most four time the current number of pixels.
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100346 sink_wants_.target_pixel_count = (pixel_count * 5) / 3;
sprangc5d62e22017-04-02 23:53:04 -0700347 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100348 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
349 << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700350 source_->AddOrUpdateSink(video_stream_encoder_,
351 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700352 return true;
sprangc5d62e22017-04-02 23:53:04 -0700353 }
354
sprangfda496a2017-06-15 04:21:07 -0700355 // Request upgrade in framerate. Returns the new requested frame, or -1 if
356 // no change requested. Note that maxint may be returned if limits due to
357 // adaptation requests are removed completely. In that case, consider
358 // |max_framerate_| to be the current limit (assuming the capturer complies).
359 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700360 // Called on the encoder task queue.
361 // The input frame rate will be scaled up to the last step, with rounding.
362 int framerate_wanted = fps;
363 if (fps != std::numeric_limits<int>::max())
364 framerate_wanted = (fps * 3) / 2;
365
sprangfda496a2017-06-15 04:21:07 -0700366 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700367 }
368
369 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700370 // Called on the encoder task queue.
371 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700372 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
373 return false;
374
375 const int fps_wanted = std::max(kMinFramerateFps, fps);
376 if (fps_wanted >= sink_wants_.max_framerate_fps)
377 return false;
378
Mirko Bonadei675513b2017-11-09 11:09:25 +0100379 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700380 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700381 source_->AddOrUpdateSink(video_stream_encoder_,
382 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700383 return true;
384 }
385
386 bool IncreaseFramerate(int fps) {
387 // Called on the encoder task queue.
388 rtc::CritScope lock(&crit_);
389 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
390 return false;
391
392 const int fps_wanted = std::max(kMinFramerateFps, fps);
393 if (fps_wanted <= sink_wants_.max_framerate_fps)
394 return false;
395
Mirko Bonadei675513b2017-11-09 11:09:25 +0100396 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700397 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700398 source_->AddOrUpdateSink(video_stream_encoder_,
399 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700400 return true;
perkj803d97f2016-11-01 11:45:46 -0700401 }
402
perkja49cbd32016-09-16 07:53:41 -0700403 private:
sprangfda496a2017-06-15 04:21:07 -0700404 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700405 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700406 rtc::VideoSinkWants wants = sink_wants_;
407 // Clear any constraints from the current sink wants that don't apply to
408 // the used degradation_preference.
409 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700410 case DegradationPreference::BALANCED:
sprangfda496a2017-06-15 04:21:07 -0700411 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700412 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangfda496a2017-06-15 04:21:07 -0700413 wants.max_framerate_fps = std::numeric_limits<int>::max();
414 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700415 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangfda496a2017-06-15 04:21:07 -0700416 wants.max_pixel_count = std::numeric_limits<int>::max();
417 wants.target_pixel_count.reset();
418 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700419 case DegradationPreference::DISABLED:
sprangfda496a2017-06-15 04:21:07 -0700420 wants.max_pixel_count = std::numeric_limits<int>::max();
421 wants.target_pixel_count.reset();
422 wants.max_framerate_fps = std::numeric_limits<int>::max();
423 }
Åsa Persson8c1bf952018-09-13 10:42:19 +0200424 // Limit to configured max framerate.
425 wants.max_framerate_fps = std::min(max_framerate_, wants.max_framerate_fps);
sprangfda496a2017-06-15 04:21:07 -0700426 return wants;
427 }
428
perkja49cbd32016-09-16 07:53:41 -0700429 rtc::CriticalSection crit_;
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200430 SequenceChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700431 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700432 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700433 DegradationPreference degradation_preference_ RTC_GUARDED_BY(&crit_);
danilchapa37de392017-09-09 04:17:22 -0700434 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
Åsa Persson8c1bf952018-09-13 10:42:19 +0200435 int max_framerate_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700436
437 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
438};
439
Erik Språng4c6ca302019-04-08 15:14:01 +0200440VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings()
Florent Castellia8336d32019-09-09 13:36:55 +0200441 : VideoEncoder::RateControlParameters(),
442 encoder_target(DataRate::Zero()),
443 stable_encoder_target(DataRate::Zero()) {}
Erik Språng4c6ca302019-04-08 15:14:01 +0200444
445VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings(
446 const VideoBitrateAllocation& bitrate,
447 double framerate_fps,
448 DataRate bandwidth_allocation,
Florent Castellia8336d32019-09-09 13:36:55 +0200449 DataRate encoder_target,
450 DataRate stable_encoder_target)
Erik Språng4c6ca302019-04-08 15:14:01 +0200451 : VideoEncoder::RateControlParameters(bitrate,
452 framerate_fps,
453 bandwidth_allocation),
Florent Castellia8336d32019-09-09 13:36:55 +0200454 encoder_target(encoder_target),
455 stable_encoder_target(stable_encoder_target) {}
Erik Språng4c6ca302019-04-08 15:14:01 +0200456
457bool VideoStreamEncoder::EncoderRateSettings::operator==(
458 const EncoderRateSettings& rhs) const {
459 return bitrate == rhs.bitrate && framerate_fps == rhs.framerate_fps &&
460 bandwidth_allocation == rhs.bandwidth_allocation &&
Florent Castellia8336d32019-09-09 13:36:55 +0200461 encoder_target == rhs.encoder_target &&
462 stable_encoder_target == rhs.stable_encoder_target;
Erik Språng4c6ca302019-04-08 15:14:01 +0200463}
464
465bool VideoStreamEncoder::EncoderRateSettings::operator!=(
466 const EncoderRateSettings& rhs) const {
467 return !(*this == rhs);
468}
469
Åsa Persson0122e842017-10-16 12:19:23 +0200470VideoStreamEncoder::VideoStreamEncoder(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100471 Clock* clock,
Åsa Persson0122e842017-10-16 12:19:23 +0200472 uint32_t number_of_cores,
Niels Möller213618e2018-07-24 09:29:58 +0200473 VideoStreamEncoderObserver* encoder_stats_observer,
474 const VideoStreamEncoderSettings& settings,
Sebastian Jansson74682c12019-03-01 11:50:20 +0100475 std::unique_ptr<OveruseFrameDetector> overuse_detector,
476 TaskQueueFactory* task_queue_factory)
perkj26091b12016-09-01 01:17:40 -0700477 : shutdown_event_(true /* manual_reset */, false),
478 number_of_cores_(number_of_cores),
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200479 initial_framedrop_(0),
480 initial_framedrop_on_bwe_enabled_(
481 webrtc::field_trial::IsEnabled(kInitialFramedropFieldTrial)),
Åsa Perssona945aee2018-04-24 16:53:25 +0200482 quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
perkja49cbd32016-09-16 07:53:41 -0700483 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200484 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700485 settings_(settings),
Erik Språng7ca375c2019-02-06 16:20:17 +0100486 rate_control_settings_(RateControlSettings::ParseFromFieldTrials()),
Åsa Persson139f4dc2019-08-02 09:29:58 +0200487 quality_scaler_settings_(QualityScalerSettings::ParseFromFieldTrials()),
Niels Möller73f29cb2018-01-31 16:09:31 +0100488 overuse_detector_(std::move(overuse_detector)),
Niels Möller213618e2018-07-24 09:29:58 +0200489 encoder_stats_observer_(encoder_stats_observer),
Erik Språng6a7baa72019-02-26 18:31:00 +0100490 encoder_initialized_(false),
sprangfda496a2017-06-15 04:21:07 -0700491 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700492 pending_encoder_reconfiguration_(false),
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000493 pending_encoder_creation_(false),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200494 crop_width_(0),
495 crop_height_(0),
perkj26091b12016-09-01 01:17:40 -0700496 encoder_start_bitrate_bps_(0),
Åsa Persson139f4dc2019-08-02 09:29:58 +0200497 set_start_bitrate_bps_(0),
498 set_start_bitrate_time_ms_(0),
499 has_seen_first_bwe_drop_(false),
Pera48ddb72016-09-29 11:48:50 +0200500 max_data_payload_length_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000501 encoder_paused_and_dropped_frame_(false),
Sergey Silkin5ee69672019-07-02 14:18:34 +0200502 was_encode_called_since_last_initialization_(false),
philipele8ed8302019-07-03 11:53:48 +0200503 encoder_failed_(false),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100504 clock_(clock),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700505 degradation_preference_(DegradationPreference::DISABLED),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700506 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700507 last_captured_timestamp_(0),
508 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
509 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700510 last_frame_log_ms_(clock_->TimeInMilliseconds()),
511 captured_frame_count_(0),
512 dropped_frame_count_(0),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200513 pending_frame_post_time_us_(0),
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100514 accumulated_update_rect_{0, 0, 0, 0},
sprang1a646ee2016-12-01 06:34:11 -0800515 bitrate_observer_(nullptr),
Elad Alon8f01c4e2019-06-28 15:19:43 +0200516 fec_controller_override_(nullptr),
Niels Möller6bb5ab92019-01-11 11:11:10 +0100517 force_disable_frame_dropper_(false),
518 input_framerate_(kFrameRateAvergingWindowSizeMs, 1000),
519 pending_frame_drops_(0),
Niels Möller8f7ce222019-03-21 15:43:58 +0100520 next_frame_types_(1, VideoFrameType::kVideoFrameDelta),
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200521 frame_encode_metadata_writer_(this),
Erik Språng6a7baa72019-02-26 18:31:00 +0100522 experiment_groups_(GetExperimentGroups()),
philipelda5aa4d2019-04-26 13:37:37 +0200523 next_frame_id_(0),
Sebastian Jansson74682c12019-03-01 11:50:20 +0100524 encoder_queue_(task_queue_factory->CreateTaskQueue(
525 "EncoderQueue",
526 TaskQueueFactory::Priority::NORMAL)) {
Niels Möller213618e2018-07-24 09:29:58 +0200527 RTC_DCHECK(encoder_stats_observer);
Niels Möller73f29cb2018-01-31 16:09:31 +0100528 RTC_DCHECK(overuse_detector_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100529 RTC_DCHECK_GE(number_of_cores, 1);
philipelda5aa4d2019-04-26 13:37:37 +0200530
531 for (auto& state : encoder_buffer_state_)
532 state.fill(std::numeric_limits<int64_t>::max());
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000533}
534
mflodmancc3d4422017-08-03 08:27:51 -0700535VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700536 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700537 RTC_DCHECK(shutdown_event_.Wait(0))
538 << "Must call ::Stop() before destruction.";
539}
540
mflodmancc3d4422017-08-03 08:27:51 -0700541void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700542 RTC_DCHECK_RUN_ON(&thread_checker_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700543 source_proxy_->SetSource(nullptr, DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700544 encoder_queue_.PostTask([this] {
545 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700546 overuse_detector_->StopCheckForOveruse();
Erik Språngb7cb7b52019-02-26 15:52:33 +0100547 rate_allocator_ = nullptr;
sprang1a646ee2016-12-01 06:34:11 -0800548 bitrate_observer_ = nullptr;
Erik Språng6a7baa72019-02-26 18:31:00 +0100549 ReleaseEncoder();
kthelgason876222f2016-11-29 01:44:11 -0800550 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700551 shutdown_event_.Set();
552 });
553
554 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700555}
556
Niels Möller0327c2d2018-05-21 14:09:31 +0200557void VideoStreamEncoder::SetBitrateAllocationObserver(
sprang1a646ee2016-12-01 06:34:11 -0800558 VideoBitrateAllocationObserver* bitrate_observer) {
559 RTC_DCHECK_RUN_ON(&thread_checker_);
560 encoder_queue_.PostTask([this, bitrate_observer] {
561 RTC_DCHECK_RUN_ON(&encoder_queue_);
562 RTC_DCHECK(!bitrate_observer_);
563 bitrate_observer_ = bitrate_observer;
564 });
565}
566
Elad Alon8f01c4e2019-06-28 15:19:43 +0200567void VideoStreamEncoder::SetFecControllerOverride(
568 FecControllerOverride* fec_controller_override) {
569 encoder_queue_.PostTask([this, fec_controller_override] {
570 RTC_DCHECK_RUN_ON(&encoder_queue_);
571 RTC_DCHECK(!fec_controller_override_);
572 fec_controller_override_ = fec_controller_override;
573 if (encoder_) {
574 encoder_->SetFecControllerOverride(fec_controller_override_);
575 }
576 });
577}
578
mflodmancc3d4422017-08-03 08:27:51 -0700579void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700580 rtc::VideoSourceInterface<VideoFrame>* source,
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700581 const DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700582 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700583 source_proxy_->SetSource(source, degradation_preference);
584 encoder_queue_.PostTask([this, degradation_preference] {
585 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700586 if (degradation_preference_ != degradation_preference) {
587 // Reset adaptation state, so that we're not tricked into thinking there's
588 // an already pending request of the same type.
589 last_adaptation_request_.reset();
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700590 if (degradation_preference == DegradationPreference::BALANCED ||
591 degradation_preference_ == DegradationPreference::BALANCED) {
asaperssonf7e294d2017-06-13 23:25:22 -0700592 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
593 // AdaptCounter for all modes.
594 source_proxy_->ResetPixelFpsCount();
595 adapt_counters_.clear();
596 }
sprangc5d62e22017-04-02 23:53:04 -0700597 }
sprangb1ca0732017-02-01 08:38:12 -0800598 degradation_preference_ = degradation_preference;
Niels Möller4db138e2018-04-19 09:04:13 +0200599
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000600 if (encoder_)
Erik Språng7ca375c2019-02-06 16:20:17 +0100601 ConfigureQualityScaler(encoder_->GetEncoderInfo());
Niels Möller4db138e2018-04-19 09:04:13 +0200602
Niels Möller7dc26b72017-12-06 10:27:48 +0100603 if (!IsFramerateScalingEnabled(degradation_preference) &&
604 max_framerate_ != -1) {
605 // If frame rate scaling is no longer allowed, remove any potential
606 // allowance for longer frame intervals.
607 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
608 }
perkj803d97f2016-11-01 11:45:46 -0700609 });
perkja49cbd32016-09-16 07:53:41 -0700610}
611
mflodmancc3d4422017-08-03 08:27:51 -0700612void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700613 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700614 encoder_queue_.PostTask([this, sink] {
615 RTC_DCHECK_RUN_ON(&encoder_queue_);
616 sink_ = sink;
617 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000618}
619
mflodmancc3d4422017-08-03 08:27:51 -0700620void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700621 encoder_queue_.PostTask([this, start_bitrate_bps] {
622 RTC_DCHECK_RUN_ON(&encoder_queue_);
623 encoder_start_bitrate_bps_ = start_bitrate_bps;
Åsa Persson139f4dc2019-08-02 09:29:58 +0200624 set_start_bitrate_bps_ = start_bitrate_bps;
625 set_start_bitrate_time_ms_ = clock_->TimeInMilliseconds();
perkj26091b12016-09-01 01:17:40 -0700626 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000627}
Peter Boström00b9d212016-05-19 16:59:03 +0200628
mflodmancc3d4422017-08-03 08:27:51 -0700629void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200630 size_t max_data_payload_length) {
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100631 // TODO(srte): This struct should be replaced by a lambda with move capture
632 // when C++14 lambda is allowed.
633 struct ConfigureEncoderTask {
634 void operator()() {
Yves Gerey665174f2018-06-19 15:03:05 +0200635 encoder->ConfigureEncoderOnTaskQueue(std::move(config),
636 max_data_payload_length);
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100637 }
638 VideoStreamEncoder* encoder;
639 VideoEncoderConfig config;
640 size_t max_data_payload_length;
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100641 };
Yves Gerey665174f2018-06-19 15:03:05 +0200642 encoder_queue_.PostTask(
643 ConfigureEncoderTask{this, std::move(config), max_data_payload_length});
perkj26091b12016-09-01 01:17:40 -0700644}
645
mflodmancc3d4422017-08-03 08:27:51 -0700646void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
647 VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200648 size_t max_data_payload_length) {
perkj26091b12016-09-01 01:17:40 -0700649 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700650 RTC_DCHECK(sink_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100651 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200652
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000653 pending_encoder_creation_ =
Erik Språngd7329ca2019-02-21 21:19:53 +0100654 (!encoder_ || encoder_config_.video_format != config.video_format ||
655 max_data_payload_length_ != max_data_payload_length);
Pera48ddb72016-09-29 11:48:50 +0200656 encoder_config_ = std::move(config);
Erik Språngd7329ca2019-02-21 21:19:53 +0100657 max_data_payload_length_ = max_data_payload_length;
perkjfa10b552016-10-02 23:45:26 -0700658 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200659
perkjfa10b552016-10-02 23:45:26 -0700660 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100661 // if the frame resolution is known. Otherwise, the reconfiguration is
662 // deferred until the next frame to minimize the number of reconfigurations.
663 // The codec configuration depends on incoming video frame size.
664 if (last_frame_info_) {
665 ReconfigureEncoder();
Erik Språngd7329ca2019-02-21 21:19:53 +0100666 } else {
667 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
668 encoder_config_.video_format);
669 if (HasInternalSource()) {
670 last_frame_info_ = VideoFrameInfo(176, 144, false);
671 ReconfigureEncoder();
672 }
perkjfa10b552016-10-02 23:45:26 -0700673 }
674}
perkj26091b12016-09-01 01:17:40 -0700675
Sergey Silkin6456e352019-07-08 17:56:40 +0200676static absl::optional<VideoEncoder::ResolutionBitrateLimits>
677GetEncoderBitrateLimits(const VideoEncoder::EncoderInfo& encoder_info,
678 int frame_size_pixels) {
679 std::vector<VideoEncoder::ResolutionBitrateLimits> bitrate_limits =
680 encoder_info.resolution_bitrate_limits;
681
682 // Sort the list of bitrate limits by resolution.
683 sort(bitrate_limits.begin(), bitrate_limits.end(),
684 [](const VideoEncoder::ResolutionBitrateLimits& lhs,
685 const VideoEncoder::ResolutionBitrateLimits& rhs) {
686 return lhs.frame_size_pixels < rhs.frame_size_pixels;
687 });
688
689 for (size_t i = 0; i < bitrate_limits.size(); ++i) {
Sergey Silkin6b2cec12019-08-09 16:04:05 +0200690 RTC_DCHECK_GT(bitrate_limits[i].min_bitrate_bps, 0);
691 RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
692 bitrate_limits[i].min_bitrate_bps);
693 RTC_DCHECK_GT(bitrate_limits[i].max_bitrate_bps,
694 bitrate_limits[i].min_start_bitrate_bps);
Sergey Silkin6456e352019-07-08 17:56:40 +0200695 if (i > 0) {
696 // The bitrate limits aren't expected to decrease with resolution.
697 RTC_DCHECK_GE(bitrate_limits[i].min_bitrate_bps,
698 bitrate_limits[i - 1].min_bitrate_bps);
699 RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
700 bitrate_limits[i - 1].min_start_bitrate_bps);
701 RTC_DCHECK_GE(bitrate_limits[i].max_bitrate_bps,
702 bitrate_limits[i - 1].max_bitrate_bps);
703 }
704
705 if (bitrate_limits[i].frame_size_pixels >= frame_size_pixels) {
706 return absl::optional<VideoEncoder::ResolutionBitrateLimits>(
707 bitrate_limits[i]);
708 }
709 }
710
711 return absl::nullopt;
712}
713
Seth Hampsoncc7125f2018-02-02 08:46:16 -0800714// TODO(bugs.webrtc.org/8807): Currently this always does a hard
715// reconfiguration, but this isn't always necessary. Add in logic to only update
716// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
717// "soft" reconfiguration.
mflodmancc3d4422017-08-03 08:27:51 -0700718void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700719 RTC_DCHECK(pending_encoder_reconfiguration_);
720 std::vector<VideoStream> streams =
721 encoder_config_.video_stream_factory->CreateEncoderStreams(
722 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700723
ilnik6b826ef2017-06-16 06:53:48 -0700724 // TODO(ilnik): If configured resolution is significantly less than provided,
725 // e.g. because there are not enough SSRCs for all simulcast streams,
726 // signal new resolutions via SinkWants to video source.
727
728 // Stream dimensions may be not equal to given because of a simulcast
729 // restrictions.
Steve Antonbd631a02019-03-28 10:51:27 -0700730 auto highest_stream = absl::c_max_element(
731 streams, [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) {
Florent Castelli450b5482018-11-29 17:32:47 +0100732 return std::tie(a.width, a.height) < std::tie(b.width, b.height);
733 });
734 int highest_stream_width = static_cast<int>(highest_stream->width);
735 int highest_stream_height = static_cast<int>(highest_stream->height);
ilnik6b826ef2017-06-16 06:53:48 -0700736 // Dimension may be reduced to be, e.g. divisible by 4.
737 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
738 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
739 crop_width_ = last_frame_info_->width - highest_stream_width;
740 crop_height_ = last_frame_info_->height - highest_stream_height;
741
Sergey Silkin6456e352019-07-08 17:56:40 +0200742 bool encoder_reset_required = false;
743 if (pending_encoder_creation_) {
744 // Destroy existing encoder instance before creating a new one. Otherwise
745 // attempt to create another instance will fail if encoder factory
746 // supports only single instance of encoder of given type.
747 encoder_.reset();
748
749 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
750 encoder_config_.video_format);
751 // TODO(nisse): What to do if creating the encoder fails? Crash,
752 // or just discard incoming frames?
753 RTC_CHECK(encoder_);
754
755 encoder_->SetFecControllerOverride(fec_controller_override_);
756
757 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
758 encoder_config_.video_format);
759
760 encoder_reset_required = true;
761 }
762
763 encoder_bitrate_limits_ = GetEncoderBitrateLimits(
764 encoder_->GetEncoderInfo(),
765 last_frame_info_->width * last_frame_info_->height);
766
Sergey Silkin6b2cec12019-08-09 16:04:05 +0200767 if (streams.size() == 1 && encoder_bitrate_limits_) {
768 // Use bitrate limits recommended by encoder only if app didn't set any of
769 // them.
770 if (encoder_config_.max_bitrate_bps <= 0 &&
771 (encoder_config_.simulcast_layers.empty() ||
772 encoder_config_.simulcast_layers[0].min_bitrate_bps <= 0)) {
773 streams.back().min_bitrate_bps = encoder_bitrate_limits_->min_bitrate_bps;
774 streams.back().max_bitrate_bps = encoder_bitrate_limits_->max_bitrate_bps;
775 streams.back().target_bitrate_bps =
776 std::min(streams.back().target_bitrate_bps,
777 encoder_bitrate_limits_->max_bitrate_bps);
778 }
Sergey Silkin6456e352019-07-08 17:56:40 +0200779 }
780
Erik Språng08127a92016-11-16 16:41:30 +0100781 VideoCodec codec;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800782 if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100783 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100784 }
perkjfa10b552016-10-02 23:45:26 -0700785
“Michael277a6562018-06-01 14:09:19 -0500786 // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9.
787 if (encoder_config_.codec_type == kVideoCodecVP9) {
“Michael277a6562018-06-01 14:09:19 -0500788 // Lower max bitrate to the level codec actually can produce.
Erik Språngcf9cbf52019-09-04 14:30:57 +0200789 streams[0].max_bitrate_bps =
790 std::min(streams[0].max_bitrate_bps,
791 SvcRateAllocator::GetMaxBitrate(codec).bps<int>());
“Michael277a6562018-06-01 14:09:19 -0500792 streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000;
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100793 // target_bitrate_bps specifies the maximum padding bitrate.
“Michael277a6562018-06-01 14:09:19 -0500794 streams[0].target_bitrate_bps =
Erik Språngcf9cbf52019-09-04 14:30:57 +0200795 SvcRateAllocator::GetPaddingBitrate(codec).bps<int>();
“Michael277a6562018-06-01 14:09:19 -0500796 }
797
perkjfa10b552016-10-02 23:45:26 -0700798 codec.startBitrate =
799 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
800 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
801 codec.expect_encode_from_texture = last_frame_info_->is_texture;
Erik Språngd7329ca2019-02-21 21:19:53 +0100802 // Make sure the start bit rate is sane...
803 RTC_DCHECK_LE(codec.startBitrate, 1000000);
sprangfda496a2017-06-15 04:21:07 -0700804 max_framerate_ = codec.maxFramerate;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200805
806 // Inform source about max configured framerate.
807 int max_framerate = 0;
808 for (const auto& stream : streams) {
809 max_framerate = std::max(stream.max_framerate, max_framerate);
810 }
811 source_proxy_->SetMaxFramerate(max_framerate);
Stefan Holmere5904162015-03-26 11:11:06 +0100812
Erik Språngb7cb7b52019-02-26 15:52:33 +0100813 if (codec.maxBitrate == 0) {
814 // max is one bit per pixel
815 codec.maxBitrate =
816 (static_cast<int>(codec.height) * static_cast<int>(codec.width) *
817 static_cast<int>(codec.maxFramerate)) /
818 1000;
819 if (codec.startBitrate > codec.maxBitrate) {
820 // But if the user tries to set a higher start bit rate we will
821 // increase the max accordingly.
822 codec.maxBitrate = codec.startBitrate;
823 }
824 }
825
826 if (codec.startBitrate > codec.maxBitrate) {
827 codec.startBitrate = codec.maxBitrate;
828 }
829
Sergey Silkin65d9c4d2019-06-12 11:02:30 +0200830 rate_allocator_ =
831 settings_.bitrate_allocator_factory->CreateVideoBitrateAllocator(codec);
832
Erik Språngb7cb7b52019-02-26 15:52:33 +0100833 // Reset (release existing encoder) if one exists and anything except
Elad Alonfb087812019-05-02 23:25:34 +0200834 // start bitrate or max framerate has changed.
Sergey Silkin6456e352019-07-08 17:56:40 +0200835 if (!encoder_reset_required) {
836 encoder_reset_required = RequiresEncoderReset(
837 codec, send_codec_, was_encode_called_since_last_initialization_);
838 }
Erik Språngb7cb7b52019-02-26 15:52:33 +0100839 send_codec_ = codec;
840
Niels Möller4db138e2018-04-19 09:04:13 +0200841 // Keep the same encoder, as long as the video_format is unchanged.
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100842 // Encoder creation block is split in two since EncoderInfo needed to start
843 // CPU adaptation with the correct settings should be polled after
844 // encoder_->InitEncode().
Erik Språngb7cb7b52019-02-26 15:52:33 +0100845 bool success = true;
Sergey Silkin6456e352019-07-08 17:56:40 +0200846 if (encoder_reset_required) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100847 ReleaseEncoder();
Elad Alon370f93a2019-06-11 14:57:57 +0200848 const size_t max_data_payload_length = max_data_payload_length_ > 0
849 ? max_data_payload_length_
850 : kDefaultPayloadSize;
851 if (encoder_->InitEncode(
852 &send_codec_,
853 VideoEncoder::Settings(settings_.capabilities, number_of_cores_,
854 max_data_payload_length)) != 0) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100855 RTC_LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
856 "codec type: "
857 << CodecTypeToPayloadString(send_codec_.codecType)
858 << " (" << send_codec_.codecType << ")";
859 ReleaseEncoder();
860 success = false;
861 } else {
862 encoder_initialized_ = true;
863 encoder_->RegisterEncodeCompleteCallback(this);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200864 frame_encode_metadata_writer_.OnEncoderInit(send_codec_,
865 HasInternalSource());
Erik Språng6a7baa72019-02-26 18:31:00 +0100866 }
867
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200868 frame_encode_metadata_writer_.Reset();
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100869 last_encode_info_ms_ = absl::nullopt;
Sergey Silkin5ee69672019-07-02 14:18:34 +0200870 was_encode_called_since_last_initialization_ = false;
Erik Språngb7cb7b52019-02-26 15:52:33 +0100871 }
Erik Språngd7329ca2019-02-21 21:19:53 +0100872
873 if (success) {
Erik Språngd7329ca2019-02-21 21:19:53 +0100874 next_frame_types_.clear();
875 next_frame_types_.resize(
876 std::max(static_cast<int>(codec.numberOfSimulcastStreams), 1),
Niels Möller8f7ce222019-03-21 15:43:58 +0100877 VideoFrameType::kVideoFrameKey);
Erik Språngd7329ca2019-02-21 21:19:53 +0100878 RTC_LOG(LS_VERBOSE) << " max bitrate " << codec.maxBitrate
879 << " start bitrate " << codec.startBitrate
880 << " max frame rate " << codec.maxFramerate
881 << " max payload size " << max_data_payload_length_;
882 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100883 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
Erik Språngb7cb7b52019-02-26 15:52:33 +0100884 rate_allocator_ = nullptr;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000885 }
Peter Boström905f8e72016-03-02 16:59:56 +0100886
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100887 if (pending_encoder_creation_) {
888 overuse_detector_->StopCheckForOveruse();
889 overuse_detector_->StartCheckForOveruse(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100890 &encoder_queue_,
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100891 GetCpuOveruseOptions(
892 settings_, encoder_->GetEncoderInfo().is_hardware_accelerated),
893 this);
894 pending_encoder_creation_ = false;
895 }
896
Niels Möller6bb5ab92019-01-11 11:11:10 +0100897 int num_layers;
898 if (codec.codecType == kVideoCodecVP8) {
899 num_layers = codec.VP8()->numberOfTemporalLayers;
900 } else if (codec.codecType == kVideoCodecVP9) {
901 num_layers = codec.VP9()->numberOfTemporalLayers;
Johnny Lee1a1c52b2019-02-08 14:25:40 -0500902 } else if (codec.codecType == kVideoCodecH264) {
903 num_layers = codec.H264()->numberOfTemporalLayers;
Niels Möller6bb5ab92019-01-11 11:11:10 +0100904 } else if (codec.codecType == kVideoCodecGeneric &&
905 codec.numberOfSimulcastStreams > 0) {
906 // This is mainly for unit testing, disabling frame dropping.
907 // TODO(sprang): Add a better way to disable frame dropping.
908 num_layers = codec.simulcastStream[0].numberOfTemporalLayers;
909 } else {
910 num_layers = 1;
911 }
912
913 frame_dropper_.Reset();
914 frame_dropper_.SetRates(codec.startBitrate, max_framerate_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100915 // Force-disable frame dropper if either:
916 // * We have screensharing with layers.
917 // * "WebRTC-FrameDropper" field trial is "Disabled".
918 force_disable_frame_dropper_ =
919 field_trial::IsDisabled(kFrameDropperFieldTrial) ||
920 (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing);
921
Erik Språng7ca375c2019-02-06 16:20:17 +0100922 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
923 if (rate_control_settings_.UseEncoderBitrateAdjuster()) {
924 bitrate_adjuster_ = absl::make_unique<EncoderBitrateAdjuster>(codec);
925 bitrate_adjuster_->OnEncoderInfo(info);
926 }
927
Erik Språng4c6ca302019-04-08 15:14:01 +0200928 if (rate_allocator_ && last_encoder_rate_settings_) {
Niels Möller6bb5ab92019-01-11 11:11:10 +0100929 // We have a new rate allocator instance and already configured target
Erik Språng4c6ca302019-04-08 15:14:01 +0200930 // bitrate. Update the rate allocation and notify observers.
931 last_encoder_rate_settings_->framerate_fps = GetInputFramerateFps();
932 SetEncoderRates(
933 UpdateBitrateAllocationAndNotifyObserver(*last_encoder_rate_settings_));
Niels Möller6bb5ab92019-01-11 11:11:10 +0100934 }
ilnik35b7de42017-03-15 04:24:21 -0700935
Niels Möller213618e2018-07-24 09:29:58 +0200936 encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
Per512ecb32016-09-23 15:52:06 +0200937
perkjfa10b552016-10-02 23:45:26 -0700938 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100939
Pera48ddb72016-09-29 11:48:50 +0200940 sink_->OnEncoderConfigurationChanged(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100941 std::move(streams), encoder_config_.content_type,
942 encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800943
Niels Möller7dc26b72017-12-06 10:27:48 +0100944 // Get the current target framerate, ie the maximum framerate as specified by
945 // the current codec configuration, or any limit imposed by cpu adaption in
946 // maintain-resolution or balanced mode. This is used to make sure overuse
947 // detection doesn't needlessly trigger in low and/or variable framerate
948 // scenarios.
949 int target_framerate = std::min(
950 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
951 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +0200952
Erik Språng7ca375c2019-02-06 16:20:17 +0100953 ConfigureQualityScaler(info);
kthelgason2bc68642017-02-07 07:02:22 -0800954}
955
Erik Språng7ca375c2019-02-06 16:20:17 +0100956void VideoStreamEncoder::ConfigureQualityScaler(
957 const VideoEncoder::EncoderInfo& encoder_info) {
kthelgason2bc68642017-02-07 07:02:22 -0800958 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +0100959 const auto scaling_settings = encoder_info.scaling_settings;
asapersson36e9eb42017-03-31 05:29:12 -0700960 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700961 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +0100962 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -0700963
asapersson36e9eb42017-03-31 05:29:12 -0700964 if (quality_scaling_allowed) {
Benjamin Wright1f4173e2019-03-13 17:59:32 -0700965 if (quality_scaler_ == nullptr) {
asapersson09f05612017-05-15 23:40:18 -0700966 // Quality scaler has not already been configured.
Niels Möller225c7872018-02-22 15:03:53 +0100967
Åsa Perssona945aee2018-04-24 16:53:25 +0200968 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200969 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 16:53:25 +0200970 if (quality_scaling_experiment_enabled_) {
971 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
972 encoder_config_.codec_type);
973 }
Karl Wiberg918f50c2018-07-05 11:40:33 +0200974 // Since the interface is non-public, absl::make_unique can't do this
975 // upcast.
Niels Möller225c7872018-02-22 15:03:53 +0100976 AdaptationObserverInterface* observer = this;
Karl Wiberg918f50c2018-07-05 11:40:33 +0200977 quality_scaler_ = absl::make_unique<QualityScaler>(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100978 &encoder_queue_, observer,
979 experimental_thresholds ? *experimental_thresholds
980 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200981 has_seen_first_significant_bwe_change_ = false;
982 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 01:44:11 -0800983 }
984 } else {
985 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200986 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800987 }
asapersson09f05612017-05-15 23:40:18 -0700988
Åsa Persson12314192019-06-20 15:45:07 +0200989 if (degradation_preference_ == DegradationPreference::BALANCED &&
990 quality_scaler_ && last_frame_info_) {
991 absl::optional<VideoEncoder::QpThresholds> thresholds =
992 balanced_settings_.GetQpThresholds(encoder_config_.codec_type,
993 last_frame_info_->pixel_count());
994 if (thresholds) {
995 quality_scaler_->SetQpThresholds(*thresholds);
996 }
997 }
998
Niels Möller213618e2018-07-24 09:29:58 +0200999 encoder_stats_observer_->OnAdaptationChanged(
1000 VideoStreamEncoderObserver::AdaptationReason::kNone,
1001 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001002}
1003
mflodmancc3d4422017-08-03 08:27:51 -07001004void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -07001005 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -07001006 VideoFrame incoming_frame = video_frame;
1007
1008 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -07001009 int64_t current_time_us = clock_->TimeInMicroseconds();
1010 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
1011 // In some cases, e.g., when the frame from decoder is fed to encoder,
1012 // the timestamp may be set to the future. As the encoding pipeline assumes
1013 // capture time to be less than present time, we should reset the capture
1014 // timestamps here. Otherwise there may be issues with RTP send stream.
1015 if (incoming_frame.timestamp_us() > current_time_us)
1016 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -07001017
1018 // Capture time may come from clock with an offset and drift from clock_.
1019 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -08001020 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -07001021 capture_ntp_time_ms = video_frame.ntp_time_ms();
1022 } else if (video_frame.render_time_ms() != 0) {
1023 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
1024 } else {
nisse1c0dea82017-01-30 02:43:18 -08001025 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -07001026 }
1027 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
1028
1029 // Convert NTP time, in ms, to RTP timestamp.
1030 const int kMsToRtpTimestamp = 90;
1031 incoming_frame.set_timestamp(
1032 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
1033
1034 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
1035 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001036 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
1037 << incoming_frame.ntp_time_ms()
1038 << " <= " << last_captured_timestamp_
1039 << ") for incoming frame. Dropping.";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001040 encoder_queue_.PostTask([this, incoming_frame]() {
1041 RTC_DCHECK_RUN_ON(&encoder_queue_);
1042 accumulated_update_rect_.Union(incoming_frame.update_rect());
1043 });
perkj26091b12016-09-01 01:17:40 -07001044 return;
1045 }
1046
asapersson6ffb67d2016-09-12 00:10:45 -07001047 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -08001048 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
1049 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -07001050 log_stats = true;
1051 }
1052
perkj26091b12016-09-01 01:17:40 -07001053 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001054
1055 int64_t post_time_us = rtc::TimeMicros();
1056 ++posted_frames_waiting_for_encode_;
1057
1058 encoder_queue_.PostTask(
1059 [this, incoming_frame, post_time_us, log_stats]() {
1060 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 09:29:58 +02001061 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
1062 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001063 ++captured_frame_count_;
1064 const int posted_frames_waiting_for_encode =
1065 posted_frames_waiting_for_encode_.fetch_sub(1);
1066 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
1067 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +02001068 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001069 } else {
1070 // There is a newer frame in flight. Do not encode this frame.
1071 RTC_LOG(LS_VERBOSE)
1072 << "Incoming frame dropped due to that the encoder is blocked.";
1073 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 09:29:58 +02001074 encoder_stats_observer_->OnFrameDropped(
1075 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001076 accumulated_update_rect_.Union(incoming_frame.update_rect());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001077 }
1078 if (log_stats) {
1079 RTC_LOG(LS_INFO) << "Number of frames: captured "
1080 << captured_frame_count_
1081 << ", dropped (due to encoder blocked) "
1082 << dropped_frame_count_ << ", interval_ms "
1083 << kFrameLogIntervalMs;
1084 captured_frame_count_ = 0;
1085 dropped_frame_count_ = 0;
1086 }
1087 });
perkj26091b12016-09-01 01:17:40 -07001088}
1089
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001090void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 09:29:58 +02001091 encoder_stats_observer_->OnFrameDropped(
1092 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001093}
1094
mflodmancc3d4422017-08-03 08:27:51 -07001095bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -07001096 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +00001097 // Pause video if paused by caller or as long as the network is down or the
1098 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -07001099 // If the pacer queue has grown too large or the network is down,
Erik Språng4c6ca302019-04-08 15:14:01 +02001100 // |last_encoder_rate_settings_->encoder_target| will be 0.
1101 return !last_encoder_rate_settings_ ||
1102 last_encoder_rate_settings_->encoder_target == DataRate::Zero();
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +00001103}
1104
mflodmancc3d4422017-08-03 08:27:51 -07001105void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -07001106 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001107 // Start trace event only on the first frame after encoder is paused.
1108 if (!encoder_paused_and_dropped_frame_) {
1109 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
1110 }
1111 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001112}
1113
mflodmancc3d4422017-08-03 08:27:51 -07001114void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -07001115 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001116 // End trace event on first frame after encoder resumes, if frame was dropped.
1117 if (encoder_paused_and_dropped_frame_) {
1118 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
1119 }
1120 encoder_paused_and_dropped_frame_ = false;
1121}
1122
Erik Språng4c6ca302019-04-08 15:14:01 +02001123VideoStreamEncoder::EncoderRateSettings
1124VideoStreamEncoder::UpdateBitrateAllocationAndNotifyObserver(
1125 const EncoderRateSettings& rate_settings) {
1126 VideoBitrateAllocation new_allocation;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001127 // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
1128 // might cap the bitrate to the min bitrate configured.
Erik Språng4c6ca302019-04-08 15:14:01 +02001129 if (rate_allocator_ && rate_settings.encoder_target > DataRate::Zero()) {
Florent Castelli8bbdb5b2019-08-02 15:16:28 +02001130 new_allocation = rate_allocator_->Allocate(VideoBitrateAllocationParameters(
Florent Castellia8336d32019-09-09 13:36:55 +02001131 rate_settings.encoder_target, rate_settings.stable_encoder_target,
1132 rate_settings.framerate_fps));
Niels Möller6bb5ab92019-01-11 11:11:10 +01001133 }
1134
Erik Språng4c6ca302019-04-08 15:14:01 +02001135 if (bitrate_observer_ && new_allocation.get_sum_bps() > 0) {
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001136 if (encoder_ && encoder_initialized_) {
1137 // Avoid too old encoder_info_.
1138 const int64_t kMaxDiffMs = 100;
1139 const bool updated_recently =
1140 (last_encode_info_ms_ && ((clock_->TimeInMilliseconds() -
1141 *last_encode_info_ms_) < kMaxDiffMs));
1142 // Update allocation according to info from encoder.
1143 bitrate_observer_->OnBitrateAllocationUpdated(
1144 UpdateAllocationFromEncoderInfo(
Erik Språng4c6ca302019-04-08 15:14:01 +02001145 new_allocation,
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001146 updated_recently ? encoder_info_ : encoder_->GetEncoderInfo()));
1147 } else {
Erik Språng4c6ca302019-04-08 15:14:01 +02001148 bitrate_observer_->OnBitrateAllocationUpdated(new_allocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001149 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001150 }
1151
Erik Språng3d11e2f2019-04-15 14:48:30 +02001152 EncoderRateSettings new_rate_settings = rate_settings;
1153 new_rate_settings.bitrate = new_allocation;
Erik Språng5056af02019-09-02 15:53:11 +02001154 // VideoBitrateAllocator subclasses may allocate a bitrate higher than the
1155 // target in order to sustain the min bitrate of the video codec. In this
1156 // case, make sure the bandwidth allocation is at least equal the allocation
1157 // as that is part of the document contract for that field.
1158 new_rate_settings.bandwidth_allocation =
1159 std::max(new_rate_settings.bandwidth_allocation,
1160 DataRate::bps(new_rate_settings.bitrate.get_sum_bps()));
Erik Språng3d11e2f2019-04-15 14:48:30 +02001161
Erik Språng7ca375c2019-02-06 16:20:17 +01001162 if (bitrate_adjuster_) {
Erik Språng0e1a1f92019-02-18 18:45:13 +01001163 VideoBitrateAllocation adjusted_allocation =
Erik Språng3d11e2f2019-04-15 14:48:30 +02001164 bitrate_adjuster_->AdjustRateAllocation(new_rate_settings);
Erik Språng4c6ca302019-04-08 15:14:01 +02001165 RTC_LOG(LS_VERBOSE) << "Adjusting allocation, fps = "
1166 << rate_settings.framerate_fps << ", from "
1167 << new_allocation.ToString() << ", to "
Erik Språng0e1a1f92019-02-18 18:45:13 +01001168 << adjusted_allocation.ToString();
Erik Språng3d11e2f2019-04-15 14:48:30 +02001169 new_rate_settings.bitrate = adjusted_allocation;
Erik Språng7ca375c2019-02-06 16:20:17 +01001170 }
Erik Språng4c6ca302019-04-08 15:14:01 +02001171
Erik Språng3d11e2f2019-04-15 14:48:30 +02001172 return new_rate_settings;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001173}
1174
1175uint32_t VideoStreamEncoder::GetInputFramerateFps() {
1176 const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
Erik Språngd7329ca2019-02-21 21:19:53 +01001177 absl::optional<uint32_t> input_fps =
1178 input_framerate_.Rate(clock_->TimeInMilliseconds());
1179 if (!input_fps || *input_fps == 0) {
1180 return default_fps;
1181 }
1182 return *input_fps;
1183}
1184
1185void VideoStreamEncoder::SetEncoderRates(
Erik Språng4c6ca302019-04-08 15:14:01 +02001186 const EncoderRateSettings& rate_settings) {
1187 RTC_DCHECK_GT(rate_settings.framerate_fps, 0.0);
1188 const bool settings_changes = !last_encoder_rate_settings_ ||
1189 rate_settings != *last_encoder_rate_settings_;
1190 if (settings_changes) {
1191 last_encoder_rate_settings_ = rate_settings;
1192 }
1193
Erik Språng6a7baa72019-02-26 18:31:00 +01001194 if (!encoder_) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001195 return;
1196 }
1197
1198 // |bitrate_allocation| is 0 it means that the network is down or the send
1199 // pacer is full. We currently only report this if the encoder has an internal
1200 // source. If the encoder does not have an internal source, higher levels
1201 // are expected to not call AddVideoFrame. We do this since its unclear
1202 // how current encoder implementations behave when given a zero target
1203 // bitrate.
1204 // TODO(perkj): Make sure all known encoder implementations handle zero
1205 // target bitrate and remove this check.
Erik Språng4c6ca302019-04-08 15:14:01 +02001206 if (!HasInternalSource() && rate_settings.bitrate.get_sum_bps() == 0) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001207 return;
1208 }
1209
Erik Språng4c6ca302019-04-08 15:14:01 +02001210 if (settings_changes) {
1211 encoder_->SetRates(rate_settings);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001212 frame_encode_metadata_writer_.OnSetRates(
Erik Språng4c6ca302019-04-08 15:14:01 +02001213 rate_settings.bitrate,
1214 static_cast<uint32_t>(rate_settings.framerate_fps + 0.5));
Erik Språng6a7baa72019-02-26 18:31:00 +01001215 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001216}
1217
Sebastian Janssona3177052018-04-10 13:05:49 +02001218void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
1219 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -07001220 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -08001221
Per21d45d22016-10-30 21:37:57 +01001222 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -07001223 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -07001224 video_frame.is_texture() != last_frame_info_->is_texture) {
1225 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +01001226 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
1227 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +01001228 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
1229 << last_frame_info_->width << "x"
1230 << last_frame_info_->height
1231 << ", texture=" << last_frame_info_->is_texture << ".";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001232 // Force full frame update, since resolution has changed.
1233 accumulated_update_rect_ =
1234 VideoFrame::UpdateRect{0, 0, video_frame.width(), video_frame.height()};
perkjfa10b552016-10-02 23:45:26 -07001235 }
1236
Niels Möller4db138e2018-04-19 09:04:13 +02001237 // We have to create then encoder before the frame drop logic,
1238 // because the latter depends on encoder_->GetScalingSettings.
1239 // According to the testcase
1240 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
1241 // from GetScalingSettings should enable or disable the frame drop.
1242
Erik Språnga8d48ab2019-02-08 14:17:40 +01001243 // Update input frame rate before we start using it. If we update it after
Erik Språngd7329ca2019-02-21 21:19:53 +01001244 // any potential frame drop we are going to artificially increase frame sizes.
1245 // Poll the rate before updating, otherwise we risk the rate being estimated
1246 // a little too high at the start of the call when then window is small.
Niels Möller6bb5ab92019-01-11 11:11:10 +01001247 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språngd7329ca2019-02-21 21:19:53 +01001248 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001249
Niels Möller4db138e2018-04-19 09:04:13 +02001250 int64_t now_ms = clock_->TimeInMilliseconds();
1251 if (pending_encoder_reconfiguration_) {
1252 ReconfigureEncoder();
1253 last_parameters_update_ms_.emplace(now_ms);
1254 } else if (!last_parameters_update_ms_ ||
1255 now_ms - *last_parameters_update_ms_ >=
1256 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001257 if (last_encoder_rate_settings_) {
1258 // Clone rate settings before update, so that SetEncoderRates() will
1259 // actually detect the change between the input and
1260 // |last_encoder_rate_setings_|, triggering the call to SetRate() on the
1261 // encoder.
1262 EncoderRateSettings new_rate_settings = *last_encoder_rate_settings_;
1263 new_rate_settings.framerate_fps = static_cast<double>(framerate_fps);
1264 SetEncoderRates(
1265 UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
1266 }
Niels Möller4db138e2018-04-19 09:04:13 +02001267 last_parameters_update_ms_.emplace(now_ms);
1268 }
1269
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001270 // Because pending frame will be dropped in any case, we need to
1271 // remember its updated region.
1272 if (pending_frame_) {
1273 encoder_stats_observer_->OnFrameDropped(
1274 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
1275 accumulated_update_rect_.Union(pending_frame_->update_rect());
1276 }
1277
Sebastian Janssona3177052018-04-10 13:05:49 +02001278 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001279 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 08:49:53 +01001280 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -08001281 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 08:49:53 +01001282 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
Niels Möller213618e2018-07-24 09:29:58 +02001283 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 08:49:53 +01001284 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001285 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001286 // Storing references to a native buffer risks blocking frame capture.
1287 if (video_frame.video_frame_buffer()->type() !=
1288 VideoFrameBuffer::Type::kNative) {
1289 pending_frame_ = video_frame;
1290 pending_frame_post_time_us_ = time_when_posted_us;
1291 } else {
1292 // Ensure that any previously stored frame is dropped.
1293 pending_frame_.reset();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001294 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001295 }
kthelgason2bc68642017-02-07 07:02:22 -08001296 return;
1297 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001298 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -08001299
perkj26091b12016-09-01 01:17:40 -07001300 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001301 // Storing references to a native buffer risks blocking frame capture.
1302 if (video_frame.video_frame_buffer()->type() !=
1303 VideoFrameBuffer::Type::kNative) {
1304 if (pending_frame_)
1305 TraceFrameDropStart();
1306 pending_frame_ = video_frame;
1307 pending_frame_post_time_us_ = time_when_posted_us;
1308 } else {
1309 // Ensure that any previously stored frame is dropped.
1310 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +02001311 TraceFrameDropStart();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001312 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001313 }
perkj26091b12016-09-01 01:17:40 -07001314 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001315 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001316
1317 pending_frame_.reset();
Niels Möller6bb5ab92019-01-11 11:11:10 +01001318
1319 frame_dropper_.Leak(framerate_fps);
1320 // Frame dropping is enabled iff frame dropping is not force-disabled, and
1321 // rate controller is not trusted.
1322 const bool frame_dropping_enabled =
1323 !force_disable_frame_dropper_ &&
1324 !encoder_info_.has_trusted_rate_controller;
1325 frame_dropper_.Enable(frame_dropping_enabled);
1326 if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001327 RTC_LOG(LS_VERBOSE)
1328 << "Drop Frame: "
1329 << "target bitrate "
1330 << (last_encoder_rate_settings_
1331 ? last_encoder_rate_settings_->encoder_target.bps()
1332 : 0)
1333 << ", input frame rate " << framerate_fps;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001334 OnDroppedFrame(
1335 EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001336 accumulated_update_rect_.Union(video_frame.update_rect());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001337 return;
1338 }
1339
Sebastian Janssona3177052018-04-10 13:05:49 +02001340 EncodeVideoFrame(video_frame, time_when_posted_us);
1341}
1342
1343void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
1344 int64_t time_when_posted_us) {
1345 RTC_DCHECK_RUN_ON(&encoder_queue_);
philipele8ed8302019-07-03 11:53:48 +02001346
1347 // If the encoder fail we can't continue to encode frames. When this happens
1348 // the WebrtcVideoSender is notified and the whole VideoSendStream is
1349 // recreated.
1350 if (encoder_failed_)
1351 return;
1352
perkj26091b12016-09-01 01:17:40 -07001353 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +00001354
ilnik6b826ef2017-06-16 06:53:48 -07001355 VideoFrame out_frame(video_frame);
1356 // Crop frame if needed.
1357 if (crop_width_ > 0 || crop_height_ > 0) {
Noah Richards51db4212019-06-12 06:59:12 -07001358 // If the frame can't be converted to I420, drop it.
1359 auto i420_buffer = video_frame.video_frame_buffer()->ToI420();
1360 if (!i420_buffer) {
1361 RTC_LOG(LS_ERROR) << "Frame conversion for crop failed, dropping frame.";
1362 return;
1363 }
ilnik6b826ef2017-06-16 06:53:48 -07001364 int cropped_width = video_frame.width() - crop_width_;
1365 int cropped_height = video_frame.height() - crop_height_;
1366 rtc::scoped_refptr<I420Buffer> cropped_buffer =
1367 I420Buffer::Create(cropped_width, cropped_height);
1368 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
1369 // happen after SinkWants signaled correctly from ReconfigureEncoder.
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001370 VideoFrame::UpdateRect update_rect = video_frame.update_rect();
ilnik6b826ef2017-06-16 06:53:48 -07001371 if (crop_width_ < 4 && crop_height_ < 4) {
Noah Richards51db4212019-06-12 06:59:12 -07001372 cropped_buffer->CropAndScaleFrom(*i420_buffer, crop_width_ / 2,
1373 crop_height_ / 2, cropped_width,
1374 cropped_height);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001375 update_rect.offset_x -= crop_width_ / 2;
1376 update_rect.offset_y -= crop_height_ / 2;
1377 update_rect.Intersect(
1378 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height});
1379
ilnik6b826ef2017-06-16 06:53:48 -07001380 } else {
Noah Richards51db4212019-06-12 06:59:12 -07001381 cropped_buffer->ScaleFrom(*i420_buffer);
Ilya Nikolaevskiy1c90cab2019-03-07 15:30:58 +01001382 if (!update_rect.IsEmpty()) {
1383 // Since we can't reason about pixels after scaling, we invalidate whole
1384 // picture, if anything changed.
1385 update_rect =
1386 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height};
1387 }
ilnik6b826ef2017-06-16 06:53:48 -07001388 }
Ilya Nikolaevskiy4fc08552019-06-05 15:59:12 +02001389 out_frame.set_video_frame_buffer(cropped_buffer);
1390 out_frame.set_update_rect(update_rect);
ilnik6b826ef2017-06-16 06:53:48 -07001391 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001392 // Since accumulated_update_rect_ is constructed before cropping,
1393 // we can't trust it. If any changes were pending, we invalidate whole
1394 // frame here.
1395 if (!accumulated_update_rect_.IsEmpty()) {
1396 accumulated_update_rect_ =
1397 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1398 }
1399 }
1400
1401 if (!accumulated_update_rect_.IsEmpty()) {
1402 accumulated_update_rect_.Union(out_frame.update_rect());
1403 accumulated_update_rect_.Intersect(
1404 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()});
1405 out_frame.set_update_rect(accumulated_update_rect_);
1406 accumulated_update_rect_.MakeEmptyUpdate();
ilnik6b826ef2017-06-16 06:53:48 -07001407 }
1408
Magnus Jedvert26679d62015-04-07 14:07:41 +02001409 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +00001410 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +00001411
Niels Möller7dc26b72017-12-06 10:27:48 +01001412 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -07001413
Erik Språnge2fd86a2018-10-24 11:32:39 +02001414 // Encoder metadata needs to be updated before encode complete callback.
1415 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
1416 if (info.implementation_name != encoder_info_.implementation_name) {
1417 encoder_stats_observer_->OnEncoderImplementationChanged(
1418 info.implementation_name);
Erik Språng7ca375c2019-02-06 16:20:17 +01001419 if (bitrate_adjuster_) {
1420 // Encoder implementation changed, reset overshoot detector states.
1421 bitrate_adjuster_->Reset();
1422 }
Erik Språnge2fd86a2018-10-24 11:32:39 +02001423 }
Erik Språng7ca375c2019-02-06 16:20:17 +01001424
1425 if (bitrate_adjuster_) {
1426 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1427 if (info.fps_allocation[si] != encoder_info_.fps_allocation[si]) {
1428 bitrate_adjuster_->OnEncoderInfo(info);
1429 break;
1430 }
1431 }
1432 }
1433
Erik Språnge2fd86a2018-10-24 11:32:39 +02001434 encoder_info_ = info;
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001435 last_encode_info_ms_ = clock_->TimeInMilliseconds();
Erik Språngb7cb7b52019-02-26 15:52:33 +01001436 RTC_DCHECK_EQ(send_codec_.width, out_frame.width());
1437 RTC_DCHECK_EQ(send_codec_.height, out_frame.height());
Erik Språngd7329ca2019-02-21 21:19:53 +01001438 const VideoFrameBuffer::Type buffer_type =
1439 out_frame.video_frame_buffer()->type();
1440 const bool is_buffer_type_supported =
1441 buffer_type == VideoFrameBuffer::Type::kI420 ||
1442 (buffer_type == VideoFrameBuffer::Type::kNative &&
Erik Språng6a7baa72019-02-26 18:31:00 +01001443 info.supports_native_handle);
Erik Språngd7329ca2019-02-21 21:19:53 +01001444
1445 if (!is_buffer_type_supported) {
1446 // This module only supports software encoding.
1447 rtc::scoped_refptr<I420BufferInterface> converted_buffer(
1448 out_frame.video_frame_buffer()->ToI420());
1449
1450 if (!converted_buffer) {
1451 RTC_LOG(LS_ERROR) << "Frame conversion failed, dropping frame.";
1452 return;
1453 }
1454
Ilya Nikolaevskiycfff6522019-05-03 14:34:35 +02001455 VideoFrame::UpdateRect update_rect = out_frame.update_rect();
1456 if (!update_rect.IsEmpty() &&
1457 out_frame.video_frame_buffer()->GetI420() == nullptr) {
1458 // UpdatedRect is reset to full update if it's not empty, and buffer was
1459 // converted, therefore we can't guarantee that pixels outside of
1460 // UpdateRect didn't change comparing to the previous frame.
1461 update_rect =
1462 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1463 }
Ilya Nikolaevskiy1c90cab2019-03-07 15:30:58 +01001464
Ilya Nikolaevskiy4fc08552019-06-05 15:59:12 +02001465 out_frame.set_video_frame_buffer(converted_buffer);
1466 out_frame.set_update_rect(update_rect);
Erik Språngd7329ca2019-02-21 21:19:53 +01001467 }
Erik Språng6a7baa72019-02-26 18:31:00 +01001468
1469 TRACE_EVENT1("webrtc", "VCMGenericEncoder::Encode", "timestamp",
1470 out_frame.timestamp());
1471
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001472 frame_encode_metadata_writer_.OnEncodeStarted(out_frame);
Erik Språng6a7baa72019-02-26 18:31:00 +01001473
Niels Möllerc8d2e732019-03-06 12:00:33 +01001474 const int32_t encode_status = encoder_->Encode(out_frame, &next_frame_types_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001475 was_encode_called_since_last_initialization_ = true;
Erik Språng6a7baa72019-02-26 18:31:00 +01001476
Erik Språngd7329ca2019-02-21 21:19:53 +01001477 if (encode_status < 0) {
philipele8ed8302019-07-03 11:53:48 +02001478 if (encode_status == WEBRTC_VIDEO_CODEC_ENCODER_FAILURE) {
1479 RTC_LOG(LS_ERROR) << "Encoder failed, failing encoder format: "
1480 << encoder_config_.video_format.ToString();
1481 if (settings_.encoder_failure_callback) {
1482 encoder_failed_ = true;
1483 settings_.encoder_failure_callback->OnEncoderFailure();
1484 } else {
1485 RTC_LOG(LS_ERROR)
1486 << "Encoder failed but no encoder fallback callback is registered";
1487 }
1488 } else {
1489 RTC_LOG(LS_ERROR) << "Failed to encode frame. Error code: "
1490 << encode_status;
1491 }
1492
Erik Språngd7329ca2019-02-21 21:19:53 +01001493 return;
1494 }
1495
1496 for (auto& it : next_frame_types_) {
Niels Möller8f7ce222019-03-21 15:43:58 +01001497 it = VideoFrameType::kVideoFrameDelta;
Erik Språngd7329ca2019-02-21 21:19:53 +01001498 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001499}
niklase@google.com470e71d2011-07-07 08:21:25 +00001500
mflodmancc3d4422017-08-03 08:27:51 -07001501void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -07001502 if (!encoder_queue_.IsCurrent()) {
1503 encoder_queue_.PostTask([this] { SendKeyFrame(); });
1504 return;
1505 }
1506 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +01001507 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Erik Språngd7329ca2019-02-21 21:19:53 +01001508 RTC_DCHECK(!next_frame_types_.empty());
Sergey Silkine62a08a2019-05-13 13:45:39 +02001509
1510 // TODO(webrtc:10615): Map keyframe request to spatial layer.
1511 std::fill(next_frame_types_.begin(), next_frame_types_.end(),
1512 VideoFrameType::kVideoFrameKey);
1513
Erik Språngd7329ca2019-02-21 21:19:53 +01001514 if (HasInternalSource()) {
1515 // Try to request the frame if we have an external encoder with
1516 // internal source since AddVideoFrame never will be called.
Erik Språng6a7baa72019-02-26 18:31:00 +01001517
1518 // TODO(nisse): Used only with internal source. Delete as soon as
1519 // that feature is removed. The only implementation I've been able
1520 // to find ignores what's in the frame. With one exception: It seems
1521 // a few test cases, e.g.,
1522 // VideoSendStreamTest.VideoSendStreamStopSetEncoderRateToZero, set
1523 // internal_source to true and use FakeEncoder. And the latter will
1524 // happily encode this 1x1 frame and pass it on down the pipeline.
1525 if (encoder_->Encode(VideoFrame::Builder()
1526 .set_video_frame_buffer(I420Buffer::Create(1, 1))
1527 .set_rotation(kVideoRotation_0)
1528 .set_timestamp_us(0)
1529 .build(),
Erik Språng6a7baa72019-02-26 18:31:00 +01001530 &next_frame_types_) == WEBRTC_VIDEO_CODEC_OK) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001531 // Try to remove just-performed keyframe request, if stream still exists.
Sergey Silkine62a08a2019-05-13 13:45:39 +02001532 std::fill(next_frame_types_.begin(), next_frame_types_.end(),
1533 VideoFrameType::kVideoFrameDelta);
Erik Språngd7329ca2019-02-21 21:19:53 +01001534 }
1535 }
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00001536}
1537
Elad Alonb6ef99b2019-04-10 16:37:07 +02001538void VideoStreamEncoder::OnLossNotification(
1539 const VideoEncoder::LossNotification& loss_notification) {
1540 if (!encoder_queue_.IsCurrent()) {
1541 encoder_queue_.PostTask(
1542 [this, loss_notification] { OnLossNotification(loss_notification); });
1543 return;
1544 }
1545
1546 RTC_DCHECK_RUN_ON(&encoder_queue_);
1547 if (encoder_) {
1548 encoder_->OnLossNotification(loss_notification);
1549 }
1550}
1551
mflodmancc3d4422017-08-03 08:27:51 -07001552EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001553 const EncodedImage& encoded_image,
1554 const CodecSpecificInfo* codec_specific_info,
1555 const RTPFragmentationHeader* fragmentation) {
Erik Språng6a7baa72019-02-26 18:31:00 +01001556 TRACE_EVENT_INSTANT1("webrtc", "VCMEncodedFrameCallback::Encoded",
1557 "timestamp", encoded_image.Timestamp());
1558 const size_t spatial_idx = encoded_image.SpatialIndex().value_or(0);
1559 EncodedImage image_copy(encoded_image);
1560
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001561 frame_encode_metadata_writer_.FillTimingInfo(spatial_idx, &image_copy);
Erik Språng6a7baa72019-02-26 18:31:00 +01001562
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001563 std::unique_ptr<RTPFragmentationHeader> fragmentation_copy =
1564 frame_encode_metadata_writer_.UpdateBitstream(codec_specific_info,
1565 fragmentation, &image_copy);
1566
Erik Språng6a7baa72019-02-26 18:31:00 +01001567 // Piggyback ALR experiment group id and simulcast id into the content type.
1568 const uint8_t experiment_id =
1569 experiment_groups_[videocontenttypehelpers::IsScreenshare(
1570 image_copy.content_type_)];
1571
1572 // TODO(ilnik): This will force content type extension to be present even
1573 // for realtime video. At the expense of miniscule overhead we will get
1574 // sliced receive statistics.
1575 RTC_CHECK(videocontenttypehelpers::SetExperimentId(&image_copy.content_type_,
1576 experiment_id));
1577 // We count simulcast streams from 1 on the wire. That's why we set simulcast
1578 // id in content type to +1 of that is actual simulcast index. This is because
1579 // value 0 on the wire is reserved for 'no simulcast stream specified'.
1580 RTC_CHECK(videocontenttypehelpers::SetSimulcastId(
1581 &image_copy.content_type_, static_cast<uint8_t>(spatial_idx + 1)));
1582
perkj26091b12016-09-01 01:17:40 -07001583 // Encoded is called on whatever thread the real encoder implementation run
1584 // on. In the case of hardware encoders, there might be several encoders
1585 // running in parallel on different threads.
Erik Språng6a7baa72019-02-26 18:31:00 +01001586 encoder_stats_observer_->OnSendEncodedImage(image_copy, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -07001587
philipelda5aa4d2019-04-26 13:37:37 +02001588 // The simulcast id is signaled in the SpatialIndex. This makes it impossible
1589 // to do simulcast for codecs that actually support spatial layers since we
1590 // can't distinguish between an actual spatial layer and a simulcast stream.
1591 // TODO(bugs.webrtc.org/10520): Signal the simulcast id explicitly.
1592 int simulcast_id = 0;
1593 if (codec_specific_info &&
1594 (codec_specific_info->codecType == kVideoCodecVP8 ||
1595 codec_specific_info->codecType == kVideoCodecH264 ||
1596 codec_specific_info->codecType == kVideoCodecGeneric)) {
1597 simulcast_id = encoded_image.SpatialIndex().value_or(0);
1598 }
1599
1600 std::unique_ptr<CodecSpecificInfo> codec_info_copy;
1601 {
1602 rtc::CritScope cs(&encoded_image_lock_);
1603
1604 if (codec_specific_info && codec_specific_info->generic_frame_info) {
1605 codec_info_copy =
1606 absl::make_unique<CodecSpecificInfo>(*codec_specific_info);
1607 GenericFrameInfo& generic_info = *codec_info_copy->generic_frame_info;
1608 generic_info.frame_id = next_frame_id_++;
1609
1610 if (encoder_buffer_state_.size() <= static_cast<size_t>(simulcast_id)) {
1611 RTC_LOG(LS_ERROR) << "At most " << encoder_buffer_state_.size()
1612 << " simulcast streams supported.";
1613 } else {
1614 std::array<int64_t, kMaxEncoderBuffers>& state =
1615 encoder_buffer_state_[simulcast_id];
1616 for (const CodecBufferUsage& buffer : generic_info.encoder_buffers) {
1617 if (state.size() <= static_cast<size_t>(buffer.id)) {
1618 RTC_LOG(LS_ERROR)
1619 << "At most " << state.size() << " encoder buffers supported.";
1620 break;
1621 }
1622
1623 if (buffer.referenced) {
1624 int64_t diff = generic_info.frame_id - state[buffer.id];
1625 if (diff <= 0) {
1626 RTC_LOG(LS_ERROR) << "Invalid frame diff: " << diff << ".";
1627 } else if (absl::c_find(generic_info.frame_diffs, diff) ==
1628 generic_info.frame_diffs.end()) {
1629 generic_info.frame_diffs.push_back(diff);
1630 }
1631 }
1632
1633 if (buffer.updated)
1634 state[buffer.id] = generic_info.frame_id;
1635 }
1636 }
1637 }
1638 }
1639
1640 EncodedImageCallback::Result result = sink_->OnEncodedImage(
1641 image_copy, codec_info_copy ? codec_info_copy.get() : codec_specific_info,
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001642 fragmentation_copy ? fragmentation_copy.get() : fragmentation);
perkjbc75d972016-05-02 06:31:25 -07001643
Erik Språng7ca375c2019-02-06 16:20:17 +01001644 // We are only interested in propagating the meta-data about the image, not
1645 // encoded data itself, to the post encode function. Since we cannot be sure
1646 // the pointer will still be valid when run on the task queue, set it to null.
Erik Språng6a7baa72019-02-26 18:31:00 +01001647 image_copy.set_buffer(nullptr, 0);
Niels Möller83dbeac2017-12-14 16:39:44 +01001648
Erik Språng7ca375c2019-02-06 16:20:17 +01001649 int temporal_index = 0;
1650 if (codec_specific_info) {
1651 if (codec_specific_info->codecType == kVideoCodecVP9) {
1652 temporal_index = codec_specific_info->codecSpecific.VP9.temporal_idx;
1653 } else if (codec_specific_info->codecType == kVideoCodecVP8) {
1654 temporal_index = codec_specific_info->codecSpecific.VP8.temporalIdx;
1655 }
1656 }
1657 if (temporal_index == kNoTemporalIdx) {
1658 temporal_index = 0;
Niels Möller83dbeac2017-12-14 16:39:44 +01001659 }
1660
Erik Språng982dc792019-03-13 16:33:02 +01001661 RunPostEncode(image_copy, rtc::TimeMicros(), temporal_index);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001662
1663 if (result.error == Result::OK) {
1664 // In case of an internal encoder running on a separate thread, the
1665 // decision to drop a frame might be a frame late and signaled via
1666 // atomic flag. This is because we can't easily wait for the worker thread
1667 // without risking deadlocks, eg during shutdown when the worker thread
1668 // might be waiting for the internal encoder threads to stop.
1669 if (pending_frame_drops_.load() > 0) {
1670 int pending_drops = pending_frame_drops_.fetch_sub(1);
1671 RTC_DCHECK_GT(pending_drops, 0);
1672 result.drop_next_frame = true;
1673 }
1674 }
perkj803d97f2016-11-01 11:45:46 -07001675
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001676 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001677}
1678
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001679void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
1680 switch (reason) {
1681 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 09:29:58 +02001682 encoder_stats_observer_->OnFrameDropped(
1683 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001684 encoder_queue_.PostTask([this] {
1685 RTC_DCHECK_RUN_ON(&encoder_queue_);
1686 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +02001687 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001688 });
1689 break;
1690 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 09:29:58 +02001691 encoder_stats_observer_->OnFrameDropped(
1692 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 16:53:25 +02001693 encoder_queue_.PostTask([this] {
1694 RTC_DCHECK_RUN_ON(&encoder_queue_);
1695 if (quality_scaler_)
1696 quality_scaler_->ReportDroppedFrameByEncoder();
1697 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001698 break;
1699 }
kthelgason876222f2016-11-29 01:44:11 -08001700}
1701
Erik Språng610c7632019-03-06 15:37:33 +01001702void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate,
Florent Castellia8336d32019-09-09 13:36:55 +02001703 DataRate stable_target_bitrate,
Erik Språng4c6ca302019-04-08 15:14:01 +02001704 DataRate link_allocation,
mflodmancc3d4422017-08-03 08:27:51 -07001705 uint8_t fraction_lost,
1706 int64_t round_trip_time_ms) {
Sebastian Jansson5a000162019-04-12 11:21:32 +02001707 RTC_DCHECK_GE(link_allocation, target_bitrate);
perkj26091b12016-09-01 01:17:40 -07001708 if (!encoder_queue_.IsCurrent()) {
Florent Castellia8336d32019-09-09 13:36:55 +02001709 encoder_queue_.PostTask([this, target_bitrate, stable_target_bitrate,
1710 link_allocation, fraction_lost,
1711 round_trip_time_ms] {
1712 OnBitrateUpdated(target_bitrate, stable_target_bitrate, link_allocation,
1713 fraction_lost, round_trip_time_ms);
Erik Språng610c7632019-03-06 15:37:33 +01001714 });
perkj26091b12016-09-01 01:17:40 -07001715 return;
1716 }
1717 RTC_DCHECK_RUN_ON(&encoder_queue_);
1718 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
1719
Erik Språng610c7632019-03-06 15:37:33 +01001720 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << target_bitrate.bps()
Florent Castellia8336d32019-09-09 13:36:55 +02001721 << " stable bitrate = " << stable_target_bitrate.bps()
Erik Språng4c6ca302019-04-08 15:14:01 +02001722 << " link allocation bitrate = " << link_allocation.bps()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001723 << " packet loss " << static_cast<int>(fraction_lost)
1724 << " rtt " << round_trip_time_ms;
Åsa Persson139f4dc2019-08-02 09:29:58 +02001725
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001726 // On significant changes to BWE at the start of the call,
1727 // enable frame drops to quickly react to jumps in available bandwidth.
1728 if (encoder_start_bitrate_bps_ != 0 &&
1729 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
1730 initial_framedrop_on_bwe_enabled_ &&
Erik Språng610c7632019-03-06 15:37:33 +01001731 abs_diff(target_bitrate.bps(), encoder_start_bitrate_bps_) >=
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001732 kFramedropThreshold * encoder_start_bitrate_bps_) {
1733 // Reset initial framedrop feature when first real BW estimate arrives.
1734 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
1735 // without an actual BW estimate.
1736 initial_framedrop_ = 0;
1737 has_seen_first_significant_bwe_change_ = true;
1738 }
Åsa Persson139f4dc2019-08-02 09:29:58 +02001739 if (set_start_bitrate_bps_ > 0 && !has_seen_first_bwe_drop_ &&
1740 quality_scaler_ && quality_scaler_settings_.InitialBitrateIntervalMs() &&
1741 quality_scaler_settings_.InitialBitrateFactor()) {
1742 int64_t diff_ms = clock_->TimeInMilliseconds() - set_start_bitrate_time_ms_;
1743 if (diff_ms < quality_scaler_settings_.InitialBitrateIntervalMs().value() &&
1744 (target_bitrate.bps() <
1745 (set_start_bitrate_bps_ *
1746 quality_scaler_settings_.InitialBitrateFactor().value()))) {
1747 RTC_LOG(LS_INFO) << "Reset initial_framedrop_. Start bitrate: "
1748 << set_start_bitrate_bps_
1749 << ", target bitrate: " << target_bitrate.bps();
1750 initial_framedrop_ = 0;
1751 has_seen_first_bwe_drop_ = true;
1752 }
1753 }
perkj26091b12016-09-01 01:17:40 -07001754
Elad Aloncde8ab22019-03-20 11:56:20 +01001755 if (encoder_) {
1756 encoder_->OnPacketLossRateUpdate(static_cast<float>(fraction_lost) / 256.f);
1757 encoder_->OnRttUpdate(round_trip_time_ms);
1758 }
1759
Niels Möller6bb5ab92019-01-11 11:11:10 +01001760 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språng610c7632019-03-06 15:37:33 +01001761 frame_dropper_.SetRates((target_bitrate.bps() + 500) / 1000, framerate_fps);
Erik Språng4c6ca302019-04-08 15:14:01 +02001762 const bool video_is_suspended = target_bitrate == DataRate::Zero();
1763 const bool video_suspension_changed = video_is_suspended != EncoderPaused();
1764
Florent Castellia8336d32019-09-09 13:36:55 +02001765 EncoderRateSettings new_rate_settings{
1766 VideoBitrateAllocation(), static_cast<double>(framerate_fps),
1767 link_allocation, target_bitrate, stable_target_bitrate};
Erik Språng4c6ca302019-04-08 15:14:01 +02001768 SetEncoderRates(UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
perkj26091b12016-09-01 01:17:40 -07001769
Erik Språng610c7632019-03-06 15:37:33 +01001770 encoder_start_bitrate_bps_ = target_bitrate.bps() != 0
1771 ? target_bitrate.bps()
1772 : encoder_start_bitrate_bps_;
Peter Boströmd153a372015-11-10 15:27:12 +00001773
sprang552c7c72017-02-13 04:41:45 -08001774 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001775 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
1776 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 09:29:58 +02001777 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +02001778 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001779 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
1780 !DropDueToSize(pending_frame_->size())) {
1781 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
1782 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
1783 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
1784 pending_frame_.reset();
1785 }
1786}
1787
1788bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001789 if (initial_framedrop_ < kMaxInitialFramedrop &&
Sebastian Janssona3177052018-04-10 13:05:49 +02001790 encoder_start_bitrate_bps_ > 0) {
1791 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
1792 return pixel_count > 320 * 240;
1793 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
1794 return pixel_count > 640 * 480;
1795 }
1796 }
1797 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001798}
1799
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001800bool VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001801 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -07001802 AdaptationRequest adaptation_request = {
1803 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001804 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001805 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -07001806
sprangc5d62e22017-04-02 23:53:04 -07001807 bool downgrade_requested =
1808 last_adaptation_request_ &&
1809 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1810
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001811 bool did_adapt = true;
1812
sprangc5d62e22017-04-02 23:53:04 -07001813 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001814 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-13 23:25:22 -07001815 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001816 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-02 23:53:04 -07001817 if (downgrade_requested &&
1818 adaptation_request.input_pixel_count_ >=
1819 last_adaptation_request_->input_pixel_count_) {
1820 // Don't request lower resolution if the current resolution is not
1821 // lower than the last time we asked for the resolution to be lowered.
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001822 return true;
sprangc5d62e22017-04-02 23:53:04 -07001823 }
1824 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001825 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-02 23:53:04 -07001826 if (adaptation_request.framerate_fps_ <= 0 ||
1827 (downgrade_requested &&
1828 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1829 // If no input fps estimate available, can't determine how to scale down
1830 // framerate. Otherwise, don't request lower framerate if we don't have
1831 // a valid frame rate. Since framerate, unlike resolution, is a measure
1832 // we have to estimate, and can fluctuate naturally over time, don't
1833 // make the same kind of limitations as for resolution, but trust the
1834 // overuse detector to not trigger too often.
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001835 return true;
sprangc5d62e22017-04-02 23:53:04 -07001836 }
1837 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001838 case DegradationPreference::DISABLED:
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001839 return true;
sprang84a37592017-02-10 07:04:27 -08001840 }
sprangc5d62e22017-04-02 23:53:04 -07001841
sprangc5d62e22017-04-02 23:53:04 -07001842 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001843 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001844 // Try scale down framerate, if lower.
Åsa Persson48284b82019-07-08 10:01:12 +02001845 int fps = balanced_settings_.MinFps(encoder_config_.codec_type,
1846 last_frame_info_->pixel_count());
asaperssonf7e294d2017-06-13 23:25:22 -07001847 if (source_proxy_->RestrictFramerate(fps)) {
1848 GetAdaptCounter().IncrementFramerate(reason);
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001849 // Check if requested fps is higher (or close to) input fps.
1850 absl::optional<int> min_diff =
1851 balanced_settings_.MinFpsDiff(last_frame_info_->pixel_count());
1852 if (min_diff && adaptation_request.framerate_fps_ > 0) {
1853 int fps_diff = adaptation_request.framerate_fps_ - fps;
1854 if (fps_diff < min_diff.value()) {
1855 did_adapt = false;
1856 }
1857 }
asaperssonf7e294d2017-06-13 23:25:22 -07001858 break;
1859 }
1860 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001861 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001862 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001863 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001864 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001865 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07001866 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07001867 adaptation_request.input_pixel_count_,
Erik Språnge2fd86a2018-10-24 11:32:39 +02001868 encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001869 &min_pixels_reached)) {
1870 if (min_pixels_reached)
Niels Möller213618e2018-07-24 09:29:58 +02001871 encoder_stats_observer_->OnMinPixelLimitReached();
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001872 return true;
asaperssond0de2952017-04-21 01:47:31 -07001873 }
asaperssonf7e294d2017-06-13 23:25:22 -07001874 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001875 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001876 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001877 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001878 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001879 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1880 adaptation_request.framerate_fps_);
1881 if (requested_framerate == -1)
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001882 return true;
sprangfda496a2017-06-15 04:21:07 -07001883 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001884 overuse_detector_->OnTargetFramerateUpdated(
1885 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001886 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001887 break;
sprangfda496a2017-06-15 04:21:07 -07001888 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001889 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001890 RTC_NOTREACHED();
1891 }
1892
asaperssond0de2952017-04-21 01:47:31 -07001893 last_adaptation_request_.emplace(adaptation_request);
1894
asapersson09f05612017-05-15 23:40:18 -07001895 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001896
Mirko Bonadei675513b2017-11-09 11:09:25 +01001897 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001898 return did_adapt;
perkj26091b12016-09-01 01:17:40 -07001899}
1900
mflodmancc3d4422017-08-03 08:27:51 -07001901void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001902 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001903
1904 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1905 int num_downgrades = adapt_counter.TotalCount(reason);
1906 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001907 return;
asapersson09f05612017-05-15 23:40:18 -07001908 RTC_DCHECK_GT(num_downgrades, 0);
1909
sprangc5d62e22017-04-02 23:53:04 -07001910 AdaptationRequest adaptation_request = {
1911 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001912 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001913 AdaptationRequest::Mode::kAdaptUp};
1914
1915 bool adapt_up_requested =
1916 last_adaptation_request_ &&
1917 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001918
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001919 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-13 23:25:22 -07001920 if (adapt_up_requested &&
1921 adaptation_request.input_pixel_count_ <=
1922 last_adaptation_request_->input_pixel_count_) {
1923 // Don't request higher resolution if the current resolution is not
1924 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001925 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001926 }
sprangb1ca0732017-02-01 08:38:12 -08001927 }
sprangc5d62e22017-04-02 23:53:04 -07001928
sprangc5d62e22017-04-02 23:53:04 -07001929 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001930 case DegradationPreference::BALANCED: {
Åsa Persson4869bd62019-08-23 16:20:06 +02001931 // Check if quality should be increased based on bitrate.
1932 if (reason == kQuality &&
1933 !balanced_settings_.CanAdaptUp(last_frame_info_->pixel_count(),
1934 encoder_start_bitrate_bps_)) {
Åsa Persson1b247f12019-08-14 17:26:39 +02001935 return;
1936 }
asaperssonf7e294d2017-06-13 23:25:22 -07001937 // Try scale up framerate, if higher.
Åsa Persson48284b82019-07-08 10:01:12 +02001938 int fps = balanced_settings_.MaxFps(encoder_config_.codec_type,
1939 last_frame_info_->pixel_count());
asaperssonf7e294d2017-06-13 23:25:22 -07001940 if (source_proxy_->IncreaseFramerate(fps)) {
1941 GetAdaptCounter().DecrementFramerate(reason, fps);
1942 // Reset framerate in case of fewer fps steps down than up.
1943 if (adapt_counter.FramerateCount() == 0 &&
1944 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001945 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001946 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1947 }
1948 break;
1949 }
Åsa Persson30ab0152019-08-27 12:22:33 +02001950 // Check if resolution should be increased based on bitrate.
1951 if (reason == kQuality &&
1952 !balanced_settings_.CanAdaptUpResolution(
1953 last_frame_info_->pixel_count(), encoder_start_bitrate_bps_)) {
1954 return;
1955 }
asaperssonf7e294d2017-06-13 23:25:22 -07001956 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001957 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001958 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001959 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001960 // Scale up resolution.
1961 int pixel_count = adaptation_request.input_pixel_count_;
1962 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001963 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001964 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001965 }
asapersson13874762017-06-07 00:01:02 -07001966 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1967 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001968 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001969 break;
asapersson13874762017-06-07 00:01:02 -07001970 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001971 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001972 // Scale up framerate.
1973 int fps = adaptation_request.framerate_fps_;
1974 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001975 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001976 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001977 }
sprangfda496a2017-06-15 04:21:07 -07001978
1979 const int requested_framerate =
1980 source_proxy_->RequestHigherFramerateThan(fps);
1981 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001982 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001983 return;
sprangfda496a2017-06-15 04:21:07 -07001984 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001985 overuse_detector_->OnTargetFramerateUpdated(
1986 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001987 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001988 break;
asapersson13874762017-06-07 00:01:02 -07001989 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001990 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-13 23:25:22 -07001991 return;
sprangc5d62e22017-04-02 23:53:04 -07001992 }
1993
asaperssond0de2952017-04-21 01:47:31 -07001994 last_adaptation_request_.emplace(adaptation_request);
1995
asapersson09f05612017-05-15 23:40:18 -07001996 UpdateAdaptationStats(reason);
1997
Mirko Bonadei675513b2017-11-09 11:09:25 +01001998 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001999}
2000
Niels Möller213618e2018-07-24 09:29:58 +02002001// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 08:27:51 -07002002void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07002003 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07002004 case kCpu:
Niels Möller213618e2018-07-24 09:29:58 +02002005 encoder_stats_observer_->OnAdaptationChanged(
2006 VideoStreamEncoderObserver::AdaptationReason::kCpu,
2007 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-15 23:40:18 -07002008 break;
2009 case kQuality:
Niels Möller213618e2018-07-24 09:29:58 +02002010 encoder_stats_observer_->OnAdaptationChanged(
2011 VideoStreamEncoderObserver::AdaptationReason::kQuality,
2012 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07002013 break;
2014 }
perkj26091b12016-09-01 01:17:40 -07002015}
2016
Niels Möller213618e2018-07-24 09:29:58 +02002017VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 08:27:51 -07002018 AdaptReason reason) {
Niels Möller213618e2018-07-24 09:29:58 +02002019 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 08:27:51 -07002020 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07002021 switch (reason) {
2022 case kCpu:
2023 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02002024 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002025 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02002026 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002027 break;
2028 case kQuality:
2029 if (!IsFramerateScalingEnabled(degradation_preference_) ||
2030 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02002031 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002032 }
2033 if (!IsResolutionScalingEnabled(degradation_preference_) ||
2034 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02002035 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002036 }
2037 break;
sprangc5d62e22017-04-02 23:53:04 -07002038 }
asapersson09f05612017-05-15 23:40:18 -07002039 return counts;
sprangc5d62e22017-04-02 23:53:04 -07002040}
2041
mflodmancc3d4422017-08-03 08:27:51 -07002042VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002043 return adapt_counters_[degradation_preference_];
2044}
2045
mflodmancc3d4422017-08-03 08:27:51 -07002046const VideoStreamEncoder::AdaptCounter&
2047VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002048 return adapt_counters_[degradation_preference_];
2049}
2050
Erik Språng7ca375c2019-02-06 16:20:17 +01002051void VideoStreamEncoder::RunPostEncode(EncodedImage encoded_image,
Niels Möller6bb5ab92019-01-11 11:11:10 +01002052 int64_t time_sent_us,
Erik Språng7ca375c2019-02-06 16:20:17 +01002053 int temporal_index) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01002054 if (!encoder_queue_.IsCurrent()) {
Erik Språng7ca375c2019-02-06 16:20:17 +01002055 encoder_queue_.PostTask(
2056 [this, encoded_image, time_sent_us, temporal_index] {
2057 RunPostEncode(encoded_image, time_sent_us, temporal_index);
2058 });
Niels Möller6bb5ab92019-01-11 11:11:10 +01002059 return;
2060 }
2061
2062 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +01002063
2064 absl::optional<int> encode_duration_us;
2065 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
2066 encode_duration_us =
2067 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
2068 rtc::kNumMicrosecsPerMillisec *
2069 (encoded_image.timing_.encode_finish_ms -
2070 encoded_image.timing_.encode_start_ms);
2071 }
2072
2073 // Run post encode tasks, such as overuse detection and frame rate/drop
2074 // stats for internal encoders.
2075 const size_t frame_size = encoded_image.size();
Niels Möller87e2d782019-03-07 10:18:23 +01002076 const bool keyframe =
2077 encoded_image._frameType == VideoFrameType::kVideoFrameKey;
Erik Språng7ca375c2019-02-06 16:20:17 +01002078
2079 if (frame_size > 0) {
2080 frame_dropper_.Fill(frame_size, !keyframe);
Niels Möller6bb5ab92019-01-11 11:11:10 +01002081 }
2082
Erik Språngd7329ca2019-02-21 21:19:53 +01002083 if (HasInternalSource()) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01002084 // Update frame dropper after the fact for internal sources.
2085 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
2086 frame_dropper_.Leak(GetInputFramerateFps());
2087 // Signal to encoder to drop next frame.
2088 if (frame_dropper_.DropFrame()) {
2089 pending_frame_drops_.fetch_add(1);
2090 }
2091 }
2092
Erik Språng7ca375c2019-02-06 16:20:17 +01002093 overuse_detector_->FrameSent(
2094 encoded_image.Timestamp(), time_sent_us,
2095 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec,
2096 encode_duration_us);
2097 if (quality_scaler_ && encoded_image.qp_ >= 0)
Sebastian Janssonb6789402019-03-01 15:40:49 +01002098 quality_scaler_->ReportQp(encoded_image.qp_, time_sent_us);
Erik Språng7ca375c2019-02-06 16:20:17 +01002099 if (bitrate_adjuster_) {
2100 bitrate_adjuster_->OnEncodedFrame(encoded_image, temporal_index);
2101 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01002102}
2103
Erik Språngd7329ca2019-02-21 21:19:53 +01002104bool VideoStreamEncoder::HasInternalSource() const {
2105 // TODO(sprang): Checking both info from encoder and from encoder factory
2106 // until we have deprecated and removed the encoder factory info.
2107 return codec_info_.has_internal_source || encoder_info_.has_internal_source;
2108}
2109
Erik Språng6a7baa72019-02-26 18:31:00 +01002110void VideoStreamEncoder::ReleaseEncoder() {
2111 if (!encoder_ || !encoder_initialized_) {
2112 return;
2113 }
2114 encoder_->Release();
2115 encoder_initialized_ = false;
2116 TRACE_EVENT0("webrtc", "VCMGenericEncoder::Release");
2117}
2118
asapersson09f05612017-05-15 23:40:18 -07002119// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07002120VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002121 fps_counters_.resize(kScaleReasonSize);
2122 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07002123 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07002124}
2125
mflodmancc3d4422017-08-03 08:27:51 -07002126VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07002127
mflodmancc3d4422017-08-03 08:27:51 -07002128std::string VideoStreamEncoder::AdaptCounter::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02002129 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07002130 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
2131 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
Jonas Olsson84df1c72018-09-14 16:59:32 +02002132 return ss.Release();
asapersson09f05612017-05-15 23:40:18 -07002133}
2134
Niels Möller213618e2018-07-24 09:29:58 +02002135VideoStreamEncoderObserver::AdaptationSteps
2136VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
2137 VideoStreamEncoderObserver::AdaptationSteps counts;
2138 counts.num_framerate_reductions = fps_counters_[reason];
2139 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-15 23:40:18 -07002140 return counts;
2141}
2142
mflodmancc3d4422017-08-03 08:27:51 -07002143void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002144 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07002145}
2146
mflodmancc3d4422017-08-03 08:27:51 -07002147void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002148 ++(resolution_counters_[reason]);
2149}
2150
mflodmancc3d4422017-08-03 08:27:51 -07002151void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002152 if (fps_counters_[reason] == 0) {
2153 // Balanced mode: Adapt up is in a different order, switch reason.
2154 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
2155 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
2156 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
2157 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
2158 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
2159 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
2160 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
2161 MoveCount(&resolution_counters_, reason);
2162 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
2163 }
2164 --(fps_counters_[reason]);
2165 RTC_DCHECK_GE(fps_counters_[reason], 0);
2166}
2167
mflodmancc3d4422017-08-03 08:27:51 -07002168void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002169 if (resolution_counters_[reason] == 0) {
2170 // Balanced mode: Adapt up is in a different order, switch reason.
2171 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
2172 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
2173 MoveCount(&fps_counters_, reason);
2174 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
2175 }
2176 --(resolution_counters_[reason]);
2177 RTC_DCHECK_GE(resolution_counters_[reason], 0);
2178}
2179
mflodmancc3d4422017-08-03 08:27:51 -07002180void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
2181 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07002182 DecrementFramerate(reason);
2183 // Reset if at max fps (i.e. in case of fewer steps up than down).
2184 if (cur_fps == std::numeric_limits<int>::max())
Steve Antonbd631a02019-03-28 10:51:27 -07002185 absl::c_fill(fps_counters_, 0);
asapersson09f05612017-05-15 23:40:18 -07002186}
2187
mflodmancc3d4422017-08-03 08:27:51 -07002188int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07002189 return Count(fps_counters_);
2190}
2191
mflodmancc3d4422017-08-03 08:27:51 -07002192int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07002193 return Count(resolution_counters_);
2194}
2195
mflodmancc3d4422017-08-03 08:27:51 -07002196int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002197 return fps_counters_[reason];
2198}
2199
mflodmancc3d4422017-08-03 08:27:51 -07002200int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002201 return resolution_counters_[reason];
2202}
2203
mflodmancc3d4422017-08-03 08:27:51 -07002204int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002205 return FramerateCount(reason) + ResolutionCount(reason);
2206}
2207
mflodmancc3d4422017-08-03 08:27:51 -07002208int VideoStreamEncoder::AdaptCounter::Count(
2209 const std::vector<int>& counters) const {
Steve Antonbd631a02019-03-28 10:51:27 -07002210 return absl::c_accumulate(counters, 0);
asapersson09f05612017-05-15 23:40:18 -07002211}
2212
mflodmancc3d4422017-08-03 08:27:51 -07002213void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
2214 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002215 int to_reason = (from_reason + 1) % kScaleReasonSize;
2216 ++((*counters)[to_reason]);
2217 --((*counters)[from_reason]);
2218}
2219
mflodmancc3d4422017-08-03 08:27:51 -07002220std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07002221 const std::vector<int>& counters) const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02002222 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07002223 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
2224 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07002225 }
Jonas Olsson84df1c72018-09-14 16:59:32 +02002226 return ss.Release();
sprangc5d62e22017-04-02 23:53:04 -07002227}
2228
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00002229} // namespace webrtc