blob: 0af1628c0f9aeb18c10bbd28dd91d796032b755b [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()
441 : VideoEncoder::RateControlParameters(), encoder_target(DataRate::Zero()) {}
442
443VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings(
444 const VideoBitrateAllocation& bitrate,
445 double framerate_fps,
446 DataRate bandwidth_allocation,
447 DataRate encoder_target)
448 : VideoEncoder::RateControlParameters(bitrate,
449 framerate_fps,
450 bandwidth_allocation),
451 encoder_target(encoder_target) {}
452
453bool VideoStreamEncoder::EncoderRateSettings::operator==(
454 const EncoderRateSettings& rhs) const {
455 return bitrate == rhs.bitrate && framerate_fps == rhs.framerate_fps &&
456 bandwidth_allocation == rhs.bandwidth_allocation &&
457 encoder_target == rhs.encoder_target;
458}
459
460bool VideoStreamEncoder::EncoderRateSettings::operator!=(
461 const EncoderRateSettings& rhs) const {
462 return !(*this == rhs);
463}
464
Åsa Persson0122e842017-10-16 12:19:23 +0200465VideoStreamEncoder::VideoStreamEncoder(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100466 Clock* clock,
Åsa Persson0122e842017-10-16 12:19:23 +0200467 uint32_t number_of_cores,
Niels Möller213618e2018-07-24 09:29:58 +0200468 VideoStreamEncoderObserver* encoder_stats_observer,
469 const VideoStreamEncoderSettings& settings,
Sebastian Jansson74682c12019-03-01 11:50:20 +0100470 std::unique_ptr<OveruseFrameDetector> overuse_detector,
471 TaskQueueFactory* task_queue_factory)
perkj26091b12016-09-01 01:17:40 -0700472 : shutdown_event_(true /* manual_reset */, false),
473 number_of_cores_(number_of_cores),
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200474 initial_framedrop_(0),
475 initial_framedrop_on_bwe_enabled_(
476 webrtc::field_trial::IsEnabled(kInitialFramedropFieldTrial)),
Åsa Perssona945aee2018-04-24 16:53:25 +0200477 quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
perkja49cbd32016-09-16 07:53:41 -0700478 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200479 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700480 settings_(settings),
Erik Språng7ca375c2019-02-06 16:20:17 +0100481 rate_control_settings_(RateControlSettings::ParseFromFieldTrials()),
Åsa Persson139f4dc2019-08-02 09:29:58 +0200482 quality_scaler_settings_(QualityScalerSettings::ParseFromFieldTrials()),
Niels Möller73f29cb2018-01-31 16:09:31 +0100483 overuse_detector_(std::move(overuse_detector)),
Niels Möller213618e2018-07-24 09:29:58 +0200484 encoder_stats_observer_(encoder_stats_observer),
Erik Språng6a7baa72019-02-26 18:31:00 +0100485 encoder_initialized_(false),
sprangfda496a2017-06-15 04:21:07 -0700486 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700487 pending_encoder_reconfiguration_(false),
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000488 pending_encoder_creation_(false),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200489 crop_width_(0),
490 crop_height_(0),
perkj26091b12016-09-01 01:17:40 -0700491 encoder_start_bitrate_bps_(0),
Åsa Persson139f4dc2019-08-02 09:29:58 +0200492 set_start_bitrate_bps_(0),
493 set_start_bitrate_time_ms_(0),
494 has_seen_first_bwe_drop_(false),
Pera48ddb72016-09-29 11:48:50 +0200495 max_data_payload_length_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000496 encoder_paused_and_dropped_frame_(false),
Sergey Silkin5ee69672019-07-02 14:18:34 +0200497 was_encode_called_since_last_initialization_(false),
philipele8ed8302019-07-03 11:53:48 +0200498 encoder_failed_(false),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100499 clock_(clock),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700500 degradation_preference_(DegradationPreference::DISABLED),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700501 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700502 last_captured_timestamp_(0),
503 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
504 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700505 last_frame_log_ms_(clock_->TimeInMilliseconds()),
506 captured_frame_count_(0),
507 dropped_frame_count_(0),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200508 pending_frame_post_time_us_(0),
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100509 accumulated_update_rect_{0, 0, 0, 0},
sprang1a646ee2016-12-01 06:34:11 -0800510 bitrate_observer_(nullptr),
Elad Alon8f01c4e2019-06-28 15:19:43 +0200511 fec_controller_override_(nullptr),
Niels Möller6bb5ab92019-01-11 11:11:10 +0100512 force_disable_frame_dropper_(false),
513 input_framerate_(kFrameRateAvergingWindowSizeMs, 1000),
514 pending_frame_drops_(0),
Niels Möller8f7ce222019-03-21 15:43:58 +0100515 next_frame_types_(1, VideoFrameType::kVideoFrameDelta),
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200516 frame_encode_metadata_writer_(this),
Erik Språng6a7baa72019-02-26 18:31:00 +0100517 experiment_groups_(GetExperimentGroups()),
philipelda5aa4d2019-04-26 13:37:37 +0200518 next_frame_id_(0),
Sebastian Jansson74682c12019-03-01 11:50:20 +0100519 encoder_queue_(task_queue_factory->CreateTaskQueue(
520 "EncoderQueue",
521 TaskQueueFactory::Priority::NORMAL)) {
Niels Möller213618e2018-07-24 09:29:58 +0200522 RTC_DCHECK(encoder_stats_observer);
Niels Möller73f29cb2018-01-31 16:09:31 +0100523 RTC_DCHECK(overuse_detector_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100524 RTC_DCHECK_GE(number_of_cores, 1);
philipelda5aa4d2019-04-26 13:37:37 +0200525
526 for (auto& state : encoder_buffer_state_)
527 state.fill(std::numeric_limits<int64_t>::max());
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000528}
529
mflodmancc3d4422017-08-03 08:27:51 -0700530VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700531 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700532 RTC_DCHECK(shutdown_event_.Wait(0))
533 << "Must call ::Stop() before destruction.";
534}
535
mflodmancc3d4422017-08-03 08:27:51 -0700536void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700537 RTC_DCHECK_RUN_ON(&thread_checker_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700538 source_proxy_->SetSource(nullptr, DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700539 encoder_queue_.PostTask([this] {
540 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700541 overuse_detector_->StopCheckForOveruse();
Erik Språngb7cb7b52019-02-26 15:52:33 +0100542 rate_allocator_ = nullptr;
sprang1a646ee2016-12-01 06:34:11 -0800543 bitrate_observer_ = nullptr;
Erik Språng6a7baa72019-02-26 18:31:00 +0100544 ReleaseEncoder();
kthelgason876222f2016-11-29 01:44:11 -0800545 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700546 shutdown_event_.Set();
547 });
548
549 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700550}
551
Niels Möller0327c2d2018-05-21 14:09:31 +0200552void VideoStreamEncoder::SetBitrateAllocationObserver(
sprang1a646ee2016-12-01 06:34:11 -0800553 VideoBitrateAllocationObserver* bitrate_observer) {
554 RTC_DCHECK_RUN_ON(&thread_checker_);
555 encoder_queue_.PostTask([this, bitrate_observer] {
556 RTC_DCHECK_RUN_ON(&encoder_queue_);
557 RTC_DCHECK(!bitrate_observer_);
558 bitrate_observer_ = bitrate_observer;
559 });
560}
561
Elad Alon8f01c4e2019-06-28 15:19:43 +0200562void VideoStreamEncoder::SetFecControllerOverride(
563 FecControllerOverride* fec_controller_override) {
564 encoder_queue_.PostTask([this, fec_controller_override] {
565 RTC_DCHECK_RUN_ON(&encoder_queue_);
566 RTC_DCHECK(!fec_controller_override_);
567 fec_controller_override_ = fec_controller_override;
568 if (encoder_) {
569 encoder_->SetFecControllerOverride(fec_controller_override_);
570 }
571 });
572}
573
mflodmancc3d4422017-08-03 08:27:51 -0700574void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700575 rtc::VideoSourceInterface<VideoFrame>* source,
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700576 const DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700577 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700578 source_proxy_->SetSource(source, degradation_preference);
579 encoder_queue_.PostTask([this, degradation_preference] {
580 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700581 if (degradation_preference_ != degradation_preference) {
582 // Reset adaptation state, so that we're not tricked into thinking there's
583 // an already pending request of the same type.
584 last_adaptation_request_.reset();
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700585 if (degradation_preference == DegradationPreference::BALANCED ||
586 degradation_preference_ == DegradationPreference::BALANCED) {
asaperssonf7e294d2017-06-13 23:25:22 -0700587 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
588 // AdaptCounter for all modes.
589 source_proxy_->ResetPixelFpsCount();
590 adapt_counters_.clear();
591 }
sprangc5d62e22017-04-02 23:53:04 -0700592 }
sprangb1ca0732017-02-01 08:38:12 -0800593 degradation_preference_ = degradation_preference;
Niels Möller4db138e2018-04-19 09:04:13 +0200594
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000595 if (encoder_)
Erik Språng7ca375c2019-02-06 16:20:17 +0100596 ConfigureQualityScaler(encoder_->GetEncoderInfo());
Niels Möller4db138e2018-04-19 09:04:13 +0200597
Niels Möller7dc26b72017-12-06 10:27:48 +0100598 if (!IsFramerateScalingEnabled(degradation_preference) &&
599 max_framerate_ != -1) {
600 // If frame rate scaling is no longer allowed, remove any potential
601 // allowance for longer frame intervals.
602 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
603 }
perkj803d97f2016-11-01 11:45:46 -0700604 });
perkja49cbd32016-09-16 07:53:41 -0700605}
606
mflodmancc3d4422017-08-03 08:27:51 -0700607void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700608 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700609 encoder_queue_.PostTask([this, sink] {
610 RTC_DCHECK_RUN_ON(&encoder_queue_);
611 sink_ = sink;
612 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000613}
614
mflodmancc3d4422017-08-03 08:27:51 -0700615void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700616 encoder_queue_.PostTask([this, start_bitrate_bps] {
617 RTC_DCHECK_RUN_ON(&encoder_queue_);
618 encoder_start_bitrate_bps_ = start_bitrate_bps;
Åsa Persson139f4dc2019-08-02 09:29:58 +0200619 set_start_bitrate_bps_ = start_bitrate_bps;
620 set_start_bitrate_time_ms_ = clock_->TimeInMilliseconds();
perkj26091b12016-09-01 01:17:40 -0700621 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000622}
Peter Boström00b9d212016-05-19 16:59:03 +0200623
mflodmancc3d4422017-08-03 08:27:51 -0700624void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200625 size_t max_data_payload_length) {
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100626 // TODO(srte): This struct should be replaced by a lambda with move capture
627 // when C++14 lambda is allowed.
628 struct ConfigureEncoderTask {
629 void operator()() {
Yves Gerey665174f2018-06-19 15:03:05 +0200630 encoder->ConfigureEncoderOnTaskQueue(std::move(config),
631 max_data_payload_length);
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100632 }
633 VideoStreamEncoder* encoder;
634 VideoEncoderConfig config;
635 size_t max_data_payload_length;
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100636 };
Yves Gerey665174f2018-06-19 15:03:05 +0200637 encoder_queue_.PostTask(
638 ConfigureEncoderTask{this, std::move(config), max_data_payload_length});
perkj26091b12016-09-01 01:17:40 -0700639}
640
mflodmancc3d4422017-08-03 08:27:51 -0700641void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
642 VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200643 size_t max_data_payload_length) {
perkj26091b12016-09-01 01:17:40 -0700644 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700645 RTC_DCHECK(sink_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100646 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200647
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000648 pending_encoder_creation_ =
Erik Språngd7329ca2019-02-21 21:19:53 +0100649 (!encoder_ || encoder_config_.video_format != config.video_format ||
650 max_data_payload_length_ != max_data_payload_length);
Pera48ddb72016-09-29 11:48:50 +0200651 encoder_config_ = std::move(config);
Erik Språngd7329ca2019-02-21 21:19:53 +0100652 max_data_payload_length_ = max_data_payload_length;
perkjfa10b552016-10-02 23:45:26 -0700653 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200654
perkjfa10b552016-10-02 23:45:26 -0700655 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100656 // if the frame resolution is known. Otherwise, the reconfiguration is
657 // deferred until the next frame to minimize the number of reconfigurations.
658 // The codec configuration depends on incoming video frame size.
659 if (last_frame_info_) {
660 ReconfigureEncoder();
Erik Språngd7329ca2019-02-21 21:19:53 +0100661 } else {
662 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
663 encoder_config_.video_format);
664 if (HasInternalSource()) {
665 last_frame_info_ = VideoFrameInfo(176, 144, false);
666 ReconfigureEncoder();
667 }
perkjfa10b552016-10-02 23:45:26 -0700668 }
669}
perkj26091b12016-09-01 01:17:40 -0700670
Sergey Silkin6456e352019-07-08 17:56:40 +0200671static absl::optional<VideoEncoder::ResolutionBitrateLimits>
672GetEncoderBitrateLimits(const VideoEncoder::EncoderInfo& encoder_info,
673 int frame_size_pixels) {
674 std::vector<VideoEncoder::ResolutionBitrateLimits> bitrate_limits =
675 encoder_info.resolution_bitrate_limits;
676
677 // Sort the list of bitrate limits by resolution.
678 sort(bitrate_limits.begin(), bitrate_limits.end(),
679 [](const VideoEncoder::ResolutionBitrateLimits& lhs,
680 const VideoEncoder::ResolutionBitrateLimits& rhs) {
681 return lhs.frame_size_pixels < rhs.frame_size_pixels;
682 });
683
684 for (size_t i = 0; i < bitrate_limits.size(); ++i) {
Sergey Silkin6b2cec12019-08-09 16:04:05 +0200685 RTC_DCHECK_GT(bitrate_limits[i].min_bitrate_bps, 0);
686 RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
687 bitrate_limits[i].min_bitrate_bps);
688 RTC_DCHECK_GT(bitrate_limits[i].max_bitrate_bps,
689 bitrate_limits[i].min_start_bitrate_bps);
Sergey Silkin6456e352019-07-08 17:56:40 +0200690 if (i > 0) {
691 // The bitrate limits aren't expected to decrease with resolution.
692 RTC_DCHECK_GE(bitrate_limits[i].min_bitrate_bps,
693 bitrate_limits[i - 1].min_bitrate_bps);
694 RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
695 bitrate_limits[i - 1].min_start_bitrate_bps);
696 RTC_DCHECK_GE(bitrate_limits[i].max_bitrate_bps,
697 bitrate_limits[i - 1].max_bitrate_bps);
698 }
699
700 if (bitrate_limits[i].frame_size_pixels >= frame_size_pixels) {
701 return absl::optional<VideoEncoder::ResolutionBitrateLimits>(
702 bitrate_limits[i]);
703 }
704 }
705
706 return absl::nullopt;
707}
708
Seth Hampsoncc7125f2018-02-02 08:46:16 -0800709// TODO(bugs.webrtc.org/8807): Currently this always does a hard
710// reconfiguration, but this isn't always necessary. Add in logic to only update
711// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
712// "soft" reconfiguration.
mflodmancc3d4422017-08-03 08:27:51 -0700713void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700714 RTC_DCHECK(pending_encoder_reconfiguration_);
715 std::vector<VideoStream> streams =
716 encoder_config_.video_stream_factory->CreateEncoderStreams(
717 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700718
ilnik6b826ef2017-06-16 06:53:48 -0700719 // TODO(ilnik): If configured resolution is significantly less than provided,
720 // e.g. because there are not enough SSRCs for all simulcast streams,
721 // signal new resolutions via SinkWants to video source.
722
723 // Stream dimensions may be not equal to given because of a simulcast
724 // restrictions.
Steve Antonbd631a02019-03-28 10:51:27 -0700725 auto highest_stream = absl::c_max_element(
726 streams, [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) {
Florent Castelli450b5482018-11-29 17:32:47 +0100727 return std::tie(a.width, a.height) < std::tie(b.width, b.height);
728 });
729 int highest_stream_width = static_cast<int>(highest_stream->width);
730 int highest_stream_height = static_cast<int>(highest_stream->height);
ilnik6b826ef2017-06-16 06:53:48 -0700731 // Dimension may be reduced to be, e.g. divisible by 4.
732 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
733 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
734 crop_width_ = last_frame_info_->width - highest_stream_width;
735 crop_height_ = last_frame_info_->height - highest_stream_height;
736
Sergey Silkin6456e352019-07-08 17:56:40 +0200737 bool encoder_reset_required = false;
738 if (pending_encoder_creation_) {
739 // Destroy existing encoder instance before creating a new one. Otherwise
740 // attempt to create another instance will fail if encoder factory
741 // supports only single instance of encoder of given type.
742 encoder_.reset();
743
744 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
745 encoder_config_.video_format);
746 // TODO(nisse): What to do if creating the encoder fails? Crash,
747 // or just discard incoming frames?
748 RTC_CHECK(encoder_);
749
750 encoder_->SetFecControllerOverride(fec_controller_override_);
751
752 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
753 encoder_config_.video_format);
754
755 encoder_reset_required = true;
756 }
757
758 encoder_bitrate_limits_ = GetEncoderBitrateLimits(
759 encoder_->GetEncoderInfo(),
760 last_frame_info_->width * last_frame_info_->height);
761
Sergey Silkin6b2cec12019-08-09 16:04:05 +0200762 if (streams.size() == 1 && encoder_bitrate_limits_) {
763 // Use bitrate limits recommended by encoder only if app didn't set any of
764 // them.
765 if (encoder_config_.max_bitrate_bps <= 0 &&
766 (encoder_config_.simulcast_layers.empty() ||
767 encoder_config_.simulcast_layers[0].min_bitrate_bps <= 0)) {
768 streams.back().min_bitrate_bps = encoder_bitrate_limits_->min_bitrate_bps;
769 streams.back().max_bitrate_bps = encoder_bitrate_limits_->max_bitrate_bps;
770 streams.back().target_bitrate_bps =
771 std::min(streams.back().target_bitrate_bps,
772 encoder_bitrate_limits_->max_bitrate_bps);
773 }
Sergey Silkin6456e352019-07-08 17:56:40 +0200774 }
775
Erik Språng08127a92016-11-16 16:41:30 +0100776 VideoCodec codec;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800777 if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100778 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100779 }
perkjfa10b552016-10-02 23:45:26 -0700780
“Michael277a6562018-06-01 14:09:19 -0500781 // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9.
782 if (encoder_config_.codec_type == kVideoCodecVP9) {
“Michael277a6562018-06-01 14:09:19 -0500783 // Lower max bitrate to the level codec actually can produce.
Erik Språngcf9cbf52019-09-04 14:30:57 +0200784 streams[0].max_bitrate_bps =
785 std::min(streams[0].max_bitrate_bps,
786 SvcRateAllocator::GetMaxBitrate(codec).bps<int>());
“Michael277a6562018-06-01 14:09:19 -0500787 streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000;
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100788 // target_bitrate_bps specifies the maximum padding bitrate.
“Michael277a6562018-06-01 14:09:19 -0500789 streams[0].target_bitrate_bps =
Erik Språngcf9cbf52019-09-04 14:30:57 +0200790 SvcRateAllocator::GetPaddingBitrate(codec).bps<int>();
“Michael277a6562018-06-01 14:09:19 -0500791 }
792
perkjfa10b552016-10-02 23:45:26 -0700793 codec.startBitrate =
794 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
795 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
796 codec.expect_encode_from_texture = last_frame_info_->is_texture;
Erik Språngd7329ca2019-02-21 21:19:53 +0100797 // Make sure the start bit rate is sane...
798 RTC_DCHECK_LE(codec.startBitrate, 1000000);
sprangfda496a2017-06-15 04:21:07 -0700799 max_framerate_ = codec.maxFramerate;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200800
801 // Inform source about max configured framerate.
802 int max_framerate = 0;
803 for (const auto& stream : streams) {
804 max_framerate = std::max(stream.max_framerate, max_framerate);
805 }
806 source_proxy_->SetMaxFramerate(max_framerate);
Stefan Holmere5904162015-03-26 11:11:06 +0100807
Erik Språngb7cb7b52019-02-26 15:52:33 +0100808 if (codec.maxBitrate == 0) {
809 // max is one bit per pixel
810 codec.maxBitrate =
811 (static_cast<int>(codec.height) * static_cast<int>(codec.width) *
812 static_cast<int>(codec.maxFramerate)) /
813 1000;
814 if (codec.startBitrate > codec.maxBitrate) {
815 // But if the user tries to set a higher start bit rate we will
816 // increase the max accordingly.
817 codec.maxBitrate = codec.startBitrate;
818 }
819 }
820
821 if (codec.startBitrate > codec.maxBitrate) {
822 codec.startBitrate = codec.maxBitrate;
823 }
824
Sergey Silkin65d9c4d2019-06-12 11:02:30 +0200825 rate_allocator_ =
826 settings_.bitrate_allocator_factory->CreateVideoBitrateAllocator(codec);
827
Erik Språngb7cb7b52019-02-26 15:52:33 +0100828 // Reset (release existing encoder) if one exists and anything except
Elad Alonfb087812019-05-02 23:25:34 +0200829 // start bitrate or max framerate has changed.
Sergey Silkin6456e352019-07-08 17:56:40 +0200830 if (!encoder_reset_required) {
831 encoder_reset_required = RequiresEncoderReset(
832 codec, send_codec_, was_encode_called_since_last_initialization_);
833 }
Erik Språngb7cb7b52019-02-26 15:52:33 +0100834 send_codec_ = codec;
835
Niels Möller4db138e2018-04-19 09:04:13 +0200836 // Keep the same encoder, as long as the video_format is unchanged.
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100837 // Encoder creation block is split in two since EncoderInfo needed to start
838 // CPU adaptation with the correct settings should be polled after
839 // encoder_->InitEncode().
Erik Språngb7cb7b52019-02-26 15:52:33 +0100840 bool success = true;
Sergey Silkin6456e352019-07-08 17:56:40 +0200841 if (encoder_reset_required) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100842 ReleaseEncoder();
Elad Alon370f93a2019-06-11 14:57:57 +0200843 const size_t max_data_payload_length = max_data_payload_length_ > 0
844 ? max_data_payload_length_
845 : kDefaultPayloadSize;
846 if (encoder_->InitEncode(
847 &send_codec_,
848 VideoEncoder::Settings(settings_.capabilities, number_of_cores_,
849 max_data_payload_length)) != 0) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100850 RTC_LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
851 "codec type: "
852 << CodecTypeToPayloadString(send_codec_.codecType)
853 << " (" << send_codec_.codecType << ")";
854 ReleaseEncoder();
855 success = false;
856 } else {
857 encoder_initialized_ = true;
858 encoder_->RegisterEncodeCompleteCallback(this);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200859 frame_encode_metadata_writer_.OnEncoderInit(send_codec_,
860 HasInternalSource());
Erik Språng6a7baa72019-02-26 18:31:00 +0100861 }
862
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200863 frame_encode_metadata_writer_.Reset();
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100864 last_encode_info_ms_ = absl::nullopt;
Sergey Silkin5ee69672019-07-02 14:18:34 +0200865 was_encode_called_since_last_initialization_ = false;
Erik Språngb7cb7b52019-02-26 15:52:33 +0100866 }
Erik Språngd7329ca2019-02-21 21:19:53 +0100867
868 if (success) {
Erik Språngd7329ca2019-02-21 21:19:53 +0100869 next_frame_types_.clear();
870 next_frame_types_.resize(
871 std::max(static_cast<int>(codec.numberOfSimulcastStreams), 1),
Niels Möller8f7ce222019-03-21 15:43:58 +0100872 VideoFrameType::kVideoFrameKey);
Erik Språngd7329ca2019-02-21 21:19:53 +0100873 RTC_LOG(LS_VERBOSE) << " max bitrate " << codec.maxBitrate
874 << " start bitrate " << codec.startBitrate
875 << " max frame rate " << codec.maxFramerate
876 << " max payload size " << max_data_payload_length_;
877 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100878 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
Erik Språngb7cb7b52019-02-26 15:52:33 +0100879 rate_allocator_ = nullptr;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000880 }
Peter Boström905f8e72016-03-02 16:59:56 +0100881
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100882 if (pending_encoder_creation_) {
883 overuse_detector_->StopCheckForOveruse();
884 overuse_detector_->StartCheckForOveruse(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100885 &encoder_queue_,
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100886 GetCpuOveruseOptions(
887 settings_, encoder_->GetEncoderInfo().is_hardware_accelerated),
888 this);
889 pending_encoder_creation_ = false;
890 }
891
Niels Möller6bb5ab92019-01-11 11:11:10 +0100892 int num_layers;
893 if (codec.codecType == kVideoCodecVP8) {
894 num_layers = codec.VP8()->numberOfTemporalLayers;
895 } else if (codec.codecType == kVideoCodecVP9) {
896 num_layers = codec.VP9()->numberOfTemporalLayers;
Johnny Lee1a1c52b2019-02-08 14:25:40 -0500897 } else if (codec.codecType == kVideoCodecH264) {
898 num_layers = codec.H264()->numberOfTemporalLayers;
Niels Möller6bb5ab92019-01-11 11:11:10 +0100899 } else if (codec.codecType == kVideoCodecGeneric &&
900 codec.numberOfSimulcastStreams > 0) {
901 // This is mainly for unit testing, disabling frame dropping.
902 // TODO(sprang): Add a better way to disable frame dropping.
903 num_layers = codec.simulcastStream[0].numberOfTemporalLayers;
904 } else {
905 num_layers = 1;
906 }
907
908 frame_dropper_.Reset();
909 frame_dropper_.SetRates(codec.startBitrate, max_framerate_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100910 // Force-disable frame dropper if either:
911 // * We have screensharing with layers.
912 // * "WebRTC-FrameDropper" field trial is "Disabled".
913 force_disable_frame_dropper_ =
914 field_trial::IsDisabled(kFrameDropperFieldTrial) ||
915 (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing);
916
Erik Språng7ca375c2019-02-06 16:20:17 +0100917 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
918 if (rate_control_settings_.UseEncoderBitrateAdjuster()) {
919 bitrate_adjuster_ = absl::make_unique<EncoderBitrateAdjuster>(codec);
920 bitrate_adjuster_->OnEncoderInfo(info);
921 }
922
Erik Språng4c6ca302019-04-08 15:14:01 +0200923 if (rate_allocator_ && last_encoder_rate_settings_) {
Niels Möller6bb5ab92019-01-11 11:11:10 +0100924 // We have a new rate allocator instance and already configured target
Erik Språng4c6ca302019-04-08 15:14:01 +0200925 // bitrate. Update the rate allocation and notify observers.
926 last_encoder_rate_settings_->framerate_fps = GetInputFramerateFps();
927 SetEncoderRates(
928 UpdateBitrateAllocationAndNotifyObserver(*last_encoder_rate_settings_));
Niels Möller6bb5ab92019-01-11 11:11:10 +0100929 }
ilnik35b7de42017-03-15 04:24:21 -0700930
Niels Möller213618e2018-07-24 09:29:58 +0200931 encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
Per512ecb32016-09-23 15:52:06 +0200932
perkjfa10b552016-10-02 23:45:26 -0700933 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100934
Pera48ddb72016-09-29 11:48:50 +0200935 sink_->OnEncoderConfigurationChanged(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100936 std::move(streams), encoder_config_.content_type,
937 encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800938
Niels Möller7dc26b72017-12-06 10:27:48 +0100939 // Get the current target framerate, ie the maximum framerate as specified by
940 // the current codec configuration, or any limit imposed by cpu adaption in
941 // maintain-resolution or balanced mode. This is used to make sure overuse
942 // detection doesn't needlessly trigger in low and/or variable framerate
943 // scenarios.
944 int target_framerate = std::min(
945 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
946 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +0200947
Erik Språng7ca375c2019-02-06 16:20:17 +0100948 ConfigureQualityScaler(info);
kthelgason2bc68642017-02-07 07:02:22 -0800949}
950
Erik Språng7ca375c2019-02-06 16:20:17 +0100951void VideoStreamEncoder::ConfigureQualityScaler(
952 const VideoEncoder::EncoderInfo& encoder_info) {
kthelgason2bc68642017-02-07 07:02:22 -0800953 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +0100954 const auto scaling_settings = encoder_info.scaling_settings;
asapersson36e9eb42017-03-31 05:29:12 -0700955 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700956 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +0100957 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -0700958
asapersson36e9eb42017-03-31 05:29:12 -0700959 if (quality_scaling_allowed) {
Benjamin Wright1f4173e2019-03-13 17:59:32 -0700960 if (quality_scaler_ == nullptr) {
asapersson09f05612017-05-15 23:40:18 -0700961 // Quality scaler has not already been configured.
Niels Möller225c7872018-02-22 15:03:53 +0100962
Åsa Perssona945aee2018-04-24 16:53:25 +0200963 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200964 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 16:53:25 +0200965 if (quality_scaling_experiment_enabled_) {
966 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
967 encoder_config_.codec_type);
968 }
Karl Wiberg918f50c2018-07-05 11:40:33 +0200969 // Since the interface is non-public, absl::make_unique can't do this
970 // upcast.
Niels Möller225c7872018-02-22 15:03:53 +0100971 AdaptationObserverInterface* observer = this;
Karl Wiberg918f50c2018-07-05 11:40:33 +0200972 quality_scaler_ = absl::make_unique<QualityScaler>(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100973 &encoder_queue_, observer,
974 experimental_thresholds ? *experimental_thresholds
975 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200976 has_seen_first_significant_bwe_change_ = false;
977 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 01:44:11 -0800978 }
979 } else {
980 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200981 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800982 }
asapersson09f05612017-05-15 23:40:18 -0700983
Åsa Persson12314192019-06-20 15:45:07 +0200984 if (degradation_preference_ == DegradationPreference::BALANCED &&
985 quality_scaler_ && last_frame_info_) {
986 absl::optional<VideoEncoder::QpThresholds> thresholds =
987 balanced_settings_.GetQpThresholds(encoder_config_.codec_type,
988 last_frame_info_->pixel_count());
989 if (thresholds) {
990 quality_scaler_->SetQpThresholds(*thresholds);
991 }
992 }
993
Niels Möller213618e2018-07-24 09:29:58 +0200994 encoder_stats_observer_->OnAdaptationChanged(
995 VideoStreamEncoderObserver::AdaptationReason::kNone,
996 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000997}
998
mflodmancc3d4422017-08-03 08:27:51 -0700999void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -07001000 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -07001001 VideoFrame incoming_frame = video_frame;
1002
1003 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -07001004 int64_t current_time_us = clock_->TimeInMicroseconds();
1005 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
1006 // In some cases, e.g., when the frame from decoder is fed to encoder,
1007 // the timestamp may be set to the future. As the encoding pipeline assumes
1008 // capture time to be less than present time, we should reset the capture
1009 // timestamps here. Otherwise there may be issues with RTP send stream.
1010 if (incoming_frame.timestamp_us() > current_time_us)
1011 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -07001012
1013 // Capture time may come from clock with an offset and drift from clock_.
1014 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -08001015 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -07001016 capture_ntp_time_ms = video_frame.ntp_time_ms();
1017 } else if (video_frame.render_time_ms() != 0) {
1018 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
1019 } else {
nisse1c0dea82017-01-30 02:43:18 -08001020 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -07001021 }
1022 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
1023
1024 // Convert NTP time, in ms, to RTP timestamp.
1025 const int kMsToRtpTimestamp = 90;
1026 incoming_frame.set_timestamp(
1027 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
1028
1029 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
1030 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001031 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
1032 << incoming_frame.ntp_time_ms()
1033 << " <= " << last_captured_timestamp_
1034 << ") for incoming frame. Dropping.";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001035 encoder_queue_.PostTask([this, incoming_frame]() {
1036 RTC_DCHECK_RUN_ON(&encoder_queue_);
1037 accumulated_update_rect_.Union(incoming_frame.update_rect());
1038 });
perkj26091b12016-09-01 01:17:40 -07001039 return;
1040 }
1041
asapersson6ffb67d2016-09-12 00:10:45 -07001042 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -08001043 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
1044 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -07001045 log_stats = true;
1046 }
1047
perkj26091b12016-09-01 01:17:40 -07001048 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001049
1050 int64_t post_time_us = rtc::TimeMicros();
1051 ++posted_frames_waiting_for_encode_;
1052
1053 encoder_queue_.PostTask(
1054 [this, incoming_frame, post_time_us, log_stats]() {
1055 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 09:29:58 +02001056 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
1057 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001058 ++captured_frame_count_;
1059 const int posted_frames_waiting_for_encode =
1060 posted_frames_waiting_for_encode_.fetch_sub(1);
1061 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
1062 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +02001063 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001064 } else {
1065 // There is a newer frame in flight. Do not encode this frame.
1066 RTC_LOG(LS_VERBOSE)
1067 << "Incoming frame dropped due to that the encoder is blocked.";
1068 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 09:29:58 +02001069 encoder_stats_observer_->OnFrameDropped(
1070 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001071 accumulated_update_rect_.Union(incoming_frame.update_rect());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001072 }
1073 if (log_stats) {
1074 RTC_LOG(LS_INFO) << "Number of frames: captured "
1075 << captured_frame_count_
1076 << ", dropped (due to encoder blocked) "
1077 << dropped_frame_count_ << ", interval_ms "
1078 << kFrameLogIntervalMs;
1079 captured_frame_count_ = 0;
1080 dropped_frame_count_ = 0;
1081 }
1082 });
perkj26091b12016-09-01 01:17:40 -07001083}
1084
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001085void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 09:29:58 +02001086 encoder_stats_observer_->OnFrameDropped(
1087 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001088}
1089
mflodmancc3d4422017-08-03 08:27:51 -07001090bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -07001091 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +00001092 // Pause video if paused by caller or as long as the network is down or the
1093 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -07001094 // If the pacer queue has grown too large or the network is down,
Erik Språng4c6ca302019-04-08 15:14:01 +02001095 // |last_encoder_rate_settings_->encoder_target| will be 0.
1096 return !last_encoder_rate_settings_ ||
1097 last_encoder_rate_settings_->encoder_target == DataRate::Zero();
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +00001098}
1099
mflodmancc3d4422017-08-03 08:27:51 -07001100void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -07001101 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001102 // Start trace event only on the first frame after encoder is paused.
1103 if (!encoder_paused_and_dropped_frame_) {
1104 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
1105 }
1106 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001107}
1108
mflodmancc3d4422017-08-03 08:27:51 -07001109void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -07001110 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001111 // End trace event on first frame after encoder resumes, if frame was dropped.
1112 if (encoder_paused_and_dropped_frame_) {
1113 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
1114 }
1115 encoder_paused_and_dropped_frame_ = false;
1116}
1117
Erik Språng4c6ca302019-04-08 15:14:01 +02001118VideoStreamEncoder::EncoderRateSettings
1119VideoStreamEncoder::UpdateBitrateAllocationAndNotifyObserver(
1120 const EncoderRateSettings& rate_settings) {
1121 VideoBitrateAllocation new_allocation;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001122 // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
1123 // might cap the bitrate to the min bitrate configured.
Erik Språng4c6ca302019-04-08 15:14:01 +02001124 if (rate_allocator_ && rate_settings.encoder_target > DataRate::Zero()) {
Florent Castelli8bbdb5b2019-08-02 15:16:28 +02001125 new_allocation = rate_allocator_->Allocate(VideoBitrateAllocationParameters(
Erik Språng4c6ca302019-04-08 15:14:01 +02001126 rate_settings.encoder_target.bps(),
Florent Castelli8bbdb5b2019-08-02 15:16:28 +02001127 static_cast<uint32_t>(rate_settings.framerate_fps + 0.5)));
Niels Möller6bb5ab92019-01-11 11:11:10 +01001128 }
1129
Erik Språng4c6ca302019-04-08 15:14:01 +02001130 if (bitrate_observer_ && new_allocation.get_sum_bps() > 0) {
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001131 if (encoder_ && encoder_initialized_) {
1132 // Avoid too old encoder_info_.
1133 const int64_t kMaxDiffMs = 100;
1134 const bool updated_recently =
1135 (last_encode_info_ms_ && ((clock_->TimeInMilliseconds() -
1136 *last_encode_info_ms_) < kMaxDiffMs));
1137 // Update allocation according to info from encoder.
1138 bitrate_observer_->OnBitrateAllocationUpdated(
1139 UpdateAllocationFromEncoderInfo(
Erik Språng4c6ca302019-04-08 15:14:01 +02001140 new_allocation,
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001141 updated_recently ? encoder_info_ : encoder_->GetEncoderInfo()));
1142 } else {
Erik Språng4c6ca302019-04-08 15:14:01 +02001143 bitrate_observer_->OnBitrateAllocationUpdated(new_allocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001144 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001145 }
1146
Erik Språng3d11e2f2019-04-15 14:48:30 +02001147 EncoderRateSettings new_rate_settings = rate_settings;
1148 new_rate_settings.bitrate = new_allocation;
Erik Språng5056af02019-09-02 15:53:11 +02001149 // VideoBitrateAllocator subclasses may allocate a bitrate higher than the
1150 // target in order to sustain the min bitrate of the video codec. In this
1151 // case, make sure the bandwidth allocation is at least equal the allocation
1152 // as that is part of the document contract for that field.
1153 new_rate_settings.bandwidth_allocation =
1154 std::max(new_rate_settings.bandwidth_allocation,
1155 DataRate::bps(new_rate_settings.bitrate.get_sum_bps()));
Erik Språng3d11e2f2019-04-15 14:48:30 +02001156
Erik Språng7ca375c2019-02-06 16:20:17 +01001157 if (bitrate_adjuster_) {
Erik Språng0e1a1f92019-02-18 18:45:13 +01001158 VideoBitrateAllocation adjusted_allocation =
Erik Språng3d11e2f2019-04-15 14:48:30 +02001159 bitrate_adjuster_->AdjustRateAllocation(new_rate_settings);
Erik Språng4c6ca302019-04-08 15:14:01 +02001160 RTC_LOG(LS_VERBOSE) << "Adjusting allocation, fps = "
1161 << rate_settings.framerate_fps << ", from "
1162 << new_allocation.ToString() << ", to "
Erik Språng0e1a1f92019-02-18 18:45:13 +01001163 << adjusted_allocation.ToString();
Erik Språng3d11e2f2019-04-15 14:48:30 +02001164 new_rate_settings.bitrate = adjusted_allocation;
Erik Språng7ca375c2019-02-06 16:20:17 +01001165 }
Erik Språng4c6ca302019-04-08 15:14:01 +02001166
Erik Språng3d11e2f2019-04-15 14:48:30 +02001167 return new_rate_settings;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001168}
1169
1170uint32_t VideoStreamEncoder::GetInputFramerateFps() {
1171 const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
Erik Språngd7329ca2019-02-21 21:19:53 +01001172 absl::optional<uint32_t> input_fps =
1173 input_framerate_.Rate(clock_->TimeInMilliseconds());
1174 if (!input_fps || *input_fps == 0) {
1175 return default_fps;
1176 }
1177 return *input_fps;
1178}
1179
1180void VideoStreamEncoder::SetEncoderRates(
Erik Språng4c6ca302019-04-08 15:14:01 +02001181 const EncoderRateSettings& rate_settings) {
1182 RTC_DCHECK_GT(rate_settings.framerate_fps, 0.0);
1183 const bool settings_changes = !last_encoder_rate_settings_ ||
1184 rate_settings != *last_encoder_rate_settings_;
1185 if (settings_changes) {
1186 last_encoder_rate_settings_ = rate_settings;
1187 }
1188
Erik Språng6a7baa72019-02-26 18:31:00 +01001189 if (!encoder_) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001190 return;
1191 }
1192
1193 // |bitrate_allocation| is 0 it means that the network is down or the send
1194 // pacer is full. We currently only report this if the encoder has an internal
1195 // source. If the encoder does not have an internal source, higher levels
1196 // are expected to not call AddVideoFrame. We do this since its unclear
1197 // how current encoder implementations behave when given a zero target
1198 // bitrate.
1199 // TODO(perkj): Make sure all known encoder implementations handle zero
1200 // target bitrate and remove this check.
Erik Språng4c6ca302019-04-08 15:14:01 +02001201 if (!HasInternalSource() && rate_settings.bitrate.get_sum_bps() == 0) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001202 return;
1203 }
1204
Erik Språng4c6ca302019-04-08 15:14:01 +02001205 if (settings_changes) {
1206 encoder_->SetRates(rate_settings);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001207 frame_encode_metadata_writer_.OnSetRates(
Erik Språng4c6ca302019-04-08 15:14:01 +02001208 rate_settings.bitrate,
1209 static_cast<uint32_t>(rate_settings.framerate_fps + 0.5));
Erik Språng6a7baa72019-02-26 18:31:00 +01001210 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001211}
1212
Sebastian Janssona3177052018-04-10 13:05:49 +02001213void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
1214 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -07001215 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -08001216
Per21d45d22016-10-30 21:37:57 +01001217 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -07001218 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -07001219 video_frame.is_texture() != last_frame_info_->is_texture) {
1220 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +01001221 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
1222 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +01001223 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
1224 << last_frame_info_->width << "x"
1225 << last_frame_info_->height
1226 << ", texture=" << last_frame_info_->is_texture << ".";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001227 // Force full frame update, since resolution has changed.
1228 accumulated_update_rect_ =
1229 VideoFrame::UpdateRect{0, 0, video_frame.width(), video_frame.height()};
perkjfa10b552016-10-02 23:45:26 -07001230 }
1231
Niels Möller4db138e2018-04-19 09:04:13 +02001232 // We have to create then encoder before the frame drop logic,
1233 // because the latter depends on encoder_->GetScalingSettings.
1234 // According to the testcase
1235 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
1236 // from GetScalingSettings should enable or disable the frame drop.
1237
Erik Språnga8d48ab2019-02-08 14:17:40 +01001238 // Update input frame rate before we start using it. If we update it after
Erik Språngd7329ca2019-02-21 21:19:53 +01001239 // any potential frame drop we are going to artificially increase frame sizes.
1240 // Poll the rate before updating, otherwise we risk the rate being estimated
1241 // a little too high at the start of the call when then window is small.
Niels Möller6bb5ab92019-01-11 11:11:10 +01001242 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språngd7329ca2019-02-21 21:19:53 +01001243 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001244
Niels Möller4db138e2018-04-19 09:04:13 +02001245 int64_t now_ms = clock_->TimeInMilliseconds();
1246 if (pending_encoder_reconfiguration_) {
1247 ReconfigureEncoder();
1248 last_parameters_update_ms_.emplace(now_ms);
1249 } else if (!last_parameters_update_ms_ ||
1250 now_ms - *last_parameters_update_ms_ >=
1251 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001252 if (last_encoder_rate_settings_) {
1253 // Clone rate settings before update, so that SetEncoderRates() will
1254 // actually detect the change between the input and
1255 // |last_encoder_rate_setings_|, triggering the call to SetRate() on the
1256 // encoder.
1257 EncoderRateSettings new_rate_settings = *last_encoder_rate_settings_;
1258 new_rate_settings.framerate_fps = static_cast<double>(framerate_fps);
1259 SetEncoderRates(
1260 UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
1261 }
Niels Möller4db138e2018-04-19 09:04:13 +02001262 last_parameters_update_ms_.emplace(now_ms);
1263 }
1264
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001265 // Because pending frame will be dropped in any case, we need to
1266 // remember its updated region.
1267 if (pending_frame_) {
1268 encoder_stats_observer_->OnFrameDropped(
1269 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
1270 accumulated_update_rect_.Union(pending_frame_->update_rect());
1271 }
1272
Sebastian Janssona3177052018-04-10 13:05:49 +02001273 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001274 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 08:49:53 +01001275 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -08001276 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 08:49:53 +01001277 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
Niels Möller213618e2018-07-24 09:29:58 +02001278 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 08:49:53 +01001279 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001280 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001281 // Storing references to a native buffer risks blocking frame capture.
1282 if (video_frame.video_frame_buffer()->type() !=
1283 VideoFrameBuffer::Type::kNative) {
1284 pending_frame_ = video_frame;
1285 pending_frame_post_time_us_ = time_when_posted_us;
1286 } else {
1287 // Ensure that any previously stored frame is dropped.
1288 pending_frame_.reset();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001289 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001290 }
kthelgason2bc68642017-02-07 07:02:22 -08001291 return;
1292 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001293 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -08001294
perkj26091b12016-09-01 01:17:40 -07001295 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001296 // Storing references to a native buffer risks blocking frame capture.
1297 if (video_frame.video_frame_buffer()->type() !=
1298 VideoFrameBuffer::Type::kNative) {
1299 if (pending_frame_)
1300 TraceFrameDropStart();
1301 pending_frame_ = video_frame;
1302 pending_frame_post_time_us_ = time_when_posted_us;
1303 } else {
1304 // Ensure that any previously stored frame is dropped.
1305 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +02001306 TraceFrameDropStart();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001307 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001308 }
perkj26091b12016-09-01 01:17:40 -07001309 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001310 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001311
1312 pending_frame_.reset();
Niels Möller6bb5ab92019-01-11 11:11:10 +01001313
1314 frame_dropper_.Leak(framerate_fps);
1315 // Frame dropping is enabled iff frame dropping is not force-disabled, and
1316 // rate controller is not trusted.
1317 const bool frame_dropping_enabled =
1318 !force_disable_frame_dropper_ &&
1319 !encoder_info_.has_trusted_rate_controller;
1320 frame_dropper_.Enable(frame_dropping_enabled);
1321 if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001322 RTC_LOG(LS_VERBOSE)
1323 << "Drop Frame: "
1324 << "target bitrate "
1325 << (last_encoder_rate_settings_
1326 ? last_encoder_rate_settings_->encoder_target.bps()
1327 : 0)
1328 << ", input frame rate " << framerate_fps;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001329 OnDroppedFrame(
1330 EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001331 accumulated_update_rect_.Union(video_frame.update_rect());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001332 return;
1333 }
1334
Sebastian Janssona3177052018-04-10 13:05:49 +02001335 EncodeVideoFrame(video_frame, time_when_posted_us);
1336}
1337
1338void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
1339 int64_t time_when_posted_us) {
1340 RTC_DCHECK_RUN_ON(&encoder_queue_);
philipele8ed8302019-07-03 11:53:48 +02001341
1342 // If the encoder fail we can't continue to encode frames. When this happens
1343 // the WebrtcVideoSender is notified and the whole VideoSendStream is
1344 // recreated.
1345 if (encoder_failed_)
1346 return;
1347
perkj26091b12016-09-01 01:17:40 -07001348 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +00001349
ilnik6b826ef2017-06-16 06:53:48 -07001350 VideoFrame out_frame(video_frame);
1351 // Crop frame if needed.
1352 if (crop_width_ > 0 || crop_height_ > 0) {
Noah Richards51db4212019-06-12 06:59:12 -07001353 // If the frame can't be converted to I420, drop it.
1354 auto i420_buffer = video_frame.video_frame_buffer()->ToI420();
1355 if (!i420_buffer) {
1356 RTC_LOG(LS_ERROR) << "Frame conversion for crop failed, dropping frame.";
1357 return;
1358 }
ilnik6b826ef2017-06-16 06:53:48 -07001359 int cropped_width = video_frame.width() - crop_width_;
1360 int cropped_height = video_frame.height() - crop_height_;
1361 rtc::scoped_refptr<I420Buffer> cropped_buffer =
1362 I420Buffer::Create(cropped_width, cropped_height);
1363 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
1364 // happen after SinkWants signaled correctly from ReconfigureEncoder.
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001365 VideoFrame::UpdateRect update_rect = video_frame.update_rect();
ilnik6b826ef2017-06-16 06:53:48 -07001366 if (crop_width_ < 4 && crop_height_ < 4) {
Noah Richards51db4212019-06-12 06:59:12 -07001367 cropped_buffer->CropAndScaleFrom(*i420_buffer, crop_width_ / 2,
1368 crop_height_ / 2, cropped_width,
1369 cropped_height);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001370 update_rect.offset_x -= crop_width_ / 2;
1371 update_rect.offset_y -= crop_height_ / 2;
1372 update_rect.Intersect(
1373 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height});
1374
ilnik6b826ef2017-06-16 06:53:48 -07001375 } else {
Noah Richards51db4212019-06-12 06:59:12 -07001376 cropped_buffer->ScaleFrom(*i420_buffer);
Ilya Nikolaevskiy1c90cab2019-03-07 15:30:58 +01001377 if (!update_rect.IsEmpty()) {
1378 // Since we can't reason about pixels after scaling, we invalidate whole
1379 // picture, if anything changed.
1380 update_rect =
1381 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height};
1382 }
ilnik6b826ef2017-06-16 06:53:48 -07001383 }
Ilya Nikolaevskiy4fc08552019-06-05 15:59:12 +02001384 out_frame.set_video_frame_buffer(cropped_buffer);
1385 out_frame.set_update_rect(update_rect);
ilnik6b826ef2017-06-16 06:53:48 -07001386 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001387 // Since accumulated_update_rect_ is constructed before cropping,
1388 // we can't trust it. If any changes were pending, we invalidate whole
1389 // frame here.
1390 if (!accumulated_update_rect_.IsEmpty()) {
1391 accumulated_update_rect_ =
1392 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1393 }
1394 }
1395
1396 if (!accumulated_update_rect_.IsEmpty()) {
1397 accumulated_update_rect_.Union(out_frame.update_rect());
1398 accumulated_update_rect_.Intersect(
1399 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()});
1400 out_frame.set_update_rect(accumulated_update_rect_);
1401 accumulated_update_rect_.MakeEmptyUpdate();
ilnik6b826ef2017-06-16 06:53:48 -07001402 }
1403
Magnus Jedvert26679d62015-04-07 14:07:41 +02001404 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +00001405 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +00001406
Niels Möller7dc26b72017-12-06 10:27:48 +01001407 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -07001408
Erik Språnge2fd86a2018-10-24 11:32:39 +02001409 // Encoder metadata needs to be updated before encode complete callback.
1410 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
1411 if (info.implementation_name != encoder_info_.implementation_name) {
1412 encoder_stats_observer_->OnEncoderImplementationChanged(
1413 info.implementation_name);
Erik Språng7ca375c2019-02-06 16:20:17 +01001414 if (bitrate_adjuster_) {
1415 // Encoder implementation changed, reset overshoot detector states.
1416 bitrate_adjuster_->Reset();
1417 }
Erik Språnge2fd86a2018-10-24 11:32:39 +02001418 }
Erik Språng7ca375c2019-02-06 16:20:17 +01001419
1420 if (bitrate_adjuster_) {
1421 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1422 if (info.fps_allocation[si] != encoder_info_.fps_allocation[si]) {
1423 bitrate_adjuster_->OnEncoderInfo(info);
1424 break;
1425 }
1426 }
1427 }
1428
Erik Språnge2fd86a2018-10-24 11:32:39 +02001429 encoder_info_ = info;
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001430 last_encode_info_ms_ = clock_->TimeInMilliseconds();
Erik Språngb7cb7b52019-02-26 15:52:33 +01001431 RTC_DCHECK_EQ(send_codec_.width, out_frame.width());
1432 RTC_DCHECK_EQ(send_codec_.height, out_frame.height());
Erik Språngd7329ca2019-02-21 21:19:53 +01001433 const VideoFrameBuffer::Type buffer_type =
1434 out_frame.video_frame_buffer()->type();
1435 const bool is_buffer_type_supported =
1436 buffer_type == VideoFrameBuffer::Type::kI420 ||
1437 (buffer_type == VideoFrameBuffer::Type::kNative &&
Erik Språng6a7baa72019-02-26 18:31:00 +01001438 info.supports_native_handle);
Erik Språngd7329ca2019-02-21 21:19:53 +01001439
1440 if (!is_buffer_type_supported) {
1441 // This module only supports software encoding.
1442 rtc::scoped_refptr<I420BufferInterface> converted_buffer(
1443 out_frame.video_frame_buffer()->ToI420());
1444
1445 if (!converted_buffer) {
1446 RTC_LOG(LS_ERROR) << "Frame conversion failed, dropping frame.";
1447 return;
1448 }
1449
Ilya Nikolaevskiycfff6522019-05-03 14:34:35 +02001450 VideoFrame::UpdateRect update_rect = out_frame.update_rect();
1451 if (!update_rect.IsEmpty() &&
1452 out_frame.video_frame_buffer()->GetI420() == nullptr) {
1453 // UpdatedRect is reset to full update if it's not empty, and buffer was
1454 // converted, therefore we can't guarantee that pixels outside of
1455 // UpdateRect didn't change comparing to the previous frame.
1456 update_rect =
1457 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1458 }
Ilya Nikolaevskiy1c90cab2019-03-07 15:30:58 +01001459
Ilya Nikolaevskiy4fc08552019-06-05 15:59:12 +02001460 out_frame.set_video_frame_buffer(converted_buffer);
1461 out_frame.set_update_rect(update_rect);
Erik Språngd7329ca2019-02-21 21:19:53 +01001462 }
Erik Språng6a7baa72019-02-26 18:31:00 +01001463
1464 TRACE_EVENT1("webrtc", "VCMGenericEncoder::Encode", "timestamp",
1465 out_frame.timestamp());
1466
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001467 frame_encode_metadata_writer_.OnEncodeStarted(out_frame);
Erik Språng6a7baa72019-02-26 18:31:00 +01001468
Niels Möllerc8d2e732019-03-06 12:00:33 +01001469 const int32_t encode_status = encoder_->Encode(out_frame, &next_frame_types_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001470 was_encode_called_since_last_initialization_ = true;
Erik Språng6a7baa72019-02-26 18:31:00 +01001471
Erik Språngd7329ca2019-02-21 21:19:53 +01001472 if (encode_status < 0) {
philipele8ed8302019-07-03 11:53:48 +02001473 if (encode_status == WEBRTC_VIDEO_CODEC_ENCODER_FAILURE) {
1474 RTC_LOG(LS_ERROR) << "Encoder failed, failing encoder format: "
1475 << encoder_config_.video_format.ToString();
1476 if (settings_.encoder_failure_callback) {
1477 encoder_failed_ = true;
1478 settings_.encoder_failure_callback->OnEncoderFailure();
1479 } else {
1480 RTC_LOG(LS_ERROR)
1481 << "Encoder failed but no encoder fallback callback is registered";
1482 }
1483 } else {
1484 RTC_LOG(LS_ERROR) << "Failed to encode frame. Error code: "
1485 << encode_status;
1486 }
1487
Erik Språngd7329ca2019-02-21 21:19:53 +01001488 return;
1489 }
1490
1491 for (auto& it : next_frame_types_) {
Niels Möller8f7ce222019-03-21 15:43:58 +01001492 it = VideoFrameType::kVideoFrameDelta;
Erik Språngd7329ca2019-02-21 21:19:53 +01001493 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001494}
niklase@google.com470e71d2011-07-07 08:21:25 +00001495
mflodmancc3d4422017-08-03 08:27:51 -07001496void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -07001497 if (!encoder_queue_.IsCurrent()) {
1498 encoder_queue_.PostTask([this] { SendKeyFrame(); });
1499 return;
1500 }
1501 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +01001502 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Erik Språngd7329ca2019-02-21 21:19:53 +01001503 RTC_DCHECK(!next_frame_types_.empty());
Sergey Silkine62a08a2019-05-13 13:45:39 +02001504
1505 // TODO(webrtc:10615): Map keyframe request to spatial layer.
1506 std::fill(next_frame_types_.begin(), next_frame_types_.end(),
1507 VideoFrameType::kVideoFrameKey);
1508
Erik Språngd7329ca2019-02-21 21:19:53 +01001509 if (HasInternalSource()) {
1510 // Try to request the frame if we have an external encoder with
1511 // internal source since AddVideoFrame never will be called.
Erik Språng6a7baa72019-02-26 18:31:00 +01001512
1513 // TODO(nisse): Used only with internal source. Delete as soon as
1514 // that feature is removed. The only implementation I've been able
1515 // to find ignores what's in the frame. With one exception: It seems
1516 // a few test cases, e.g.,
1517 // VideoSendStreamTest.VideoSendStreamStopSetEncoderRateToZero, set
1518 // internal_source to true and use FakeEncoder. And the latter will
1519 // happily encode this 1x1 frame and pass it on down the pipeline.
1520 if (encoder_->Encode(VideoFrame::Builder()
1521 .set_video_frame_buffer(I420Buffer::Create(1, 1))
1522 .set_rotation(kVideoRotation_0)
1523 .set_timestamp_us(0)
1524 .build(),
Erik Språng6a7baa72019-02-26 18:31:00 +01001525 &next_frame_types_) == WEBRTC_VIDEO_CODEC_OK) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001526 // Try to remove just-performed keyframe request, if stream still exists.
Sergey Silkine62a08a2019-05-13 13:45:39 +02001527 std::fill(next_frame_types_.begin(), next_frame_types_.end(),
1528 VideoFrameType::kVideoFrameDelta);
Erik Språngd7329ca2019-02-21 21:19:53 +01001529 }
1530 }
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00001531}
1532
Elad Alonb6ef99b2019-04-10 16:37:07 +02001533void VideoStreamEncoder::OnLossNotification(
1534 const VideoEncoder::LossNotification& loss_notification) {
1535 if (!encoder_queue_.IsCurrent()) {
1536 encoder_queue_.PostTask(
1537 [this, loss_notification] { OnLossNotification(loss_notification); });
1538 return;
1539 }
1540
1541 RTC_DCHECK_RUN_ON(&encoder_queue_);
1542 if (encoder_) {
1543 encoder_->OnLossNotification(loss_notification);
1544 }
1545}
1546
mflodmancc3d4422017-08-03 08:27:51 -07001547EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001548 const EncodedImage& encoded_image,
1549 const CodecSpecificInfo* codec_specific_info,
1550 const RTPFragmentationHeader* fragmentation) {
Erik Språng6a7baa72019-02-26 18:31:00 +01001551 TRACE_EVENT_INSTANT1("webrtc", "VCMEncodedFrameCallback::Encoded",
1552 "timestamp", encoded_image.Timestamp());
1553 const size_t spatial_idx = encoded_image.SpatialIndex().value_or(0);
1554 EncodedImage image_copy(encoded_image);
1555
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001556 frame_encode_metadata_writer_.FillTimingInfo(spatial_idx, &image_copy);
Erik Språng6a7baa72019-02-26 18:31:00 +01001557
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001558 std::unique_ptr<RTPFragmentationHeader> fragmentation_copy =
1559 frame_encode_metadata_writer_.UpdateBitstream(codec_specific_info,
1560 fragmentation, &image_copy);
1561
Erik Språng6a7baa72019-02-26 18:31:00 +01001562 // Piggyback ALR experiment group id and simulcast id into the content type.
1563 const uint8_t experiment_id =
1564 experiment_groups_[videocontenttypehelpers::IsScreenshare(
1565 image_copy.content_type_)];
1566
1567 // TODO(ilnik): This will force content type extension to be present even
1568 // for realtime video. At the expense of miniscule overhead we will get
1569 // sliced receive statistics.
1570 RTC_CHECK(videocontenttypehelpers::SetExperimentId(&image_copy.content_type_,
1571 experiment_id));
1572 // We count simulcast streams from 1 on the wire. That's why we set simulcast
1573 // id in content type to +1 of that is actual simulcast index. This is because
1574 // value 0 on the wire is reserved for 'no simulcast stream specified'.
1575 RTC_CHECK(videocontenttypehelpers::SetSimulcastId(
1576 &image_copy.content_type_, static_cast<uint8_t>(spatial_idx + 1)));
1577
perkj26091b12016-09-01 01:17:40 -07001578 // Encoded is called on whatever thread the real encoder implementation run
1579 // on. In the case of hardware encoders, there might be several encoders
1580 // running in parallel on different threads.
Erik Språng6a7baa72019-02-26 18:31:00 +01001581 encoder_stats_observer_->OnSendEncodedImage(image_copy, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -07001582
philipelda5aa4d2019-04-26 13:37:37 +02001583 // The simulcast id is signaled in the SpatialIndex. This makes it impossible
1584 // to do simulcast for codecs that actually support spatial layers since we
1585 // can't distinguish between an actual spatial layer and a simulcast stream.
1586 // TODO(bugs.webrtc.org/10520): Signal the simulcast id explicitly.
1587 int simulcast_id = 0;
1588 if (codec_specific_info &&
1589 (codec_specific_info->codecType == kVideoCodecVP8 ||
1590 codec_specific_info->codecType == kVideoCodecH264 ||
1591 codec_specific_info->codecType == kVideoCodecGeneric)) {
1592 simulcast_id = encoded_image.SpatialIndex().value_or(0);
1593 }
1594
1595 std::unique_ptr<CodecSpecificInfo> codec_info_copy;
1596 {
1597 rtc::CritScope cs(&encoded_image_lock_);
1598
1599 if (codec_specific_info && codec_specific_info->generic_frame_info) {
1600 codec_info_copy =
1601 absl::make_unique<CodecSpecificInfo>(*codec_specific_info);
1602 GenericFrameInfo& generic_info = *codec_info_copy->generic_frame_info;
1603 generic_info.frame_id = next_frame_id_++;
1604
1605 if (encoder_buffer_state_.size() <= static_cast<size_t>(simulcast_id)) {
1606 RTC_LOG(LS_ERROR) << "At most " << encoder_buffer_state_.size()
1607 << " simulcast streams supported.";
1608 } else {
1609 std::array<int64_t, kMaxEncoderBuffers>& state =
1610 encoder_buffer_state_[simulcast_id];
1611 for (const CodecBufferUsage& buffer : generic_info.encoder_buffers) {
1612 if (state.size() <= static_cast<size_t>(buffer.id)) {
1613 RTC_LOG(LS_ERROR)
1614 << "At most " << state.size() << " encoder buffers supported.";
1615 break;
1616 }
1617
1618 if (buffer.referenced) {
1619 int64_t diff = generic_info.frame_id - state[buffer.id];
1620 if (diff <= 0) {
1621 RTC_LOG(LS_ERROR) << "Invalid frame diff: " << diff << ".";
1622 } else if (absl::c_find(generic_info.frame_diffs, diff) ==
1623 generic_info.frame_diffs.end()) {
1624 generic_info.frame_diffs.push_back(diff);
1625 }
1626 }
1627
1628 if (buffer.updated)
1629 state[buffer.id] = generic_info.frame_id;
1630 }
1631 }
1632 }
1633 }
1634
1635 EncodedImageCallback::Result result = sink_->OnEncodedImage(
1636 image_copy, codec_info_copy ? codec_info_copy.get() : codec_specific_info,
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001637 fragmentation_copy ? fragmentation_copy.get() : fragmentation);
perkjbc75d972016-05-02 06:31:25 -07001638
Erik Språng7ca375c2019-02-06 16:20:17 +01001639 // We are only interested in propagating the meta-data about the image, not
1640 // encoded data itself, to the post encode function. Since we cannot be sure
1641 // the pointer will still be valid when run on the task queue, set it to null.
Erik Språng6a7baa72019-02-26 18:31:00 +01001642 image_copy.set_buffer(nullptr, 0);
Niels Möller83dbeac2017-12-14 16:39:44 +01001643
Erik Språng7ca375c2019-02-06 16:20:17 +01001644 int temporal_index = 0;
1645 if (codec_specific_info) {
1646 if (codec_specific_info->codecType == kVideoCodecVP9) {
1647 temporal_index = codec_specific_info->codecSpecific.VP9.temporal_idx;
1648 } else if (codec_specific_info->codecType == kVideoCodecVP8) {
1649 temporal_index = codec_specific_info->codecSpecific.VP8.temporalIdx;
1650 }
1651 }
1652 if (temporal_index == kNoTemporalIdx) {
1653 temporal_index = 0;
Niels Möller83dbeac2017-12-14 16:39:44 +01001654 }
1655
Erik Språng982dc792019-03-13 16:33:02 +01001656 RunPostEncode(image_copy, rtc::TimeMicros(), temporal_index);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001657
1658 if (result.error == Result::OK) {
1659 // In case of an internal encoder running on a separate thread, the
1660 // decision to drop a frame might be a frame late and signaled via
1661 // atomic flag. This is because we can't easily wait for the worker thread
1662 // without risking deadlocks, eg during shutdown when the worker thread
1663 // might be waiting for the internal encoder threads to stop.
1664 if (pending_frame_drops_.load() > 0) {
1665 int pending_drops = pending_frame_drops_.fetch_sub(1);
1666 RTC_DCHECK_GT(pending_drops, 0);
1667 result.drop_next_frame = true;
1668 }
1669 }
perkj803d97f2016-11-01 11:45:46 -07001670
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001671 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001672}
1673
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001674void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
1675 switch (reason) {
1676 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 09:29:58 +02001677 encoder_stats_observer_->OnFrameDropped(
1678 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001679 encoder_queue_.PostTask([this] {
1680 RTC_DCHECK_RUN_ON(&encoder_queue_);
1681 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +02001682 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001683 });
1684 break;
1685 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 09:29:58 +02001686 encoder_stats_observer_->OnFrameDropped(
1687 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 16:53:25 +02001688 encoder_queue_.PostTask([this] {
1689 RTC_DCHECK_RUN_ON(&encoder_queue_);
1690 if (quality_scaler_)
1691 quality_scaler_->ReportDroppedFrameByEncoder();
1692 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001693 break;
1694 }
kthelgason876222f2016-11-29 01:44:11 -08001695}
1696
Erik Språng610c7632019-03-06 15:37:33 +01001697void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate,
Erik Språng4c6ca302019-04-08 15:14:01 +02001698 DataRate link_allocation,
mflodmancc3d4422017-08-03 08:27:51 -07001699 uint8_t fraction_lost,
1700 int64_t round_trip_time_ms) {
Sebastian Jansson5a000162019-04-12 11:21:32 +02001701 RTC_DCHECK_GE(link_allocation, target_bitrate);
perkj26091b12016-09-01 01:17:40 -07001702 if (!encoder_queue_.IsCurrent()) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001703 encoder_queue_.PostTask([this, target_bitrate, link_allocation,
Erik Språng610c7632019-03-06 15:37:33 +01001704 fraction_lost, round_trip_time_ms] {
Erik Språng4c6ca302019-04-08 15:14:01 +02001705 OnBitrateUpdated(target_bitrate, link_allocation, fraction_lost,
Erik Språng610c7632019-03-06 15:37:33 +01001706 round_trip_time_ms);
1707 });
perkj26091b12016-09-01 01:17:40 -07001708 return;
1709 }
1710 RTC_DCHECK_RUN_ON(&encoder_queue_);
1711 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
1712
Erik Språng610c7632019-03-06 15:37:33 +01001713 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << target_bitrate.bps()
Erik Språng4c6ca302019-04-08 15:14:01 +02001714 << " link allocation bitrate = " << link_allocation.bps()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001715 << " packet loss " << static_cast<int>(fraction_lost)
1716 << " rtt " << round_trip_time_ms;
Åsa Persson139f4dc2019-08-02 09:29:58 +02001717
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001718 // On significant changes to BWE at the start of the call,
1719 // enable frame drops to quickly react to jumps in available bandwidth.
1720 if (encoder_start_bitrate_bps_ != 0 &&
1721 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
1722 initial_framedrop_on_bwe_enabled_ &&
Erik Språng610c7632019-03-06 15:37:33 +01001723 abs_diff(target_bitrate.bps(), encoder_start_bitrate_bps_) >=
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001724 kFramedropThreshold * encoder_start_bitrate_bps_) {
1725 // Reset initial framedrop feature when first real BW estimate arrives.
1726 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
1727 // without an actual BW estimate.
1728 initial_framedrop_ = 0;
1729 has_seen_first_significant_bwe_change_ = true;
1730 }
Åsa Persson139f4dc2019-08-02 09:29:58 +02001731 if (set_start_bitrate_bps_ > 0 && !has_seen_first_bwe_drop_ &&
1732 quality_scaler_ && quality_scaler_settings_.InitialBitrateIntervalMs() &&
1733 quality_scaler_settings_.InitialBitrateFactor()) {
1734 int64_t diff_ms = clock_->TimeInMilliseconds() - set_start_bitrate_time_ms_;
1735 if (diff_ms < quality_scaler_settings_.InitialBitrateIntervalMs().value() &&
1736 (target_bitrate.bps() <
1737 (set_start_bitrate_bps_ *
1738 quality_scaler_settings_.InitialBitrateFactor().value()))) {
1739 RTC_LOG(LS_INFO) << "Reset initial_framedrop_. Start bitrate: "
1740 << set_start_bitrate_bps_
1741 << ", target bitrate: " << target_bitrate.bps();
1742 initial_framedrop_ = 0;
1743 has_seen_first_bwe_drop_ = true;
1744 }
1745 }
perkj26091b12016-09-01 01:17:40 -07001746
Elad Aloncde8ab22019-03-20 11:56:20 +01001747 if (encoder_) {
1748 encoder_->OnPacketLossRateUpdate(static_cast<float>(fraction_lost) / 256.f);
1749 encoder_->OnRttUpdate(round_trip_time_ms);
1750 }
1751
Niels Möller6bb5ab92019-01-11 11:11:10 +01001752 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språng610c7632019-03-06 15:37:33 +01001753 frame_dropper_.SetRates((target_bitrate.bps() + 500) / 1000, framerate_fps);
Erik Språng4c6ca302019-04-08 15:14:01 +02001754 const bool video_is_suspended = target_bitrate == DataRate::Zero();
1755 const bool video_suspension_changed = video_is_suspended != EncoderPaused();
1756
1757 EncoderRateSettings new_rate_settings{VideoBitrateAllocation(),
1758 static_cast<double>(framerate_fps),
1759 link_allocation, target_bitrate};
1760 SetEncoderRates(UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
perkj26091b12016-09-01 01:17:40 -07001761
Erik Språng610c7632019-03-06 15:37:33 +01001762 encoder_start_bitrate_bps_ = target_bitrate.bps() != 0
1763 ? target_bitrate.bps()
1764 : encoder_start_bitrate_bps_;
Peter Boströmd153a372015-11-10 15:27:12 +00001765
sprang552c7c72017-02-13 04:41:45 -08001766 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001767 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
1768 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 09:29:58 +02001769 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +02001770 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001771 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
1772 !DropDueToSize(pending_frame_->size())) {
1773 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
1774 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
1775 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
1776 pending_frame_.reset();
1777 }
1778}
1779
1780bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001781 if (initial_framedrop_ < kMaxInitialFramedrop &&
Sebastian Janssona3177052018-04-10 13:05:49 +02001782 encoder_start_bitrate_bps_ > 0) {
1783 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
1784 return pixel_count > 320 * 240;
1785 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
1786 return pixel_count > 640 * 480;
1787 }
1788 }
1789 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001790}
1791
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001792bool VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001793 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -07001794 AdaptationRequest adaptation_request = {
1795 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001796 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001797 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -07001798
sprangc5d62e22017-04-02 23:53:04 -07001799 bool downgrade_requested =
1800 last_adaptation_request_ &&
1801 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1802
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001803 bool did_adapt = true;
1804
sprangc5d62e22017-04-02 23:53:04 -07001805 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001806 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-13 23:25:22 -07001807 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001808 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-02 23:53:04 -07001809 if (downgrade_requested &&
1810 adaptation_request.input_pixel_count_ >=
1811 last_adaptation_request_->input_pixel_count_) {
1812 // Don't request lower resolution if the current resolution is not
1813 // lower than the last time we asked for the resolution to be lowered.
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001814 return true;
sprangc5d62e22017-04-02 23:53:04 -07001815 }
1816 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001817 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-02 23:53:04 -07001818 if (adaptation_request.framerate_fps_ <= 0 ||
1819 (downgrade_requested &&
1820 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1821 // If no input fps estimate available, can't determine how to scale down
1822 // framerate. Otherwise, don't request lower framerate if we don't have
1823 // a valid frame rate. Since framerate, unlike resolution, is a measure
1824 // we have to estimate, and can fluctuate naturally over time, don't
1825 // make the same kind of limitations as for resolution, but trust the
1826 // overuse detector to not trigger too often.
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001827 return true;
sprangc5d62e22017-04-02 23:53:04 -07001828 }
1829 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001830 case DegradationPreference::DISABLED:
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001831 return true;
sprang84a37592017-02-10 07:04:27 -08001832 }
sprangc5d62e22017-04-02 23:53:04 -07001833
sprangc5d62e22017-04-02 23:53:04 -07001834 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001835 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001836 // Try scale down framerate, if lower.
Åsa Persson48284b82019-07-08 10:01:12 +02001837 int fps = balanced_settings_.MinFps(encoder_config_.codec_type,
1838 last_frame_info_->pixel_count());
asaperssonf7e294d2017-06-13 23:25:22 -07001839 if (source_proxy_->RestrictFramerate(fps)) {
1840 GetAdaptCounter().IncrementFramerate(reason);
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001841 // Check if requested fps is higher (or close to) input fps.
1842 absl::optional<int> min_diff =
1843 balanced_settings_.MinFpsDiff(last_frame_info_->pixel_count());
1844 if (min_diff && adaptation_request.framerate_fps_ > 0) {
1845 int fps_diff = adaptation_request.framerate_fps_ - fps;
1846 if (fps_diff < min_diff.value()) {
1847 did_adapt = false;
1848 }
1849 }
asaperssonf7e294d2017-06-13 23:25:22 -07001850 break;
1851 }
1852 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001853 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001854 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001855 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001856 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001857 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07001858 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07001859 adaptation_request.input_pixel_count_,
Erik Språnge2fd86a2018-10-24 11:32:39 +02001860 encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001861 &min_pixels_reached)) {
1862 if (min_pixels_reached)
Niels Möller213618e2018-07-24 09:29:58 +02001863 encoder_stats_observer_->OnMinPixelLimitReached();
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001864 return true;
asaperssond0de2952017-04-21 01:47:31 -07001865 }
asaperssonf7e294d2017-06-13 23:25:22 -07001866 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001867 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001868 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001869 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001870 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001871 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1872 adaptation_request.framerate_fps_);
1873 if (requested_framerate == -1)
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001874 return true;
sprangfda496a2017-06-15 04:21:07 -07001875 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001876 overuse_detector_->OnTargetFramerateUpdated(
1877 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001878 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001879 break;
sprangfda496a2017-06-15 04:21:07 -07001880 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001881 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001882 RTC_NOTREACHED();
1883 }
1884
asaperssond0de2952017-04-21 01:47:31 -07001885 last_adaptation_request_.emplace(adaptation_request);
1886
asapersson09f05612017-05-15 23:40:18 -07001887 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001888
Mirko Bonadei675513b2017-11-09 11:09:25 +01001889 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001890 return did_adapt;
perkj26091b12016-09-01 01:17:40 -07001891}
1892
mflodmancc3d4422017-08-03 08:27:51 -07001893void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001894 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001895
1896 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1897 int num_downgrades = adapt_counter.TotalCount(reason);
1898 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001899 return;
asapersson09f05612017-05-15 23:40:18 -07001900 RTC_DCHECK_GT(num_downgrades, 0);
1901
sprangc5d62e22017-04-02 23:53:04 -07001902 AdaptationRequest adaptation_request = {
1903 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001904 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001905 AdaptationRequest::Mode::kAdaptUp};
1906
1907 bool adapt_up_requested =
1908 last_adaptation_request_ &&
1909 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001910
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001911 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-13 23:25:22 -07001912 if (adapt_up_requested &&
1913 adaptation_request.input_pixel_count_ <=
1914 last_adaptation_request_->input_pixel_count_) {
1915 // Don't request higher resolution if the current resolution is not
1916 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001917 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001918 }
sprangb1ca0732017-02-01 08:38:12 -08001919 }
sprangc5d62e22017-04-02 23:53:04 -07001920
sprangc5d62e22017-04-02 23:53:04 -07001921 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001922 case DegradationPreference::BALANCED: {
Åsa Persson4869bd62019-08-23 16:20:06 +02001923 // Check if quality should be increased based on bitrate.
1924 if (reason == kQuality &&
1925 !balanced_settings_.CanAdaptUp(last_frame_info_->pixel_count(),
1926 encoder_start_bitrate_bps_)) {
Åsa Persson1b247f12019-08-14 17:26:39 +02001927 return;
1928 }
asaperssonf7e294d2017-06-13 23:25:22 -07001929 // Try scale up framerate, if higher.
Åsa Persson48284b82019-07-08 10:01:12 +02001930 int fps = balanced_settings_.MaxFps(encoder_config_.codec_type,
1931 last_frame_info_->pixel_count());
asaperssonf7e294d2017-06-13 23:25:22 -07001932 if (source_proxy_->IncreaseFramerate(fps)) {
1933 GetAdaptCounter().DecrementFramerate(reason, fps);
1934 // Reset framerate in case of fewer fps steps down than up.
1935 if (adapt_counter.FramerateCount() == 0 &&
1936 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001937 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001938 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1939 }
1940 break;
1941 }
Åsa Persson30ab0152019-08-27 12:22:33 +02001942 // Check if resolution should be increased based on bitrate.
1943 if (reason == kQuality &&
1944 !balanced_settings_.CanAdaptUpResolution(
1945 last_frame_info_->pixel_count(), encoder_start_bitrate_bps_)) {
1946 return;
1947 }
asaperssonf7e294d2017-06-13 23:25:22 -07001948 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001949 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001950 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001951 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001952 // Scale up resolution.
1953 int pixel_count = adaptation_request.input_pixel_count_;
1954 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001955 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001956 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001957 }
asapersson13874762017-06-07 00:01:02 -07001958 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1959 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001960 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001961 break;
asapersson13874762017-06-07 00:01:02 -07001962 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001963 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001964 // Scale up framerate.
1965 int fps = adaptation_request.framerate_fps_;
1966 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001967 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001968 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001969 }
sprangfda496a2017-06-15 04:21:07 -07001970
1971 const int requested_framerate =
1972 source_proxy_->RequestHigherFramerateThan(fps);
1973 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001974 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001975 return;
sprangfda496a2017-06-15 04:21:07 -07001976 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001977 overuse_detector_->OnTargetFramerateUpdated(
1978 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001979 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001980 break;
asapersson13874762017-06-07 00:01:02 -07001981 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001982 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-13 23:25:22 -07001983 return;
sprangc5d62e22017-04-02 23:53:04 -07001984 }
1985
asaperssond0de2952017-04-21 01:47:31 -07001986 last_adaptation_request_.emplace(adaptation_request);
1987
asapersson09f05612017-05-15 23:40:18 -07001988 UpdateAdaptationStats(reason);
1989
Mirko Bonadei675513b2017-11-09 11:09:25 +01001990 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001991}
1992
Niels Möller213618e2018-07-24 09:29:58 +02001993// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 08:27:51 -07001994void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001995 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001996 case kCpu:
Niels Möller213618e2018-07-24 09:29:58 +02001997 encoder_stats_observer_->OnAdaptationChanged(
1998 VideoStreamEncoderObserver::AdaptationReason::kCpu,
1999 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-15 23:40:18 -07002000 break;
2001 case kQuality:
Niels Möller213618e2018-07-24 09:29:58 +02002002 encoder_stats_observer_->OnAdaptationChanged(
2003 VideoStreamEncoderObserver::AdaptationReason::kQuality,
2004 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07002005 break;
2006 }
perkj26091b12016-09-01 01:17:40 -07002007}
2008
Niels Möller213618e2018-07-24 09:29:58 +02002009VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 08:27:51 -07002010 AdaptReason reason) {
Niels Möller213618e2018-07-24 09:29:58 +02002011 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 08:27:51 -07002012 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07002013 switch (reason) {
2014 case kCpu:
2015 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02002016 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002017 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02002018 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002019 break;
2020 case kQuality:
2021 if (!IsFramerateScalingEnabled(degradation_preference_) ||
2022 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02002023 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002024 }
2025 if (!IsResolutionScalingEnabled(degradation_preference_) ||
2026 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02002027 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002028 }
2029 break;
sprangc5d62e22017-04-02 23:53:04 -07002030 }
asapersson09f05612017-05-15 23:40:18 -07002031 return counts;
sprangc5d62e22017-04-02 23:53:04 -07002032}
2033
mflodmancc3d4422017-08-03 08:27:51 -07002034VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002035 return adapt_counters_[degradation_preference_];
2036}
2037
mflodmancc3d4422017-08-03 08:27:51 -07002038const VideoStreamEncoder::AdaptCounter&
2039VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002040 return adapt_counters_[degradation_preference_];
2041}
2042
Erik Språng7ca375c2019-02-06 16:20:17 +01002043void VideoStreamEncoder::RunPostEncode(EncodedImage encoded_image,
Niels Möller6bb5ab92019-01-11 11:11:10 +01002044 int64_t time_sent_us,
Erik Språng7ca375c2019-02-06 16:20:17 +01002045 int temporal_index) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01002046 if (!encoder_queue_.IsCurrent()) {
Erik Språng7ca375c2019-02-06 16:20:17 +01002047 encoder_queue_.PostTask(
2048 [this, encoded_image, time_sent_us, temporal_index] {
2049 RunPostEncode(encoded_image, time_sent_us, temporal_index);
2050 });
Niels Möller6bb5ab92019-01-11 11:11:10 +01002051 return;
2052 }
2053
2054 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +01002055
2056 absl::optional<int> encode_duration_us;
2057 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
2058 encode_duration_us =
2059 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
2060 rtc::kNumMicrosecsPerMillisec *
2061 (encoded_image.timing_.encode_finish_ms -
2062 encoded_image.timing_.encode_start_ms);
2063 }
2064
2065 // Run post encode tasks, such as overuse detection and frame rate/drop
2066 // stats for internal encoders.
2067 const size_t frame_size = encoded_image.size();
Niels Möller87e2d782019-03-07 10:18:23 +01002068 const bool keyframe =
2069 encoded_image._frameType == VideoFrameType::kVideoFrameKey;
Erik Språng7ca375c2019-02-06 16:20:17 +01002070
2071 if (frame_size > 0) {
2072 frame_dropper_.Fill(frame_size, !keyframe);
Niels Möller6bb5ab92019-01-11 11:11:10 +01002073 }
2074
Erik Språngd7329ca2019-02-21 21:19:53 +01002075 if (HasInternalSource()) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01002076 // Update frame dropper after the fact for internal sources.
2077 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
2078 frame_dropper_.Leak(GetInputFramerateFps());
2079 // Signal to encoder to drop next frame.
2080 if (frame_dropper_.DropFrame()) {
2081 pending_frame_drops_.fetch_add(1);
2082 }
2083 }
2084
Erik Språng7ca375c2019-02-06 16:20:17 +01002085 overuse_detector_->FrameSent(
2086 encoded_image.Timestamp(), time_sent_us,
2087 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec,
2088 encode_duration_us);
2089 if (quality_scaler_ && encoded_image.qp_ >= 0)
Sebastian Janssonb6789402019-03-01 15:40:49 +01002090 quality_scaler_->ReportQp(encoded_image.qp_, time_sent_us);
Erik Språng7ca375c2019-02-06 16:20:17 +01002091 if (bitrate_adjuster_) {
2092 bitrate_adjuster_->OnEncodedFrame(encoded_image, temporal_index);
2093 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01002094}
2095
Erik Språngd7329ca2019-02-21 21:19:53 +01002096bool VideoStreamEncoder::HasInternalSource() const {
2097 // TODO(sprang): Checking both info from encoder and from encoder factory
2098 // until we have deprecated and removed the encoder factory info.
2099 return codec_info_.has_internal_source || encoder_info_.has_internal_source;
2100}
2101
Erik Språng6a7baa72019-02-26 18:31:00 +01002102void VideoStreamEncoder::ReleaseEncoder() {
2103 if (!encoder_ || !encoder_initialized_) {
2104 return;
2105 }
2106 encoder_->Release();
2107 encoder_initialized_ = false;
2108 TRACE_EVENT0("webrtc", "VCMGenericEncoder::Release");
2109}
2110
asapersson09f05612017-05-15 23:40:18 -07002111// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07002112VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002113 fps_counters_.resize(kScaleReasonSize);
2114 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07002115 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07002116}
2117
mflodmancc3d4422017-08-03 08:27:51 -07002118VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07002119
mflodmancc3d4422017-08-03 08:27:51 -07002120std::string VideoStreamEncoder::AdaptCounter::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02002121 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07002122 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
2123 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
Jonas Olsson84df1c72018-09-14 16:59:32 +02002124 return ss.Release();
asapersson09f05612017-05-15 23:40:18 -07002125}
2126
Niels Möller213618e2018-07-24 09:29:58 +02002127VideoStreamEncoderObserver::AdaptationSteps
2128VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
2129 VideoStreamEncoderObserver::AdaptationSteps counts;
2130 counts.num_framerate_reductions = fps_counters_[reason];
2131 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-15 23:40:18 -07002132 return counts;
2133}
2134
mflodmancc3d4422017-08-03 08:27:51 -07002135void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002136 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07002137}
2138
mflodmancc3d4422017-08-03 08:27:51 -07002139void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002140 ++(resolution_counters_[reason]);
2141}
2142
mflodmancc3d4422017-08-03 08:27:51 -07002143void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002144 if (fps_counters_[reason] == 0) {
2145 // Balanced mode: Adapt up is in a different order, switch reason.
2146 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
2147 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
2148 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
2149 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
2150 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
2151 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
2152 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
2153 MoveCount(&resolution_counters_, reason);
2154 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
2155 }
2156 --(fps_counters_[reason]);
2157 RTC_DCHECK_GE(fps_counters_[reason], 0);
2158}
2159
mflodmancc3d4422017-08-03 08:27:51 -07002160void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002161 if (resolution_counters_[reason] == 0) {
2162 // Balanced mode: Adapt up is in a different order, switch reason.
2163 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
2164 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
2165 MoveCount(&fps_counters_, reason);
2166 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
2167 }
2168 --(resolution_counters_[reason]);
2169 RTC_DCHECK_GE(resolution_counters_[reason], 0);
2170}
2171
mflodmancc3d4422017-08-03 08:27:51 -07002172void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
2173 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07002174 DecrementFramerate(reason);
2175 // Reset if at max fps (i.e. in case of fewer steps up than down).
2176 if (cur_fps == std::numeric_limits<int>::max())
Steve Antonbd631a02019-03-28 10:51:27 -07002177 absl::c_fill(fps_counters_, 0);
asapersson09f05612017-05-15 23:40:18 -07002178}
2179
mflodmancc3d4422017-08-03 08:27:51 -07002180int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07002181 return Count(fps_counters_);
2182}
2183
mflodmancc3d4422017-08-03 08:27:51 -07002184int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07002185 return Count(resolution_counters_);
2186}
2187
mflodmancc3d4422017-08-03 08:27:51 -07002188int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002189 return fps_counters_[reason];
2190}
2191
mflodmancc3d4422017-08-03 08:27:51 -07002192int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002193 return resolution_counters_[reason];
2194}
2195
mflodmancc3d4422017-08-03 08:27:51 -07002196int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002197 return FramerateCount(reason) + ResolutionCount(reason);
2198}
2199
mflodmancc3d4422017-08-03 08:27:51 -07002200int VideoStreamEncoder::AdaptCounter::Count(
2201 const std::vector<int>& counters) const {
Steve Antonbd631a02019-03-28 10:51:27 -07002202 return absl::c_accumulate(counters, 0);
asapersson09f05612017-05-15 23:40:18 -07002203}
2204
mflodmancc3d4422017-08-03 08:27:51 -07002205void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
2206 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002207 int to_reason = (from_reason + 1) % kScaleReasonSize;
2208 ++((*counters)[to_reason]);
2209 --((*counters)[from_reason]);
2210}
2211
mflodmancc3d4422017-08-03 08:27:51 -07002212std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07002213 const std::vector<int>& counters) const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02002214 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07002215 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
2216 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07002217 }
Jonas Olsson84df1c72018-09-14 16:59:32 +02002218 return ss.Release();
sprangc5d62e22017-04-02 23:53:04 -07002219}
2220
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00002221} // namespace webrtc