blob: f119acdc653584b1ab5eaa5256225d2eecb6de6a [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"
Sergey Silkin8b9b5f92018-12-10 09:28:53 +010023#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/video_coding/include/video_codec_initializer.h"
25#include "modules/video_coding/include/video_coding.h"
Niels Möller6bb5ab92019-01-11 11:11:10 +010026#include "modules/video_coding/utility/default_video_bitrate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/arraysize.h"
28#include "rtc_base/checks.h"
Erik Språng6a7baa72019-02-26 18:31:00 +010029#include "rtc_base/experiments/alr_experiment.h"
Åsa Perssona945aee2018-04-24 16:53:25 +020030#include "rtc_base/experiments/quality_scaling_experiment.h"
Erik Språng7ca375c2019-02-06 16:20:17 +010031#include "rtc_base/experiments/rate_control_settings.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/location.h"
33#include "rtc_base/logging.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020034#include "rtc_base/strings/string_builder.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010035#include "rtc_base/system/fallthrough.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/trace_event.h"
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020038#include "system_wrappers/include/field_trial.h"
nisseea3a7982017-05-15 02:42:11 -070039
niklase@google.com470e71d2011-07-07 08:21:25 +000040namespace webrtc {
41
perkj26091b12016-09-01 01:17:40 -070042namespace {
sprangb1ca0732017-02-01 08:38:12 -080043
asapersson6ffb67d2016-09-12 00:10:45 -070044// Time interval for logging frame counts.
45const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070046const int kMinFramerateFps = 2;
perkj26091b12016-09-01 01:17:40 -070047
Sebastian Janssona3177052018-04-10 13:05:49 +020048// Time to keep a single cached pending frame in paused state.
49const int64_t kPendingFrameTimeoutMs = 1000;
50
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020051const char kInitialFramedropFieldTrial[] = "WebRTC-InitialFramedrop";
Niels Möller6bb5ab92019-01-11 11:11:10 +010052constexpr char kFrameDropperFieldTrial[] = "WebRTC-FrameDropper";
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020053
kthelgason2bc68642017-02-07 07:02:22 -080054// The maximum number of frames to drop at beginning of stream
55// to try and achieve desired bitrate.
56const int kMaxInitialFramedrop = 4;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020057// When the first change in BWE above this threshold occurs,
58// enable DropFrameDueToSize logic.
59const float kFramedropThreshold = 0.3;
kthelgason2bc68642017-02-07 07:02:22 -080060
Niels Möller6bb5ab92019-01-11 11:11:10 +010061// Averaging window spanning 90 frames at default 30fps, matching old media
62// optimization module defaults.
63const int64_t kFrameRateAvergingWindowSizeMs = (1000 / 30) * 90;
64
Erik Språngb7cb7b52019-02-26 15:52:33 +010065const size_t kDefaultPayloadSize = 1440;
66
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070067// Initial limits for BALANCED degradation preference.
asaperssonf7e294d2017-06-13 23:25:22 -070068int MinFps(int pixels) {
69 if (pixels <= 320 * 240) {
70 return 7;
71 } else if (pixels <= 480 * 270) {
72 return 10;
73 } else if (pixels <= 640 * 480) {
74 return 15;
75 } else {
76 return std::numeric_limits<int>::max();
77 }
78}
79
80int MaxFps(int pixels) {
81 if (pixels <= 320 * 240) {
82 return 10;
83 } else if (pixels <= 480 * 270) {
84 return 15;
85 } else {
86 return std::numeric_limits<int>::max();
87 }
88}
89
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020090uint32_t abs_diff(uint32_t a, uint32_t b) {
91 return (a < b) ? b - a : a - b;
92}
93
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070094bool IsResolutionScalingEnabled(DegradationPreference degradation_preference) {
95 return degradation_preference == DegradationPreference::MAINTAIN_FRAMERATE ||
96 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070097}
98
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070099bool IsFramerateScalingEnabled(DegradationPreference degradation_preference) {
100 return degradation_preference == DegradationPreference::MAINTAIN_RESOLUTION ||
101 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -0700102}
103
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200104// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
105// pipelining encoders better (multiple input frames before something comes
106// out). This should effectively turn off CPU adaptations for systems that
107// remotely cope with the load right now.
108CpuOveruseOptions GetCpuOveruseOptions(
Niels Möller213618e2018-07-24 09:29:58 +0200109 const VideoStreamEncoderSettings& settings,
Niels Möller4db138e2018-04-19 09:04:13 +0200110 bool full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200111 CpuOveruseOptions options;
112
Niels Möller4db138e2018-04-19 09:04:13 +0200113 if (full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200114 options.low_encode_usage_threshold_percent = 150;
115 options.high_encode_usage_threshold_percent = 200;
116 }
117 if (settings.experiment_cpu_load_estimator) {
118 options.filter_time_ms = 5 * rtc::kNumMillisecsPerSec;
119 }
120
121 return options;
122}
123
Erik Språngb7cb7b52019-02-26 15:52:33 +0100124bool RequiresEncoderReset(const VideoCodec& previous_send_codec,
125 const VideoCodec& new_send_codec) {
126 // Does not check startBitrate or maxFramerate.
127 if (new_send_codec.codecType != previous_send_codec.codecType ||
128 new_send_codec.width != previous_send_codec.width ||
129 new_send_codec.height != previous_send_codec.height ||
130 new_send_codec.maxBitrate != previous_send_codec.maxBitrate ||
131 new_send_codec.minBitrate != previous_send_codec.minBitrate ||
132 new_send_codec.qpMax != previous_send_codec.qpMax ||
133 new_send_codec.numberOfSimulcastStreams !=
134 previous_send_codec.numberOfSimulcastStreams ||
135 new_send_codec.mode != previous_send_codec.mode) {
136 return true;
137 }
138
139 switch (new_send_codec.codecType) {
140 case kVideoCodecVP8:
141 if (new_send_codec.VP8() != previous_send_codec.VP8()) {
142 return true;
143 }
144 break;
145
146 case kVideoCodecVP9:
147 if (new_send_codec.VP9() != previous_send_codec.VP9()) {
148 return true;
149 }
150 break;
151
152 case kVideoCodecH264:
153 if (new_send_codec.H264() != previous_send_codec.H264()) {
154 return true;
155 }
156 break;
157
158 default:
159 break;
160 }
161
162 for (unsigned char i = 0; i < new_send_codec.numberOfSimulcastStreams; ++i) {
163 if (new_send_codec.simulcastStream[i] !=
164 previous_send_codec.simulcastStream[i])
165 return true;
166 }
167 return false;
168}
Erik Språng6a7baa72019-02-26 18:31:00 +0100169
170std::array<uint8_t, 2> GetExperimentGroups() {
171 std::array<uint8_t, 2> experiment_groups;
172 absl::optional<AlrExperimentSettings> experiment_settings =
173 AlrExperimentSettings::CreateFromFieldTrial(
174 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
175 if (experiment_settings) {
176 experiment_groups[0] = experiment_settings->group_id + 1;
177 } else {
178 experiment_groups[0] = 0;
179 }
180 experiment_settings = AlrExperimentSettings::CreateFromFieldTrial(
181 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
182 if (experiment_settings) {
183 experiment_groups[1] = experiment_settings->group_id + 1;
184 } else {
185 experiment_groups[1] = 0;
186 }
187 return experiment_groups;
188}
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100189
190// Limit allocation across TLs in bitrate allocation according to number of TLs
191// in EncoderInfo.
192VideoBitrateAllocation UpdateAllocationFromEncoderInfo(
193 const VideoBitrateAllocation& allocation,
194 const VideoEncoder::EncoderInfo& encoder_info) {
195 if (allocation.get_sum_bps() == 0) {
196 return allocation;
197 }
198 VideoBitrateAllocation new_allocation;
199 for (int si = 0; si < kMaxSpatialLayers; ++si) {
200 if (encoder_info.fps_allocation[si].size() == 1 &&
201 allocation.IsSpatialLayerUsed(si)) {
202 // One TL is signalled to be used by the encoder. Do not distribute
203 // bitrate allocation across TLs (use sum at ti:0).
204 new_allocation.SetBitrate(si, 0, allocation.GetSpatialLayerSum(si));
205 } else {
206 for (int ti = 0; ti < kMaxTemporalStreams; ++ti) {
207 if (allocation.HasBitrate(si, ti))
208 new_allocation.SetBitrate(si, ti, allocation.GetBitrate(si, ti));
209 }
210 }
211 }
212 return new_allocation;
213}
perkj26091b12016-09-01 01:17:40 -0700214} // namespace
215
perkja49cbd32016-09-16 07:53:41 -0700216// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700217// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
218// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700219// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700220class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700221 public:
mflodmancc3d4422017-08-03 08:27:51 -0700222 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
223 : video_stream_encoder_(video_stream_encoder),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700224 degradation_preference_(DegradationPreference::DISABLED),
Åsa Persson8c1bf952018-09-13 10:42:19 +0200225 source_(nullptr),
226 max_framerate_(std::numeric_limits<int>::max()) {}
perkja49cbd32016-09-16 07:53:41 -0700227
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700228 void SetSource(rtc::VideoSourceInterface<VideoFrame>* source,
229 const DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700230 // Called on libjingle's worker thread.
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200231 RTC_DCHECK_RUN_ON(&main_checker_);
perkja49cbd32016-09-16 07:53:41 -0700232 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700233 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700234 {
235 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700236 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700237 old_source = source_;
238 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700239 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700240 }
241
242 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700243 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700244 }
245
246 if (!source) {
247 return;
248 }
249
mflodmancc3d4422017-08-03 08:27:51 -0700250 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700251 }
252
Åsa Persson8c1bf952018-09-13 10:42:19 +0200253 void SetMaxFramerate(int max_framerate) {
254 RTC_DCHECK_GT(max_framerate, 0);
255 rtc::CritScope lock(&crit_);
256 if (max_framerate == max_framerate_)
257 return;
258
259 RTC_LOG(LS_INFO) << "Set max framerate: " << max_framerate;
260 max_framerate_ = max_framerate;
261 if (source_) {
262 source_->AddOrUpdateSink(video_stream_encoder_,
263 GetActiveSinkWantsInternal());
264 }
265 }
266
perkj803d97f2016-11-01 11:45:46 -0700267 void SetWantsRotationApplied(bool rotation_applied) {
268 rtc::CritScope lock(&crit_);
269 sink_wants_.rotation_applied = rotation_applied;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200270 if (source_) {
271 source_->AddOrUpdateSink(video_stream_encoder_,
272 GetActiveSinkWantsInternal());
273 }
sprangc5d62e22017-04-02 23:53:04 -0700274 }
275
sprangfda496a2017-06-15 04:21:07 -0700276 rtc::VideoSinkWants GetActiveSinkWants() {
277 rtc::CritScope lock(&crit_);
278 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700279 }
280
asaperssonf7e294d2017-06-13 23:25:22 -0700281 void ResetPixelFpsCount() {
282 rtc::CritScope lock(&crit_);
283 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
284 sink_wants_.target_pixel_count.reset();
285 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
286 if (source_)
Åsa Persson8c1bf952018-09-13 10:42:19 +0200287 source_->AddOrUpdateSink(video_stream_encoder_,
288 GetActiveSinkWantsInternal());
asaperssonf7e294d2017-06-13 23:25:22 -0700289 }
290
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100291 bool RequestResolutionLowerThan(int pixel_count,
292 int min_pixels_per_frame,
293 bool* min_pixels_reached) {
perkj803d97f2016-11-01 11:45:46 -0700294 // Called on the encoder task queue.
295 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700296 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700297 // This can happen since |degradation_preference_| is set on libjingle's
298 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700299 return false;
perkj803d97f2016-11-01 11:45:46 -0700300 }
asapersson13874762017-06-07 00:01:02 -0700301 // The input video frame size will have a resolution less than or equal to
302 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800303 const int pixels_wanted = (pixel_count * 3) / 5;
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100304 if (pixels_wanted >= sink_wants_.max_pixel_count) {
305 return false;
306 }
307 if (pixels_wanted < min_pixels_per_frame) {
308 *min_pixels_reached = true;
asaperssond0de2952017-04-21 01:47:31 -0700309 return false;
asapersson13874762017-06-07 00:01:02 -0700310 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100311 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
312 << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700313 sink_wants_.max_pixel_count = pixels_wanted;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200314 sink_wants_.target_pixel_count = absl::nullopt;
mflodmancc3d4422017-08-03 08:27:51 -0700315 source_->AddOrUpdateSink(video_stream_encoder_,
316 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700317 return true;
sprangc5d62e22017-04-02 23:53:04 -0700318 }
319
sprangfda496a2017-06-15 04:21:07 -0700320 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700321 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700322 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700323 int framerate_wanted = (fps * 2) / 3;
324 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700325 }
326
asapersson13874762017-06-07 00:01:02 -0700327 bool RequestHigherResolutionThan(int pixel_count) {
328 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700329 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700330 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700331 // This can happen since |degradation_preference_| is set on libjingle's
332 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700333 return false;
perkj803d97f2016-11-01 11:45:46 -0700334 }
asapersson13874762017-06-07 00:01:02 -0700335 int max_pixels_wanted = pixel_count;
336 if (max_pixels_wanted != std::numeric_limits<int>::max())
337 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700338
asapersson13874762017-06-07 00:01:02 -0700339 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
340 return false;
341
342 sink_wants_.max_pixel_count = max_pixels_wanted;
343 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700344 // Remove any constraints.
345 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700346 } else {
347 // On step down we request at most 3/5 the pixel count of the previous
348 // resolution, so in order to take "one step up" we request a resolution
349 // as close as possible to 5/3 of the current resolution. The actual pixel
350 // count selected depends on the capabilities of the source. In order to
351 // not take a too large step up, we cap the requested pixel count to be at
352 // most four time the current number of pixels.
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100353 sink_wants_.target_pixel_count = (pixel_count * 5) / 3;
sprangc5d62e22017-04-02 23:53:04 -0700354 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100355 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
356 << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700357 source_->AddOrUpdateSink(video_stream_encoder_,
358 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700359 return true;
sprangc5d62e22017-04-02 23:53:04 -0700360 }
361
sprangfda496a2017-06-15 04:21:07 -0700362 // Request upgrade in framerate. Returns the new requested frame, or -1 if
363 // no change requested. Note that maxint may be returned if limits due to
364 // adaptation requests are removed completely. In that case, consider
365 // |max_framerate_| to be the current limit (assuming the capturer complies).
366 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700367 // Called on the encoder task queue.
368 // The input frame rate will be scaled up to the last step, with rounding.
369 int framerate_wanted = fps;
370 if (fps != std::numeric_limits<int>::max())
371 framerate_wanted = (fps * 3) / 2;
372
sprangfda496a2017-06-15 04:21:07 -0700373 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700374 }
375
376 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700377 // Called on the encoder task queue.
378 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700379 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
380 return false;
381
382 const int fps_wanted = std::max(kMinFramerateFps, fps);
383 if (fps_wanted >= sink_wants_.max_framerate_fps)
384 return false;
385
Mirko Bonadei675513b2017-11-09 11:09:25 +0100386 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700387 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700388 source_->AddOrUpdateSink(video_stream_encoder_,
389 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700390 return true;
391 }
392
393 bool IncreaseFramerate(int fps) {
394 // Called on the encoder task queue.
395 rtc::CritScope lock(&crit_);
396 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
397 return false;
398
399 const int fps_wanted = std::max(kMinFramerateFps, fps);
400 if (fps_wanted <= sink_wants_.max_framerate_fps)
401 return false;
402
Mirko Bonadei675513b2017-11-09 11:09:25 +0100403 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700404 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700405 source_->AddOrUpdateSink(video_stream_encoder_,
406 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700407 return true;
perkj803d97f2016-11-01 11:45:46 -0700408 }
409
perkja49cbd32016-09-16 07:53:41 -0700410 private:
sprangfda496a2017-06-15 04:21:07 -0700411 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700412 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700413 rtc::VideoSinkWants wants = sink_wants_;
414 // Clear any constraints from the current sink wants that don't apply to
415 // the used degradation_preference.
416 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700417 case DegradationPreference::BALANCED:
sprangfda496a2017-06-15 04:21:07 -0700418 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700419 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangfda496a2017-06-15 04:21:07 -0700420 wants.max_framerate_fps = std::numeric_limits<int>::max();
421 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700422 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangfda496a2017-06-15 04:21:07 -0700423 wants.max_pixel_count = std::numeric_limits<int>::max();
424 wants.target_pixel_count.reset();
425 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700426 case DegradationPreference::DISABLED:
sprangfda496a2017-06-15 04:21:07 -0700427 wants.max_pixel_count = std::numeric_limits<int>::max();
428 wants.target_pixel_count.reset();
429 wants.max_framerate_fps = std::numeric_limits<int>::max();
430 }
Åsa Persson8c1bf952018-09-13 10:42:19 +0200431 // Limit to configured max framerate.
432 wants.max_framerate_fps = std::min(max_framerate_, wants.max_framerate_fps);
sprangfda496a2017-06-15 04:21:07 -0700433 return wants;
434 }
435
perkja49cbd32016-09-16 07:53:41 -0700436 rtc::CriticalSection crit_;
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200437 SequenceChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700438 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700439 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700440 DegradationPreference degradation_preference_ RTC_GUARDED_BY(&crit_);
danilchapa37de392017-09-09 04:17:22 -0700441 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
Åsa Persson8c1bf952018-09-13 10:42:19 +0200442 int max_framerate_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700443
444 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
445};
446
Erik Språng4c6ca302019-04-08 15:14:01 +0200447VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings()
448 : VideoEncoder::RateControlParameters(), encoder_target(DataRate::Zero()) {}
449
450VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings(
451 const VideoBitrateAllocation& bitrate,
452 double framerate_fps,
453 DataRate bandwidth_allocation,
454 DataRate encoder_target)
455 : VideoEncoder::RateControlParameters(bitrate,
456 framerate_fps,
457 bandwidth_allocation),
458 encoder_target(encoder_target) {}
459
460bool VideoStreamEncoder::EncoderRateSettings::operator==(
461 const EncoderRateSettings& rhs) const {
462 return bitrate == rhs.bitrate && framerate_fps == rhs.framerate_fps &&
463 bandwidth_allocation == rhs.bandwidth_allocation &&
464 encoder_target == rhs.encoder_target;
465}
466
467bool VideoStreamEncoder::EncoderRateSettings::operator!=(
468 const EncoderRateSettings& rhs) const {
469 return !(*this == rhs);
470}
471
Åsa Persson0122e842017-10-16 12:19:23 +0200472VideoStreamEncoder::VideoStreamEncoder(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100473 Clock* clock,
Åsa Persson0122e842017-10-16 12:19:23 +0200474 uint32_t number_of_cores,
Niels Möller213618e2018-07-24 09:29:58 +0200475 VideoStreamEncoderObserver* encoder_stats_observer,
476 const VideoStreamEncoderSettings& settings,
Sebastian Jansson74682c12019-03-01 11:50:20 +0100477 std::unique_ptr<OveruseFrameDetector> overuse_detector,
478 TaskQueueFactory* task_queue_factory)
perkj26091b12016-09-01 01:17:40 -0700479 : shutdown_event_(true /* manual_reset */, false),
480 number_of_cores_(number_of_cores),
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200481 initial_framedrop_(0),
482 initial_framedrop_on_bwe_enabled_(
483 webrtc::field_trial::IsEnabled(kInitialFramedropFieldTrial)),
Åsa Perssona945aee2018-04-24 16:53:25 +0200484 quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
perkja49cbd32016-09-16 07:53:41 -0700485 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200486 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700487 settings_(settings),
Erik Språng7ca375c2019-02-06 16:20:17 +0100488 rate_control_settings_(RateControlSettings::ParseFromFieldTrials()),
Niels Möller73f29cb2018-01-31 16:09:31 +0100489 overuse_detector_(std::move(overuse_detector)),
Niels Möller213618e2018-07-24 09:29:58 +0200490 encoder_stats_observer_(encoder_stats_observer),
Erik Språng6a7baa72019-02-26 18:31:00 +0100491 encoder_initialized_(false),
sprangfda496a2017-06-15 04:21:07 -0700492 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700493 pending_encoder_reconfiguration_(false),
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000494 pending_encoder_creation_(false),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200495 crop_width_(0),
496 crop_height_(0),
perkj26091b12016-09-01 01:17:40 -0700497 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 11:48:50 +0200498 max_data_payload_length_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000499 encoder_paused_and_dropped_frame_(false),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100500 clock_(clock),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700501 degradation_preference_(DegradationPreference::DISABLED),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700502 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700503 last_captured_timestamp_(0),
504 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
505 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700506 last_frame_log_ms_(clock_->TimeInMilliseconds()),
507 captured_frame_count_(0),
508 dropped_frame_count_(0),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200509 pending_frame_post_time_us_(0),
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100510 accumulated_update_rect_{0, 0, 0, 0},
sprang1a646ee2016-12-01 06:34:11 -0800511 bitrate_observer_(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 Nikolaevskiy4fb12b02019-05-02 14:44:29 +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
mflodmancc3d4422017-08-03 08:27:51 -0700562void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700563 rtc::VideoSourceInterface<VideoFrame>* source,
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700564 const DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700565 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700566 source_proxy_->SetSource(source, degradation_preference);
567 encoder_queue_.PostTask([this, degradation_preference] {
568 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700569 if (degradation_preference_ != degradation_preference) {
570 // Reset adaptation state, so that we're not tricked into thinking there's
571 // an already pending request of the same type.
572 last_adaptation_request_.reset();
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700573 if (degradation_preference == DegradationPreference::BALANCED ||
574 degradation_preference_ == DegradationPreference::BALANCED) {
asaperssonf7e294d2017-06-13 23:25:22 -0700575 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
576 // AdaptCounter for all modes.
577 source_proxy_->ResetPixelFpsCount();
578 adapt_counters_.clear();
579 }
sprangc5d62e22017-04-02 23:53:04 -0700580 }
sprangb1ca0732017-02-01 08:38:12 -0800581 degradation_preference_ = degradation_preference;
Niels Möller4db138e2018-04-19 09:04:13 +0200582
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000583 if (encoder_)
Erik Språng7ca375c2019-02-06 16:20:17 +0100584 ConfigureQualityScaler(encoder_->GetEncoderInfo());
Niels Möller4db138e2018-04-19 09:04:13 +0200585
Niels Möller7dc26b72017-12-06 10:27:48 +0100586 if (!IsFramerateScalingEnabled(degradation_preference) &&
587 max_framerate_ != -1) {
588 // If frame rate scaling is no longer allowed, remove any potential
589 // allowance for longer frame intervals.
590 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
591 }
perkj803d97f2016-11-01 11:45:46 -0700592 });
perkja49cbd32016-09-16 07:53:41 -0700593}
594
mflodmancc3d4422017-08-03 08:27:51 -0700595void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700596 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700597 encoder_queue_.PostTask([this, sink] {
598 RTC_DCHECK_RUN_ON(&encoder_queue_);
599 sink_ = sink;
600 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000601}
602
mflodmancc3d4422017-08-03 08:27:51 -0700603void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700604 encoder_queue_.PostTask([this, start_bitrate_bps] {
605 RTC_DCHECK_RUN_ON(&encoder_queue_);
606 encoder_start_bitrate_bps_ = start_bitrate_bps;
607 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000608}
Peter Boström00b9d212016-05-19 16:59:03 +0200609
mflodmancc3d4422017-08-03 08:27:51 -0700610void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200611 size_t max_data_payload_length) {
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100612 // TODO(srte): This struct should be replaced by a lambda with move capture
613 // when C++14 lambda is allowed.
614 struct ConfigureEncoderTask {
615 void operator()() {
Yves Gerey665174f2018-06-19 15:03:05 +0200616 encoder->ConfigureEncoderOnTaskQueue(std::move(config),
617 max_data_payload_length);
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100618 }
619 VideoStreamEncoder* encoder;
620 VideoEncoderConfig config;
621 size_t max_data_payload_length;
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100622 };
Yves Gerey665174f2018-06-19 15:03:05 +0200623 encoder_queue_.PostTask(
624 ConfigureEncoderTask{this, std::move(config), max_data_payload_length});
perkj26091b12016-09-01 01:17:40 -0700625}
626
mflodmancc3d4422017-08-03 08:27:51 -0700627void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
628 VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200629 size_t max_data_payload_length) {
perkj26091b12016-09-01 01:17:40 -0700630 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700631 RTC_DCHECK(sink_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100632 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200633
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000634 pending_encoder_creation_ =
Erik Språngd7329ca2019-02-21 21:19:53 +0100635 (!encoder_ || encoder_config_.video_format != config.video_format ||
636 max_data_payload_length_ != max_data_payload_length);
Pera48ddb72016-09-29 11:48:50 +0200637 encoder_config_ = std::move(config);
Erik Språngd7329ca2019-02-21 21:19:53 +0100638 max_data_payload_length_ = max_data_payload_length;
perkjfa10b552016-10-02 23:45:26 -0700639 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200640
perkjfa10b552016-10-02 23:45:26 -0700641 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100642 // if the frame resolution is known. Otherwise, the reconfiguration is
643 // deferred until the next frame to minimize the number of reconfigurations.
644 // The codec configuration depends on incoming video frame size.
645 if (last_frame_info_) {
646 ReconfigureEncoder();
Erik Språngd7329ca2019-02-21 21:19:53 +0100647 } else {
648 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
649 encoder_config_.video_format);
650 if (HasInternalSource()) {
651 last_frame_info_ = VideoFrameInfo(176, 144, false);
652 ReconfigureEncoder();
653 }
perkjfa10b552016-10-02 23:45:26 -0700654 }
655}
perkj26091b12016-09-01 01:17:40 -0700656
Seth Hampsoncc7125f2018-02-02 08:46:16 -0800657// TODO(bugs.webrtc.org/8807): Currently this always does a hard
658// reconfiguration, but this isn't always necessary. Add in logic to only update
659// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
660// "soft" reconfiguration.
mflodmancc3d4422017-08-03 08:27:51 -0700661void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700662 RTC_DCHECK(pending_encoder_reconfiguration_);
663 std::vector<VideoStream> streams =
664 encoder_config_.video_stream_factory->CreateEncoderStreams(
665 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700666
ilnik6b826ef2017-06-16 06:53:48 -0700667 // TODO(ilnik): If configured resolution is significantly less than provided,
668 // e.g. because there are not enough SSRCs for all simulcast streams,
669 // signal new resolutions via SinkWants to video source.
670
671 // Stream dimensions may be not equal to given because of a simulcast
672 // restrictions.
Steve Antonbd631a02019-03-28 10:51:27 -0700673 auto highest_stream = absl::c_max_element(
674 streams, [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) {
Florent Castelli450b5482018-11-29 17:32:47 +0100675 return std::tie(a.width, a.height) < std::tie(b.width, b.height);
676 });
677 int highest_stream_width = static_cast<int>(highest_stream->width);
678 int highest_stream_height = static_cast<int>(highest_stream->height);
ilnik6b826ef2017-06-16 06:53:48 -0700679 // Dimension may be reduced to be, e.g. divisible by 4.
680 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
681 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
682 crop_width_ = last_frame_info_->width - highest_stream_width;
683 crop_height_ = last_frame_info_->height - highest_stream_height;
684
Erik Språng08127a92016-11-16 16:41:30 +0100685 VideoCodec codec;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800686 if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100687 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100688 }
perkjfa10b552016-10-02 23:45:26 -0700689
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800690 rate_allocator_ =
691 settings_.bitrate_allocator_factory->CreateVideoBitrateAllocator(codec);
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800692
“Michael277a6562018-06-01 14:09:19 -0500693 // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9.
694 if (encoder_config_.codec_type == kVideoCodecVP9) {
“Michael277a6562018-06-01 14:09:19 -0500695 // Lower max bitrate to the level codec actually can produce.
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100696 streams[0].max_bitrate_bps = std::min<int>(
697 streams[0].max_bitrate_bps, SvcRateAllocator::GetMaxBitrateBps(codec));
“Michael277a6562018-06-01 14:09:19 -0500698 streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000;
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100699 // target_bitrate_bps specifies the maximum padding bitrate.
“Michael277a6562018-06-01 14:09:19 -0500700 streams[0].target_bitrate_bps =
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100701 SvcRateAllocator::GetPaddingBitrateBps(codec);
“Michael277a6562018-06-01 14:09:19 -0500702 }
703
perkjfa10b552016-10-02 23:45:26 -0700704 codec.startBitrate =
705 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
706 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
707 codec.expect_encode_from_texture = last_frame_info_->is_texture;
Erik Språngd7329ca2019-02-21 21:19:53 +0100708 // Make sure the start bit rate is sane...
709 RTC_DCHECK_LE(codec.startBitrate, 1000000);
sprangfda496a2017-06-15 04:21:07 -0700710 max_framerate_ = codec.maxFramerate;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200711
712 // Inform source about max configured framerate.
713 int max_framerate = 0;
714 for (const auto& stream : streams) {
715 max_framerate = std::max(stream.max_framerate, max_framerate);
716 }
717 source_proxy_->SetMaxFramerate(max_framerate);
Stefan Holmere5904162015-03-26 11:11:06 +0100718
Erik Språngb7cb7b52019-02-26 15:52:33 +0100719 if (codec.maxBitrate == 0) {
720 // max is one bit per pixel
721 codec.maxBitrate =
722 (static_cast<int>(codec.height) * static_cast<int>(codec.width) *
723 static_cast<int>(codec.maxFramerate)) /
724 1000;
725 if (codec.startBitrate > codec.maxBitrate) {
726 // But if the user tries to set a higher start bit rate we will
727 // increase the max accordingly.
728 codec.maxBitrate = codec.startBitrate;
729 }
730 }
731
732 if (codec.startBitrate > codec.maxBitrate) {
733 codec.startBitrate = codec.maxBitrate;
734 }
735
736 // Reset (release existing encoder) if one exists and anything except
Elad Alon4d6795f2019-05-02 23:25:34 +0200737 // start bitrate or max framerate has changed.
Erik Språngb7cb7b52019-02-26 15:52:33 +0100738 const bool reset_required = RequiresEncoderReset(codec, send_codec_);
739 send_codec_ = codec;
740
Niels Möller4db138e2018-04-19 09:04:13 +0200741 // Keep the same encoder, as long as the video_format is unchanged.
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100742 // Encoder creation block is split in two since EncoderInfo needed to start
743 // CPU adaptation with the correct settings should be polled after
744 // encoder_->InitEncode().
Erik Språngb7cb7b52019-02-26 15:52:33 +0100745 bool success = true;
Erik Språng6a7baa72019-02-26 18:31:00 +0100746 if (pending_encoder_creation_ || reset_required) {
747 ReleaseEncoder();
748 if (pending_encoder_creation_) {
749 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
750 encoder_config_.video_format);
751 // TODO(nisse): What to do if creating the encoder fails? Crash,
752 // or just discard incoming frames?
753 RTC_CHECK(encoder_);
754 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
755 encoder_config_.video_format);
Erik Språngb7cb7b52019-02-26 15:52:33 +0100756 }
Erik Språng6a7baa72019-02-26 18:31:00 +0100757
758 if (encoder_->InitEncode(&send_codec_, number_of_cores_,
759 max_data_payload_length_ > 0
760 ? max_data_payload_length_
761 : kDefaultPayloadSize) != 0) {
762 RTC_LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
763 "codec type: "
764 << CodecTypeToPayloadString(send_codec_.codecType)
765 << " (" << send_codec_.codecType << ")";
766 ReleaseEncoder();
767 success = false;
768 } else {
769 encoder_initialized_ = true;
770 encoder_->RegisterEncodeCompleteCallback(this);
Ilya Nikolaevskiy4fb12b02019-05-02 14:44:29 +0200771 frame_encode_metadata_writer_.OnEncoderInit(send_codec_,
772 HasInternalSource());
Erik Språng6a7baa72019-02-26 18:31:00 +0100773 }
774
Ilya Nikolaevskiy4fb12b02019-05-02 14:44:29 +0200775 frame_encode_metadata_writer_.Reset();
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100776 last_encode_info_ms_ = absl::nullopt;
Erik Språngb7cb7b52019-02-26 15:52:33 +0100777 }
Erik Språngd7329ca2019-02-21 21:19:53 +0100778
779 if (success) {
Erik Språngd7329ca2019-02-21 21:19:53 +0100780 next_frame_types_.clear();
781 next_frame_types_.resize(
782 std::max(static_cast<int>(codec.numberOfSimulcastStreams), 1),
Niels Möller8f7ce222019-03-21 15:43:58 +0100783 VideoFrameType::kVideoFrameKey);
Erik Språngd7329ca2019-02-21 21:19:53 +0100784 RTC_LOG(LS_VERBOSE) << " max bitrate " << codec.maxBitrate
785 << " start bitrate " << codec.startBitrate
786 << " max frame rate " << codec.maxFramerate
787 << " max payload size " << max_data_payload_length_;
788 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100789 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
Erik Språngb7cb7b52019-02-26 15:52:33 +0100790 rate_allocator_ = nullptr;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000791 }
Peter Boström905f8e72016-03-02 16:59:56 +0100792
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100793 if (pending_encoder_creation_) {
794 overuse_detector_->StopCheckForOveruse();
795 overuse_detector_->StartCheckForOveruse(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100796 &encoder_queue_,
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100797 GetCpuOveruseOptions(
798 settings_, encoder_->GetEncoderInfo().is_hardware_accelerated),
799 this);
800 pending_encoder_creation_ = false;
801 }
802
Niels Möller6bb5ab92019-01-11 11:11:10 +0100803 int num_layers;
804 if (codec.codecType == kVideoCodecVP8) {
805 num_layers = codec.VP8()->numberOfTemporalLayers;
806 } else if (codec.codecType == kVideoCodecVP9) {
807 num_layers = codec.VP9()->numberOfTemporalLayers;
Johnny Lee1a1c52b2019-02-08 14:25:40 -0500808 } else if (codec.codecType == kVideoCodecH264) {
809 num_layers = codec.H264()->numberOfTemporalLayers;
Niels Möller6bb5ab92019-01-11 11:11:10 +0100810 } else if (codec.codecType == kVideoCodecGeneric &&
811 codec.numberOfSimulcastStreams > 0) {
812 // This is mainly for unit testing, disabling frame dropping.
813 // TODO(sprang): Add a better way to disable frame dropping.
814 num_layers = codec.simulcastStream[0].numberOfTemporalLayers;
815 } else {
816 num_layers = 1;
817 }
818
819 frame_dropper_.Reset();
820 frame_dropper_.SetRates(codec.startBitrate, max_framerate_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100821 // Force-disable frame dropper if either:
822 // * We have screensharing with layers.
823 // * "WebRTC-FrameDropper" field trial is "Disabled".
824 force_disable_frame_dropper_ =
825 field_trial::IsDisabled(kFrameDropperFieldTrial) ||
826 (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing);
827
Erik Språng7ca375c2019-02-06 16:20:17 +0100828 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
829 if (rate_control_settings_.UseEncoderBitrateAdjuster()) {
830 bitrate_adjuster_ = absl::make_unique<EncoderBitrateAdjuster>(codec);
831 bitrate_adjuster_->OnEncoderInfo(info);
832 }
833
Erik Språng4c6ca302019-04-08 15:14:01 +0200834 if (rate_allocator_ && last_encoder_rate_settings_) {
Niels Möller6bb5ab92019-01-11 11:11:10 +0100835 // We have a new rate allocator instance and already configured target
Erik Språng4c6ca302019-04-08 15:14:01 +0200836 // bitrate. Update the rate allocation and notify observers.
837 last_encoder_rate_settings_->framerate_fps = GetInputFramerateFps();
838 SetEncoderRates(
839 UpdateBitrateAllocationAndNotifyObserver(*last_encoder_rate_settings_));
Niels Möller6bb5ab92019-01-11 11:11:10 +0100840 }
ilnik35b7de42017-03-15 04:24:21 -0700841
Niels Möller213618e2018-07-24 09:29:58 +0200842 encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
Per512ecb32016-09-23 15:52:06 +0200843
perkjfa10b552016-10-02 23:45:26 -0700844 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100845
Pera48ddb72016-09-29 11:48:50 +0200846 sink_->OnEncoderConfigurationChanged(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100847 std::move(streams), encoder_config_.content_type,
848 encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800849
Niels Möller7dc26b72017-12-06 10:27:48 +0100850 // Get the current target framerate, ie the maximum framerate as specified by
851 // the current codec configuration, or any limit imposed by cpu adaption in
852 // maintain-resolution or balanced mode. This is used to make sure overuse
853 // detection doesn't needlessly trigger in low and/or variable framerate
854 // scenarios.
855 int target_framerate = std::min(
856 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
857 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +0200858
Erik Språng7ca375c2019-02-06 16:20:17 +0100859 ConfigureQualityScaler(info);
kthelgason2bc68642017-02-07 07:02:22 -0800860}
861
Erik Språng7ca375c2019-02-06 16:20:17 +0100862void VideoStreamEncoder::ConfigureQualityScaler(
863 const VideoEncoder::EncoderInfo& encoder_info) {
kthelgason2bc68642017-02-07 07:02:22 -0800864 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +0100865 const auto scaling_settings = encoder_info.scaling_settings;
asapersson36e9eb42017-03-31 05:29:12 -0700866 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700867 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +0100868 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -0700869
asapersson36e9eb42017-03-31 05:29:12 -0700870 if (quality_scaling_allowed) {
Benjamin Wright1f4173e2019-03-13 17:59:32 -0700871 if (quality_scaler_ == nullptr) {
asapersson09f05612017-05-15 23:40:18 -0700872 // Quality scaler has not already been configured.
Niels Möller225c7872018-02-22 15:03:53 +0100873
Åsa Perssona945aee2018-04-24 16:53:25 +0200874 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200875 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 16:53:25 +0200876 if (quality_scaling_experiment_enabled_) {
877 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
878 encoder_config_.codec_type);
879 }
Karl Wiberg918f50c2018-07-05 11:40:33 +0200880 // Since the interface is non-public, absl::make_unique can't do this
881 // upcast.
Niels Möller225c7872018-02-22 15:03:53 +0100882 AdaptationObserverInterface* observer = this;
Karl Wiberg918f50c2018-07-05 11:40:33 +0200883 quality_scaler_ = absl::make_unique<QualityScaler>(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100884 &encoder_queue_, observer,
885 experimental_thresholds ? *experimental_thresholds
886 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200887 has_seen_first_significant_bwe_change_ = false;
888 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 01:44:11 -0800889 }
890 } else {
891 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200892 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800893 }
asapersson09f05612017-05-15 23:40:18 -0700894
Niels Möller213618e2018-07-24 09:29:58 +0200895 encoder_stats_observer_->OnAdaptationChanged(
896 VideoStreamEncoderObserver::AdaptationReason::kNone,
897 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000898}
899
mflodmancc3d4422017-08-03 08:27:51 -0700900void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700901 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700902 VideoFrame incoming_frame = video_frame;
903
904 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700905 int64_t current_time_us = clock_->TimeInMicroseconds();
906 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
907 // In some cases, e.g., when the frame from decoder is fed to encoder,
908 // the timestamp may be set to the future. As the encoding pipeline assumes
909 // capture time to be less than present time, we should reset the capture
910 // timestamps here. Otherwise there may be issues with RTP send stream.
911 if (incoming_frame.timestamp_us() > current_time_us)
912 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700913
914 // Capture time may come from clock with an offset and drift from clock_.
915 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800916 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700917 capture_ntp_time_ms = video_frame.ntp_time_ms();
918 } else if (video_frame.render_time_ms() != 0) {
919 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
920 } else {
nisse1c0dea82017-01-30 02:43:18 -0800921 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700922 }
923 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
924
925 // Convert NTP time, in ms, to RTP timestamp.
926 const int kMsToRtpTimestamp = 90;
927 incoming_frame.set_timestamp(
928 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
929
930 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
931 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100932 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
933 << incoming_frame.ntp_time_ms()
934 << " <= " << last_captured_timestamp_
935 << ") for incoming frame. Dropping.";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100936 encoder_queue_.PostTask([this, incoming_frame]() {
937 RTC_DCHECK_RUN_ON(&encoder_queue_);
938 accumulated_update_rect_.Union(incoming_frame.update_rect());
939 });
perkj26091b12016-09-01 01:17:40 -0700940 return;
941 }
942
asapersson6ffb67d2016-09-12 00:10:45 -0700943 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800944 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
945 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700946 log_stats = true;
947 }
948
perkj26091b12016-09-01 01:17:40 -0700949 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200950
951 int64_t post_time_us = rtc::TimeMicros();
952 ++posted_frames_waiting_for_encode_;
953
954 encoder_queue_.PostTask(
955 [this, incoming_frame, post_time_us, log_stats]() {
956 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 09:29:58 +0200957 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
958 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200959 ++captured_frame_count_;
960 const int posted_frames_waiting_for_encode =
961 posted_frames_waiting_for_encode_.fetch_sub(1);
962 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
963 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +0200964 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200965 } else {
966 // There is a newer frame in flight. Do not encode this frame.
967 RTC_LOG(LS_VERBOSE)
968 << "Incoming frame dropped due to that the encoder is blocked.";
969 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 09:29:58 +0200970 encoder_stats_observer_->OnFrameDropped(
971 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100972 accumulated_update_rect_.Union(incoming_frame.update_rect());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200973 }
974 if (log_stats) {
975 RTC_LOG(LS_INFO) << "Number of frames: captured "
976 << captured_frame_count_
977 << ", dropped (due to encoder blocked) "
978 << dropped_frame_count_ << ", interval_ms "
979 << kFrameLogIntervalMs;
980 captured_frame_count_ = 0;
981 dropped_frame_count_ = 0;
982 }
983 });
perkj26091b12016-09-01 01:17:40 -0700984}
985
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200986void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 09:29:58 +0200987 encoder_stats_observer_->OnFrameDropped(
988 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200989}
990
mflodmancc3d4422017-08-03 08:27:51 -0700991bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700992 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000993 // Pause video if paused by caller or as long as the network is down or the
994 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700995 // If the pacer queue has grown too large or the network is down,
Erik Språng4c6ca302019-04-08 15:14:01 +0200996 // |last_encoder_rate_settings_->encoder_target| will be 0.
997 return !last_encoder_rate_settings_ ||
998 last_encoder_rate_settings_->encoder_target == DataRate::Zero();
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000999}
1000
mflodmancc3d4422017-08-03 08:27:51 -07001001void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -07001002 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001003 // Start trace event only on the first frame after encoder is paused.
1004 if (!encoder_paused_and_dropped_frame_) {
1005 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
1006 }
1007 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001008}
1009
mflodmancc3d4422017-08-03 08:27:51 -07001010void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -07001011 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001012 // End trace event on first frame after encoder resumes, if frame was dropped.
1013 if (encoder_paused_and_dropped_frame_) {
1014 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
1015 }
1016 encoder_paused_and_dropped_frame_ = false;
1017}
1018
Erik Språng4c6ca302019-04-08 15:14:01 +02001019VideoStreamEncoder::EncoderRateSettings
1020VideoStreamEncoder::UpdateBitrateAllocationAndNotifyObserver(
1021 const EncoderRateSettings& rate_settings) {
1022 VideoBitrateAllocation new_allocation;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001023 // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
1024 // might cap the bitrate to the min bitrate configured.
Erik Språng4c6ca302019-04-08 15:14:01 +02001025 if (rate_allocator_ && rate_settings.encoder_target > DataRate::Zero()) {
1026 new_allocation = rate_allocator_->GetAllocation(
1027 rate_settings.encoder_target.bps(),
1028 static_cast<uint32_t>(rate_settings.framerate_fps + 0.5));
Niels Möller6bb5ab92019-01-11 11:11:10 +01001029 }
1030
Erik Språng4c6ca302019-04-08 15:14:01 +02001031 if (bitrate_observer_ && new_allocation.get_sum_bps() > 0) {
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001032 if (encoder_ && encoder_initialized_) {
1033 // Avoid too old encoder_info_.
1034 const int64_t kMaxDiffMs = 100;
1035 const bool updated_recently =
1036 (last_encode_info_ms_ && ((clock_->TimeInMilliseconds() -
1037 *last_encode_info_ms_) < kMaxDiffMs));
1038 // Update allocation according to info from encoder.
1039 bitrate_observer_->OnBitrateAllocationUpdated(
1040 UpdateAllocationFromEncoderInfo(
Erik Språng4c6ca302019-04-08 15:14:01 +02001041 new_allocation,
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001042 updated_recently ? encoder_info_ : encoder_->GetEncoderInfo()));
1043 } else {
Erik Språng4c6ca302019-04-08 15:14:01 +02001044 bitrate_observer_->OnBitrateAllocationUpdated(new_allocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001045 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001046 }
1047
Erik Språng3d11e2f2019-04-15 14:48:30 +02001048 EncoderRateSettings new_rate_settings = rate_settings;
1049 new_rate_settings.bitrate = new_allocation;
1050
Erik Språng7ca375c2019-02-06 16:20:17 +01001051 if (bitrate_adjuster_) {
Erik Språng0e1a1f92019-02-18 18:45:13 +01001052 VideoBitrateAllocation adjusted_allocation =
Erik Språng3d11e2f2019-04-15 14:48:30 +02001053 bitrate_adjuster_->AdjustRateAllocation(new_rate_settings);
Erik Språng4c6ca302019-04-08 15:14:01 +02001054 RTC_LOG(LS_VERBOSE) << "Adjusting allocation, fps = "
1055 << rate_settings.framerate_fps << ", from "
1056 << new_allocation.ToString() << ", to "
Erik Språng0e1a1f92019-02-18 18:45:13 +01001057 << adjusted_allocation.ToString();
Erik Språng3d11e2f2019-04-15 14:48:30 +02001058 new_rate_settings.bitrate = adjusted_allocation;
Erik Språng7ca375c2019-02-06 16:20:17 +01001059 }
Erik Språng4c6ca302019-04-08 15:14:01 +02001060
Erik Språng3d11e2f2019-04-15 14:48:30 +02001061 return new_rate_settings;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001062}
1063
1064uint32_t VideoStreamEncoder::GetInputFramerateFps() {
1065 const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
Erik Språngd7329ca2019-02-21 21:19:53 +01001066 absl::optional<uint32_t> input_fps =
1067 input_framerate_.Rate(clock_->TimeInMilliseconds());
1068 if (!input_fps || *input_fps == 0) {
1069 return default_fps;
1070 }
1071 return *input_fps;
1072}
1073
1074void VideoStreamEncoder::SetEncoderRates(
Erik Språng4c6ca302019-04-08 15:14:01 +02001075 const EncoderRateSettings& rate_settings) {
1076 RTC_DCHECK_GT(rate_settings.framerate_fps, 0.0);
1077 const bool settings_changes = !last_encoder_rate_settings_ ||
1078 rate_settings != *last_encoder_rate_settings_;
1079 if (settings_changes) {
1080 last_encoder_rate_settings_ = rate_settings;
1081 }
1082
Erik Språng6a7baa72019-02-26 18:31:00 +01001083 if (!encoder_) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001084 return;
1085 }
1086
1087 // |bitrate_allocation| is 0 it means that the network is down or the send
1088 // pacer is full. We currently only report this if the encoder has an internal
1089 // source. If the encoder does not have an internal source, higher levels
1090 // are expected to not call AddVideoFrame. We do this since its unclear
1091 // how current encoder implementations behave when given a zero target
1092 // bitrate.
1093 // TODO(perkj): Make sure all known encoder implementations handle zero
1094 // target bitrate and remove this check.
Erik Språng4c6ca302019-04-08 15:14:01 +02001095 if (!HasInternalSource() && rate_settings.bitrate.get_sum_bps() == 0) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001096 return;
1097 }
1098
Erik Språng4c6ca302019-04-08 15:14:01 +02001099 if (settings_changes) {
1100 encoder_->SetRates(rate_settings);
Ilya Nikolaevskiy4fb12b02019-05-02 14:44:29 +02001101 frame_encode_metadata_writer_.OnSetRates(
Erik Språng4c6ca302019-04-08 15:14:01 +02001102 rate_settings.bitrate,
1103 static_cast<uint32_t>(rate_settings.framerate_fps + 0.5));
Erik Språng6a7baa72019-02-26 18:31:00 +01001104 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001105}
1106
Sebastian Janssona3177052018-04-10 13:05:49 +02001107void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
1108 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -07001109 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -08001110
Per21d45d22016-10-30 21:37:57 +01001111 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -07001112 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -07001113 video_frame.is_texture() != last_frame_info_->is_texture) {
1114 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +01001115 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
1116 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +01001117 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
1118 << last_frame_info_->width << "x"
1119 << last_frame_info_->height
1120 << ", texture=" << last_frame_info_->is_texture << ".";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001121 // Force full frame update, since resolution has changed.
1122 accumulated_update_rect_ =
1123 VideoFrame::UpdateRect{0, 0, video_frame.width(), video_frame.height()};
perkjfa10b552016-10-02 23:45:26 -07001124 }
1125
Niels Möller4db138e2018-04-19 09:04:13 +02001126 // We have to create then encoder before the frame drop logic,
1127 // because the latter depends on encoder_->GetScalingSettings.
1128 // According to the testcase
1129 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
1130 // from GetScalingSettings should enable or disable the frame drop.
1131
Erik Språnga8d48ab2019-02-08 14:17:40 +01001132 // Update input frame rate before we start using it. If we update it after
Erik Språngd7329ca2019-02-21 21:19:53 +01001133 // any potential frame drop we are going to artificially increase frame sizes.
1134 // Poll the rate before updating, otherwise we risk the rate being estimated
1135 // a little too high at the start of the call when then window is small.
Niels Möller6bb5ab92019-01-11 11:11:10 +01001136 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språngd7329ca2019-02-21 21:19:53 +01001137 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001138
Niels Möller4db138e2018-04-19 09:04:13 +02001139 int64_t now_ms = clock_->TimeInMilliseconds();
1140 if (pending_encoder_reconfiguration_) {
1141 ReconfigureEncoder();
1142 last_parameters_update_ms_.emplace(now_ms);
1143 } else if (!last_parameters_update_ms_ ||
1144 now_ms - *last_parameters_update_ms_ >=
1145 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001146 if (last_encoder_rate_settings_) {
1147 // Clone rate settings before update, so that SetEncoderRates() will
1148 // actually detect the change between the input and
1149 // |last_encoder_rate_setings_|, triggering the call to SetRate() on the
1150 // encoder.
1151 EncoderRateSettings new_rate_settings = *last_encoder_rate_settings_;
1152 new_rate_settings.framerate_fps = static_cast<double>(framerate_fps);
1153 SetEncoderRates(
1154 UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
1155 }
Niels Möller4db138e2018-04-19 09:04:13 +02001156 last_parameters_update_ms_.emplace(now_ms);
1157 }
1158
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001159 // Because pending frame will be dropped in any case, we need to
1160 // remember its updated region.
1161 if (pending_frame_) {
1162 encoder_stats_observer_->OnFrameDropped(
1163 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
1164 accumulated_update_rect_.Union(pending_frame_->update_rect());
1165 }
1166
Sebastian Janssona3177052018-04-10 13:05:49 +02001167 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001168 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 08:49:53 +01001169 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -08001170 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 08:49:53 +01001171 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
Niels Möller213618e2018-07-24 09:29:58 +02001172 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 08:49:53 +01001173 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001174 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001175 // Storing references to a native buffer risks blocking frame capture.
1176 if (video_frame.video_frame_buffer()->type() !=
1177 VideoFrameBuffer::Type::kNative) {
1178 pending_frame_ = video_frame;
1179 pending_frame_post_time_us_ = time_when_posted_us;
1180 } else {
1181 // Ensure that any previously stored frame is dropped.
1182 pending_frame_.reset();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001183 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001184 }
kthelgason2bc68642017-02-07 07:02:22 -08001185 return;
1186 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001187 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -08001188
perkj26091b12016-09-01 01:17:40 -07001189 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001190 // Storing references to a native buffer risks blocking frame capture.
1191 if (video_frame.video_frame_buffer()->type() !=
1192 VideoFrameBuffer::Type::kNative) {
1193 if (pending_frame_)
1194 TraceFrameDropStart();
1195 pending_frame_ = video_frame;
1196 pending_frame_post_time_us_ = time_when_posted_us;
1197 } else {
1198 // Ensure that any previously stored frame is dropped.
1199 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +02001200 TraceFrameDropStart();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001201 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001202 }
perkj26091b12016-09-01 01:17:40 -07001203 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001204 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001205
1206 pending_frame_.reset();
Niels Möller6bb5ab92019-01-11 11:11:10 +01001207
1208 frame_dropper_.Leak(framerate_fps);
1209 // Frame dropping is enabled iff frame dropping is not force-disabled, and
1210 // rate controller is not trusted.
1211 const bool frame_dropping_enabled =
1212 !force_disable_frame_dropper_ &&
1213 !encoder_info_.has_trusted_rate_controller;
1214 frame_dropper_.Enable(frame_dropping_enabled);
1215 if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001216 RTC_LOG(LS_VERBOSE)
1217 << "Drop Frame: "
1218 << "target bitrate "
1219 << (last_encoder_rate_settings_
1220 ? last_encoder_rate_settings_->encoder_target.bps()
1221 : 0)
1222 << ", input frame rate " << framerate_fps;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001223 OnDroppedFrame(
1224 EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001225 accumulated_update_rect_.Union(video_frame.update_rect());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001226 return;
1227 }
1228
Sebastian Janssona3177052018-04-10 13:05:49 +02001229 EncodeVideoFrame(video_frame, time_when_posted_us);
1230}
1231
1232void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
1233 int64_t time_when_posted_us) {
1234 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -07001235 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +00001236
ilnik6b826ef2017-06-16 06:53:48 -07001237 VideoFrame out_frame(video_frame);
1238 // Crop frame if needed.
1239 if (crop_width_ > 0 || crop_height_ > 0) {
1240 int cropped_width = video_frame.width() - crop_width_;
1241 int cropped_height = video_frame.height() - crop_height_;
1242 rtc::scoped_refptr<I420Buffer> cropped_buffer =
1243 I420Buffer::Create(cropped_width, cropped_height);
1244 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
1245 // happen after SinkWants signaled correctly from ReconfigureEncoder.
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001246 VideoFrame::UpdateRect update_rect = video_frame.update_rect();
ilnik6b826ef2017-06-16 06:53:48 -07001247 if (crop_width_ < 4 && crop_height_ < 4) {
1248 cropped_buffer->CropAndScaleFrom(
1249 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
1250 crop_height_ / 2, cropped_width, cropped_height);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001251 update_rect.offset_x -= crop_width_ / 2;
1252 update_rect.offset_y -= crop_height_ / 2;
1253 update_rect.Intersect(
1254 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height});
1255
ilnik6b826ef2017-06-16 06:53:48 -07001256 } else {
1257 cropped_buffer->ScaleFrom(
1258 *video_frame.video_frame_buffer()->ToI420().get());
Ilya Nikolaevskiy1c90cab2019-03-07 15:30:58 +01001259 if (!update_rect.IsEmpty()) {
1260 // Since we can't reason about pixels after scaling, we invalidate whole
1261 // picture, if anything changed.
1262 update_rect =
1263 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height};
1264 }
ilnik6b826ef2017-06-16 06:53:48 -07001265 }
Artem Titov1ebfb6a2019-01-03 23:49:37 +01001266 out_frame = VideoFrame::Builder()
1267 .set_video_frame_buffer(cropped_buffer)
1268 .set_timestamp_rtp(video_frame.timestamp())
1269 .set_timestamp_ms(video_frame.render_time_ms())
1270 .set_rotation(video_frame.rotation())
1271 .set_id(video_frame.id())
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001272 .set_update_rect(update_rect)
Artem Titov1ebfb6a2019-01-03 23:49:37 +01001273 .build();
ilnik6b826ef2017-06-16 06:53:48 -07001274 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001275 // Since accumulated_update_rect_ is constructed before cropping,
1276 // we can't trust it. If any changes were pending, we invalidate whole
1277 // frame here.
1278 if (!accumulated_update_rect_.IsEmpty()) {
1279 accumulated_update_rect_ =
1280 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1281 }
1282 }
1283
1284 if (!accumulated_update_rect_.IsEmpty()) {
1285 accumulated_update_rect_.Union(out_frame.update_rect());
1286 accumulated_update_rect_.Intersect(
1287 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()});
1288 out_frame.set_update_rect(accumulated_update_rect_);
1289 accumulated_update_rect_.MakeEmptyUpdate();
ilnik6b826ef2017-06-16 06:53:48 -07001290 }
1291
Magnus Jedvert26679d62015-04-07 14:07:41 +02001292 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +00001293 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +00001294
Niels Möller7dc26b72017-12-06 10:27:48 +01001295 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -07001296
Erik Språnge2fd86a2018-10-24 11:32:39 +02001297 // Encoder metadata needs to be updated before encode complete callback.
1298 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
1299 if (info.implementation_name != encoder_info_.implementation_name) {
1300 encoder_stats_observer_->OnEncoderImplementationChanged(
1301 info.implementation_name);
Erik Språng7ca375c2019-02-06 16:20:17 +01001302 if (bitrate_adjuster_) {
1303 // Encoder implementation changed, reset overshoot detector states.
1304 bitrate_adjuster_->Reset();
1305 }
Erik Språnge2fd86a2018-10-24 11:32:39 +02001306 }
Erik Språng7ca375c2019-02-06 16:20:17 +01001307
1308 if (bitrate_adjuster_) {
1309 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1310 if (info.fps_allocation[si] != encoder_info_.fps_allocation[si]) {
1311 bitrate_adjuster_->OnEncoderInfo(info);
1312 break;
1313 }
1314 }
1315 }
1316
Erik Språnge2fd86a2018-10-24 11:32:39 +02001317 encoder_info_ = info;
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001318 last_encode_info_ms_ = clock_->TimeInMilliseconds();
Erik Språngb7cb7b52019-02-26 15:52:33 +01001319 RTC_DCHECK_EQ(send_codec_.width, out_frame.width());
1320 RTC_DCHECK_EQ(send_codec_.height, out_frame.height());
Erik Språngd7329ca2019-02-21 21:19:53 +01001321 const VideoFrameBuffer::Type buffer_type =
1322 out_frame.video_frame_buffer()->type();
1323 const bool is_buffer_type_supported =
1324 buffer_type == VideoFrameBuffer::Type::kI420 ||
1325 (buffer_type == VideoFrameBuffer::Type::kNative &&
Erik Språng6a7baa72019-02-26 18:31:00 +01001326 info.supports_native_handle);
Erik Språngd7329ca2019-02-21 21:19:53 +01001327
1328 if (!is_buffer_type_supported) {
1329 // This module only supports software encoding.
1330 rtc::scoped_refptr<I420BufferInterface> converted_buffer(
1331 out_frame.video_frame_buffer()->ToI420());
1332
1333 if (!converted_buffer) {
1334 RTC_LOG(LS_ERROR) << "Frame conversion failed, dropping frame.";
1335 return;
1336 }
1337
Ilya Nikolaevskiycfff6522019-05-03 14:34:35 +02001338 VideoFrame::UpdateRect update_rect = out_frame.update_rect();
1339 if (!update_rect.IsEmpty() &&
1340 out_frame.video_frame_buffer()->GetI420() == nullptr) {
1341 // UpdatedRect is reset to full update if it's not empty, and buffer was
1342 // converted, therefore we can't guarantee that pixels outside of
1343 // UpdateRect didn't change comparing to the previous frame.
1344 update_rect =
1345 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1346 }
Ilya Nikolaevskiy1c90cab2019-03-07 15:30:58 +01001347
Erik Språngd7329ca2019-02-21 21:19:53 +01001348 out_frame = VideoFrame::Builder()
1349 .set_video_frame_buffer(converted_buffer)
1350 .set_timestamp_rtp(out_frame.timestamp())
1351 .set_timestamp_ms(out_frame.render_time_ms())
1352 .set_rotation(out_frame.rotation())
1353 .set_id(out_frame.id())
Ilya Nikolaevskiy1c90cab2019-03-07 15:30:58 +01001354 .set_update_rect(update_rect)
Erik Språngd7329ca2019-02-21 21:19:53 +01001355 .build();
1356 }
Erik Språng6a7baa72019-02-26 18:31:00 +01001357
1358 TRACE_EVENT1("webrtc", "VCMGenericEncoder::Encode", "timestamp",
1359 out_frame.timestamp());
1360
Ilya Nikolaevskiy4fb12b02019-05-02 14:44:29 +02001361 frame_encode_metadata_writer_.OnEncodeStarted(out_frame);
Erik Språng6a7baa72019-02-26 18:31:00 +01001362
Niels Möllerc8d2e732019-03-06 12:00:33 +01001363 const int32_t encode_status = encoder_->Encode(out_frame, &next_frame_types_);
Erik Språng6a7baa72019-02-26 18:31:00 +01001364
Erik Språngd7329ca2019-02-21 21:19:53 +01001365 if (encode_status < 0) {
1366 RTC_LOG(LS_ERROR) << "Failed to encode frame. Error code: "
1367 << encode_status;
1368 return;
1369 }
1370
1371 for (auto& it : next_frame_types_) {
Niels Möller8f7ce222019-03-21 15:43:58 +01001372 it = VideoFrameType::kVideoFrameDelta;
Erik Språngd7329ca2019-02-21 21:19:53 +01001373 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001374}
niklase@google.com470e71d2011-07-07 08:21:25 +00001375
mflodmancc3d4422017-08-03 08:27:51 -07001376void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -07001377 if (!encoder_queue_.IsCurrent()) {
1378 encoder_queue_.PostTask([this] { SendKeyFrame(); });
1379 return;
1380 }
1381 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +01001382 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Erik Språngd7329ca2019-02-21 21:19:53 +01001383 RTC_DCHECK(!next_frame_types_.empty());
Niels Möller8f7ce222019-03-21 15:43:58 +01001384 next_frame_types_[0] = VideoFrameType::kVideoFrameKey;
Erik Språngd7329ca2019-02-21 21:19:53 +01001385 if (HasInternalSource()) {
1386 // Try to request the frame if we have an external encoder with
1387 // internal source since AddVideoFrame never will be called.
Erik Språng6a7baa72019-02-26 18:31:00 +01001388
1389 // TODO(nisse): Used only with internal source. Delete as soon as
1390 // that feature is removed. The only implementation I've been able
1391 // to find ignores what's in the frame. With one exception: It seems
1392 // a few test cases, e.g.,
1393 // VideoSendStreamTest.VideoSendStreamStopSetEncoderRateToZero, set
1394 // internal_source to true and use FakeEncoder. And the latter will
1395 // happily encode this 1x1 frame and pass it on down the pipeline.
1396 if (encoder_->Encode(VideoFrame::Builder()
1397 .set_video_frame_buffer(I420Buffer::Create(1, 1))
1398 .set_rotation(kVideoRotation_0)
1399 .set_timestamp_us(0)
1400 .build(),
Erik Språng6a7baa72019-02-26 18:31:00 +01001401 &next_frame_types_) == WEBRTC_VIDEO_CODEC_OK) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001402 // Try to remove just-performed keyframe request, if stream still exists.
Niels Möller8f7ce222019-03-21 15:43:58 +01001403 next_frame_types_[0] = VideoFrameType::kVideoFrameDelta;
Erik Språngd7329ca2019-02-21 21:19:53 +01001404 }
1405 }
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00001406}
1407
Elad Alonb6ef99b2019-04-10 16:37:07 +02001408void VideoStreamEncoder::OnLossNotification(
1409 const VideoEncoder::LossNotification& loss_notification) {
1410 if (!encoder_queue_.IsCurrent()) {
1411 encoder_queue_.PostTask(
1412 [this, loss_notification] { OnLossNotification(loss_notification); });
1413 return;
1414 }
1415
1416 RTC_DCHECK_RUN_ON(&encoder_queue_);
1417 if (encoder_) {
1418 encoder_->OnLossNotification(loss_notification);
1419 }
1420}
1421
mflodmancc3d4422017-08-03 08:27:51 -07001422EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001423 const EncodedImage& encoded_image,
1424 const CodecSpecificInfo* codec_specific_info,
1425 const RTPFragmentationHeader* fragmentation) {
Erik Språng6a7baa72019-02-26 18:31:00 +01001426 TRACE_EVENT_INSTANT1("webrtc", "VCMEncodedFrameCallback::Encoded",
1427 "timestamp", encoded_image.Timestamp());
1428 const size_t spatial_idx = encoded_image.SpatialIndex().value_or(0);
1429 EncodedImage image_copy(encoded_image);
1430
Ilya Nikolaevskiy4fb12b02019-05-02 14:44:29 +02001431 frame_encode_metadata_writer_.FillTimingInfo(spatial_idx, &image_copy);
Erik Språng6a7baa72019-02-26 18:31:00 +01001432
1433 // Piggyback ALR experiment group id and simulcast id into the content type.
1434 const uint8_t experiment_id =
1435 experiment_groups_[videocontenttypehelpers::IsScreenshare(
1436 image_copy.content_type_)];
1437
1438 // TODO(ilnik): This will force content type extension to be present even
1439 // for realtime video. At the expense of miniscule overhead we will get
1440 // sliced receive statistics.
1441 RTC_CHECK(videocontenttypehelpers::SetExperimentId(&image_copy.content_type_,
1442 experiment_id));
1443 // We count simulcast streams from 1 on the wire. That's why we set simulcast
1444 // id in content type to +1 of that is actual simulcast index. This is because
1445 // value 0 on the wire is reserved for 'no simulcast stream specified'.
1446 RTC_CHECK(videocontenttypehelpers::SetSimulcastId(
1447 &image_copy.content_type_, static_cast<uint8_t>(spatial_idx + 1)));
1448
perkj26091b12016-09-01 01:17:40 -07001449 // Encoded is called on whatever thread the real encoder implementation run
1450 // on. In the case of hardware encoders, there might be several encoders
1451 // running in parallel on different threads.
Erik Språng6a7baa72019-02-26 18:31:00 +01001452 encoder_stats_observer_->OnSendEncodedImage(image_copy, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -07001453
philipelda5aa4d2019-04-26 13:37:37 +02001454 // The simulcast id is signaled in the SpatialIndex. This makes it impossible
1455 // to do simulcast for codecs that actually support spatial layers since we
1456 // can't distinguish between an actual spatial layer and a simulcast stream.
1457 // TODO(bugs.webrtc.org/10520): Signal the simulcast id explicitly.
1458 int simulcast_id = 0;
1459 if (codec_specific_info &&
1460 (codec_specific_info->codecType == kVideoCodecVP8 ||
1461 codec_specific_info->codecType == kVideoCodecH264 ||
1462 codec_specific_info->codecType == kVideoCodecGeneric)) {
1463 simulcast_id = encoded_image.SpatialIndex().value_or(0);
1464 }
1465
1466 std::unique_ptr<CodecSpecificInfo> codec_info_copy;
1467 {
1468 rtc::CritScope cs(&encoded_image_lock_);
1469
1470 if (codec_specific_info && codec_specific_info->generic_frame_info) {
1471 codec_info_copy =
1472 absl::make_unique<CodecSpecificInfo>(*codec_specific_info);
1473 GenericFrameInfo& generic_info = *codec_info_copy->generic_frame_info;
1474 generic_info.frame_id = next_frame_id_++;
1475
1476 if (encoder_buffer_state_.size() <= static_cast<size_t>(simulcast_id)) {
1477 RTC_LOG(LS_ERROR) << "At most " << encoder_buffer_state_.size()
1478 << " simulcast streams supported.";
1479 } else {
1480 std::array<int64_t, kMaxEncoderBuffers>& state =
1481 encoder_buffer_state_[simulcast_id];
1482 for (const CodecBufferUsage& buffer : generic_info.encoder_buffers) {
1483 if (state.size() <= static_cast<size_t>(buffer.id)) {
1484 RTC_LOG(LS_ERROR)
1485 << "At most " << state.size() << " encoder buffers supported.";
1486 break;
1487 }
1488
1489 if (buffer.referenced) {
1490 int64_t diff = generic_info.frame_id - state[buffer.id];
1491 if (diff <= 0) {
1492 RTC_LOG(LS_ERROR) << "Invalid frame diff: " << diff << ".";
1493 } else if (absl::c_find(generic_info.frame_diffs, diff) ==
1494 generic_info.frame_diffs.end()) {
1495 generic_info.frame_diffs.push_back(diff);
1496 }
1497 }
1498
1499 if (buffer.updated)
1500 state[buffer.id] = generic_info.frame_id;
1501 }
1502 }
1503 }
1504 }
1505
1506 EncodedImageCallback::Result result = sink_->OnEncodedImage(
1507 image_copy, codec_info_copy ? codec_info_copy.get() : codec_specific_info,
1508 fragmentation);
perkjbc75d972016-05-02 06:31:25 -07001509
Erik Språng7ca375c2019-02-06 16:20:17 +01001510 // We are only interested in propagating the meta-data about the image, not
1511 // encoded data itself, to the post encode function. Since we cannot be sure
1512 // the pointer will still be valid when run on the task queue, set it to null.
Erik Språng6a7baa72019-02-26 18:31:00 +01001513 image_copy.set_buffer(nullptr, 0);
Niels Möller83dbeac2017-12-14 16:39:44 +01001514
Erik Språng7ca375c2019-02-06 16:20:17 +01001515 int temporal_index = 0;
1516 if (codec_specific_info) {
1517 if (codec_specific_info->codecType == kVideoCodecVP9) {
1518 temporal_index = codec_specific_info->codecSpecific.VP9.temporal_idx;
1519 } else if (codec_specific_info->codecType == kVideoCodecVP8) {
1520 temporal_index = codec_specific_info->codecSpecific.VP8.temporalIdx;
1521 }
1522 }
1523 if (temporal_index == kNoTemporalIdx) {
1524 temporal_index = 0;
Niels Möller83dbeac2017-12-14 16:39:44 +01001525 }
1526
Erik Språng982dc792019-03-13 16:33:02 +01001527 RunPostEncode(image_copy, rtc::TimeMicros(), temporal_index);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001528
1529 if (result.error == Result::OK) {
1530 // In case of an internal encoder running on a separate thread, the
1531 // decision to drop a frame might be a frame late and signaled via
1532 // atomic flag. This is because we can't easily wait for the worker thread
1533 // without risking deadlocks, eg during shutdown when the worker thread
1534 // might be waiting for the internal encoder threads to stop.
1535 if (pending_frame_drops_.load() > 0) {
1536 int pending_drops = pending_frame_drops_.fetch_sub(1);
1537 RTC_DCHECK_GT(pending_drops, 0);
1538 result.drop_next_frame = true;
1539 }
1540 }
perkj803d97f2016-11-01 11:45:46 -07001541
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001542 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001543}
1544
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001545void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
1546 switch (reason) {
1547 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 09:29:58 +02001548 encoder_stats_observer_->OnFrameDropped(
1549 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001550 encoder_queue_.PostTask([this] {
1551 RTC_DCHECK_RUN_ON(&encoder_queue_);
1552 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +02001553 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001554 });
1555 break;
1556 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 09:29:58 +02001557 encoder_stats_observer_->OnFrameDropped(
1558 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 16:53:25 +02001559 encoder_queue_.PostTask([this] {
1560 RTC_DCHECK_RUN_ON(&encoder_queue_);
1561 if (quality_scaler_)
1562 quality_scaler_->ReportDroppedFrameByEncoder();
1563 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001564 break;
1565 }
kthelgason876222f2016-11-29 01:44:11 -08001566}
1567
Erik Språng610c7632019-03-06 15:37:33 +01001568void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate,
Erik Språng4c6ca302019-04-08 15:14:01 +02001569 DataRate link_allocation,
mflodmancc3d4422017-08-03 08:27:51 -07001570 uint8_t fraction_lost,
1571 int64_t round_trip_time_ms) {
Sebastian Jansson5a000162019-04-12 11:21:32 +02001572 RTC_DCHECK_GE(link_allocation, target_bitrate);
perkj26091b12016-09-01 01:17:40 -07001573 if (!encoder_queue_.IsCurrent()) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001574 encoder_queue_.PostTask([this, target_bitrate, link_allocation,
Erik Språng610c7632019-03-06 15:37:33 +01001575 fraction_lost, round_trip_time_ms] {
Erik Språng4c6ca302019-04-08 15:14:01 +02001576 OnBitrateUpdated(target_bitrate, link_allocation, fraction_lost,
Erik Språng610c7632019-03-06 15:37:33 +01001577 round_trip_time_ms);
1578 });
perkj26091b12016-09-01 01:17:40 -07001579 return;
1580 }
1581 RTC_DCHECK_RUN_ON(&encoder_queue_);
1582 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
1583
Erik Språng610c7632019-03-06 15:37:33 +01001584 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << target_bitrate.bps()
Erik Språng4c6ca302019-04-08 15:14:01 +02001585 << " link allocation bitrate = " << link_allocation.bps()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001586 << " packet loss " << static_cast<int>(fraction_lost)
1587 << " rtt " << round_trip_time_ms;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001588 // On significant changes to BWE at the start of the call,
1589 // enable frame drops to quickly react to jumps in available bandwidth.
1590 if (encoder_start_bitrate_bps_ != 0 &&
1591 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
1592 initial_framedrop_on_bwe_enabled_ &&
Erik Språng610c7632019-03-06 15:37:33 +01001593 abs_diff(target_bitrate.bps(), encoder_start_bitrate_bps_) >=
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001594 kFramedropThreshold * encoder_start_bitrate_bps_) {
1595 // Reset initial framedrop feature when first real BW estimate arrives.
1596 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
1597 // without an actual BW estimate.
1598 initial_framedrop_ = 0;
1599 has_seen_first_significant_bwe_change_ = true;
1600 }
perkj26091b12016-09-01 01:17:40 -07001601
Elad Aloncde8ab22019-03-20 11:56:20 +01001602 if (encoder_) {
1603 encoder_->OnPacketLossRateUpdate(static_cast<float>(fraction_lost) / 256.f);
1604 encoder_->OnRttUpdate(round_trip_time_ms);
1605 }
1606
Niels Möller6bb5ab92019-01-11 11:11:10 +01001607 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språng610c7632019-03-06 15:37:33 +01001608 frame_dropper_.SetRates((target_bitrate.bps() + 500) / 1000, framerate_fps);
Erik Språng4c6ca302019-04-08 15:14:01 +02001609 const bool video_is_suspended = target_bitrate == DataRate::Zero();
1610 const bool video_suspension_changed = video_is_suspended != EncoderPaused();
1611
1612 EncoderRateSettings new_rate_settings{VideoBitrateAllocation(),
1613 static_cast<double>(framerate_fps),
1614 link_allocation, target_bitrate};
1615 SetEncoderRates(UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
perkj26091b12016-09-01 01:17:40 -07001616
Erik Språng610c7632019-03-06 15:37:33 +01001617 encoder_start_bitrate_bps_ = target_bitrate.bps() != 0
1618 ? target_bitrate.bps()
1619 : encoder_start_bitrate_bps_;
Peter Boströmd153a372015-11-10 15:27:12 +00001620
sprang552c7c72017-02-13 04:41:45 -08001621 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001622 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
1623 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 09:29:58 +02001624 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +02001625 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001626 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
1627 !DropDueToSize(pending_frame_->size())) {
1628 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
1629 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
1630 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
1631 pending_frame_.reset();
1632 }
1633}
1634
1635bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001636 if (initial_framedrop_ < kMaxInitialFramedrop &&
Sebastian Janssona3177052018-04-10 13:05:49 +02001637 encoder_start_bitrate_bps_ > 0) {
1638 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
1639 return pixel_count > 320 * 240;
1640 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
1641 return pixel_count > 640 * 480;
1642 }
1643 }
1644 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001645}
1646
mflodmancc3d4422017-08-03 08:27:51 -07001647void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001648 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -07001649 AdaptationRequest adaptation_request = {
1650 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001651 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001652 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -07001653
sprangc5d62e22017-04-02 23:53:04 -07001654 bool downgrade_requested =
1655 last_adaptation_request_ &&
1656 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1657
sprangc5d62e22017-04-02 23:53:04 -07001658 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001659 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-13 23:25:22 -07001660 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001661 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-02 23:53:04 -07001662 if (downgrade_requested &&
1663 adaptation_request.input_pixel_count_ >=
1664 last_adaptation_request_->input_pixel_count_) {
1665 // Don't request lower resolution if the current resolution is not
1666 // lower than the last time we asked for the resolution to be lowered.
1667 return;
1668 }
1669 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001670 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-02 23:53:04 -07001671 if (adaptation_request.framerate_fps_ <= 0 ||
1672 (downgrade_requested &&
1673 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1674 // If no input fps estimate available, can't determine how to scale down
1675 // framerate. Otherwise, don't request lower framerate if we don't have
1676 // a valid frame rate. Since framerate, unlike resolution, is a measure
1677 // we have to estimate, and can fluctuate naturally over time, don't
1678 // make the same kind of limitations as for resolution, but trust the
1679 // overuse detector to not trigger too often.
1680 return;
1681 }
1682 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001683 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001684 return;
sprang84a37592017-02-10 07:04:27 -08001685 }
sprangc5d62e22017-04-02 23:53:04 -07001686
sprangc5d62e22017-04-02 23:53:04 -07001687 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001688 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001689 // Try scale down framerate, if lower.
1690 int fps = MinFps(last_frame_info_->pixel_count());
1691 if (source_proxy_->RestrictFramerate(fps)) {
1692 GetAdaptCounter().IncrementFramerate(reason);
1693 break;
1694 }
1695 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001696 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001697 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001698 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001699 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001700 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07001701 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07001702 adaptation_request.input_pixel_count_,
Erik Språnge2fd86a2018-10-24 11:32:39 +02001703 encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001704 &min_pixels_reached)) {
1705 if (min_pixels_reached)
Niels Möller213618e2018-07-24 09:29:58 +02001706 encoder_stats_observer_->OnMinPixelLimitReached();
asaperssond0de2952017-04-21 01:47:31 -07001707 return;
1708 }
asaperssonf7e294d2017-06-13 23:25:22 -07001709 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001710 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001711 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001712 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001713 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001714 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1715 adaptation_request.framerate_fps_);
1716 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -07001717 return;
sprangfda496a2017-06-15 04:21:07 -07001718 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001719 overuse_detector_->OnTargetFramerateUpdated(
1720 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001721 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001722 break;
sprangfda496a2017-06-15 04:21:07 -07001723 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001724 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001725 RTC_NOTREACHED();
1726 }
1727
asaperssond0de2952017-04-21 01:47:31 -07001728 last_adaptation_request_.emplace(adaptation_request);
1729
asapersson09f05612017-05-15 23:40:18 -07001730 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001731
Mirko Bonadei675513b2017-11-09 11:09:25 +01001732 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -07001733}
1734
mflodmancc3d4422017-08-03 08:27:51 -07001735void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001736 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001737
1738 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1739 int num_downgrades = adapt_counter.TotalCount(reason);
1740 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001741 return;
asapersson09f05612017-05-15 23:40:18 -07001742 RTC_DCHECK_GT(num_downgrades, 0);
1743
sprangc5d62e22017-04-02 23:53:04 -07001744 AdaptationRequest adaptation_request = {
1745 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001746 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001747 AdaptationRequest::Mode::kAdaptUp};
1748
1749 bool adapt_up_requested =
1750 last_adaptation_request_ &&
1751 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001752
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001753 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-13 23:25:22 -07001754 if (adapt_up_requested &&
1755 adaptation_request.input_pixel_count_ <=
1756 last_adaptation_request_->input_pixel_count_) {
1757 // Don't request higher resolution if the current resolution is not
1758 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001759 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001760 }
sprangb1ca0732017-02-01 08:38:12 -08001761 }
sprangc5d62e22017-04-02 23:53:04 -07001762
sprangc5d62e22017-04-02 23:53:04 -07001763 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001764 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001765 // Try scale up framerate, if higher.
1766 int fps = MaxFps(last_frame_info_->pixel_count());
1767 if (source_proxy_->IncreaseFramerate(fps)) {
1768 GetAdaptCounter().DecrementFramerate(reason, fps);
1769 // Reset framerate in case of fewer fps steps down than up.
1770 if (adapt_counter.FramerateCount() == 0 &&
1771 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001772 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001773 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1774 }
1775 break;
1776 }
1777 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001778 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001779 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001780 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001781 // Scale up resolution.
1782 int pixel_count = adaptation_request.input_pixel_count_;
1783 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001784 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001785 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001786 }
asapersson13874762017-06-07 00:01:02 -07001787 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1788 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001789 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001790 break;
asapersson13874762017-06-07 00:01:02 -07001791 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001792 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001793 // Scale up framerate.
1794 int fps = adaptation_request.framerate_fps_;
1795 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001796 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001797 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001798 }
sprangfda496a2017-06-15 04:21:07 -07001799
1800 const int requested_framerate =
1801 source_proxy_->RequestHigherFramerateThan(fps);
1802 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001803 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001804 return;
sprangfda496a2017-06-15 04:21:07 -07001805 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001806 overuse_detector_->OnTargetFramerateUpdated(
1807 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001808 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001809 break;
asapersson13874762017-06-07 00:01:02 -07001810 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001811 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-13 23:25:22 -07001812 return;
sprangc5d62e22017-04-02 23:53:04 -07001813 }
1814
asaperssond0de2952017-04-21 01:47:31 -07001815 last_adaptation_request_.emplace(adaptation_request);
1816
asapersson09f05612017-05-15 23:40:18 -07001817 UpdateAdaptationStats(reason);
1818
Mirko Bonadei675513b2017-11-09 11:09:25 +01001819 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001820}
1821
Niels Möller213618e2018-07-24 09:29:58 +02001822// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 08:27:51 -07001823void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001824 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001825 case kCpu:
Niels Möller213618e2018-07-24 09:29:58 +02001826 encoder_stats_observer_->OnAdaptationChanged(
1827 VideoStreamEncoderObserver::AdaptationReason::kCpu,
1828 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-15 23:40:18 -07001829 break;
1830 case kQuality:
Niels Möller213618e2018-07-24 09:29:58 +02001831 encoder_stats_observer_->OnAdaptationChanged(
1832 VideoStreamEncoderObserver::AdaptationReason::kQuality,
1833 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001834 break;
1835 }
perkj26091b12016-09-01 01:17:40 -07001836}
1837
Niels Möller213618e2018-07-24 09:29:58 +02001838VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 08:27:51 -07001839 AdaptReason reason) {
Niels Möller213618e2018-07-24 09:29:58 +02001840 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 08:27:51 -07001841 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001842 switch (reason) {
1843 case kCpu:
1844 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001845 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001846 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001847 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001848 break;
1849 case kQuality:
1850 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1851 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001852 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001853 }
1854 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1855 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001856 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001857 }
1858 break;
sprangc5d62e22017-04-02 23:53:04 -07001859 }
asapersson09f05612017-05-15 23:40:18 -07001860 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001861}
1862
mflodmancc3d4422017-08-03 08:27:51 -07001863VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001864 return adapt_counters_[degradation_preference_];
1865}
1866
mflodmancc3d4422017-08-03 08:27:51 -07001867const VideoStreamEncoder::AdaptCounter&
1868VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001869 return adapt_counters_[degradation_preference_];
1870}
1871
Erik Språng7ca375c2019-02-06 16:20:17 +01001872void VideoStreamEncoder::RunPostEncode(EncodedImage encoded_image,
Niels Möller6bb5ab92019-01-11 11:11:10 +01001873 int64_t time_sent_us,
Erik Språng7ca375c2019-02-06 16:20:17 +01001874 int temporal_index) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01001875 if (!encoder_queue_.IsCurrent()) {
Erik Språng7ca375c2019-02-06 16:20:17 +01001876 encoder_queue_.PostTask(
1877 [this, encoded_image, time_sent_us, temporal_index] {
1878 RunPostEncode(encoded_image, time_sent_us, temporal_index);
1879 });
Niels Möller6bb5ab92019-01-11 11:11:10 +01001880 return;
1881 }
1882
1883 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +01001884
1885 absl::optional<int> encode_duration_us;
1886 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
1887 encode_duration_us =
1888 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
1889 rtc::kNumMicrosecsPerMillisec *
1890 (encoded_image.timing_.encode_finish_ms -
1891 encoded_image.timing_.encode_start_ms);
1892 }
1893
1894 // Run post encode tasks, such as overuse detection and frame rate/drop
1895 // stats for internal encoders.
1896 const size_t frame_size = encoded_image.size();
Niels Möller87e2d782019-03-07 10:18:23 +01001897 const bool keyframe =
1898 encoded_image._frameType == VideoFrameType::kVideoFrameKey;
Erik Språng7ca375c2019-02-06 16:20:17 +01001899
1900 if (frame_size > 0) {
1901 frame_dropper_.Fill(frame_size, !keyframe);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001902 }
1903
Erik Språngd7329ca2019-02-21 21:19:53 +01001904 if (HasInternalSource()) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01001905 // Update frame dropper after the fact for internal sources.
1906 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
1907 frame_dropper_.Leak(GetInputFramerateFps());
1908 // Signal to encoder to drop next frame.
1909 if (frame_dropper_.DropFrame()) {
1910 pending_frame_drops_.fetch_add(1);
1911 }
1912 }
1913
Erik Språng7ca375c2019-02-06 16:20:17 +01001914 overuse_detector_->FrameSent(
1915 encoded_image.Timestamp(), time_sent_us,
1916 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec,
1917 encode_duration_us);
1918 if (quality_scaler_ && encoded_image.qp_ >= 0)
Sebastian Janssonb6789402019-03-01 15:40:49 +01001919 quality_scaler_->ReportQp(encoded_image.qp_, time_sent_us);
Erik Språng7ca375c2019-02-06 16:20:17 +01001920 if (bitrate_adjuster_) {
1921 bitrate_adjuster_->OnEncodedFrame(encoded_image, temporal_index);
1922 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001923}
1924
Erik Språngd7329ca2019-02-21 21:19:53 +01001925bool VideoStreamEncoder::HasInternalSource() const {
1926 // TODO(sprang): Checking both info from encoder and from encoder factory
1927 // until we have deprecated and removed the encoder factory info.
1928 return codec_info_.has_internal_source || encoder_info_.has_internal_source;
1929}
1930
Erik Språng6a7baa72019-02-26 18:31:00 +01001931void VideoStreamEncoder::ReleaseEncoder() {
1932 if (!encoder_ || !encoder_initialized_) {
1933 return;
1934 }
1935 encoder_->Release();
1936 encoder_initialized_ = false;
1937 TRACE_EVENT0("webrtc", "VCMGenericEncoder::Release");
1938}
1939
asapersson09f05612017-05-15 23:40:18 -07001940// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001941VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001942 fps_counters_.resize(kScaleReasonSize);
1943 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001944 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001945}
1946
mflodmancc3d4422017-08-03 08:27:51 -07001947VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001948
mflodmancc3d4422017-08-03 08:27:51 -07001949std::string VideoStreamEncoder::AdaptCounter::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001950 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07001951 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1952 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
Jonas Olsson84df1c72018-09-14 16:59:32 +02001953 return ss.Release();
asapersson09f05612017-05-15 23:40:18 -07001954}
1955
Niels Möller213618e2018-07-24 09:29:58 +02001956VideoStreamEncoderObserver::AdaptationSteps
1957VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
1958 VideoStreamEncoderObserver::AdaptationSteps counts;
1959 counts.num_framerate_reductions = fps_counters_[reason];
1960 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-15 23:40:18 -07001961 return counts;
1962}
1963
mflodmancc3d4422017-08-03 08:27:51 -07001964void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001965 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001966}
1967
mflodmancc3d4422017-08-03 08:27:51 -07001968void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001969 ++(resolution_counters_[reason]);
1970}
1971
mflodmancc3d4422017-08-03 08:27:51 -07001972void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001973 if (fps_counters_[reason] == 0) {
1974 // Balanced mode: Adapt up is in a different order, switch reason.
1975 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1976 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1977 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1978 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1979 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1980 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1981 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1982 MoveCount(&resolution_counters_, reason);
1983 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1984 }
1985 --(fps_counters_[reason]);
1986 RTC_DCHECK_GE(fps_counters_[reason], 0);
1987}
1988
mflodmancc3d4422017-08-03 08:27:51 -07001989void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001990 if (resolution_counters_[reason] == 0) {
1991 // Balanced mode: Adapt up is in a different order, switch reason.
1992 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1993 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1994 MoveCount(&fps_counters_, reason);
1995 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1996 }
1997 --(resolution_counters_[reason]);
1998 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1999}
2000
mflodmancc3d4422017-08-03 08:27:51 -07002001void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
2002 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07002003 DecrementFramerate(reason);
2004 // Reset if at max fps (i.e. in case of fewer steps up than down).
2005 if (cur_fps == std::numeric_limits<int>::max())
Steve Antonbd631a02019-03-28 10:51:27 -07002006 absl::c_fill(fps_counters_, 0);
asapersson09f05612017-05-15 23:40:18 -07002007}
2008
mflodmancc3d4422017-08-03 08:27:51 -07002009int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07002010 return Count(fps_counters_);
2011}
2012
mflodmancc3d4422017-08-03 08:27:51 -07002013int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07002014 return Count(resolution_counters_);
2015}
2016
mflodmancc3d4422017-08-03 08:27:51 -07002017int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002018 return fps_counters_[reason];
2019}
2020
mflodmancc3d4422017-08-03 08:27:51 -07002021int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002022 return resolution_counters_[reason];
2023}
2024
mflodmancc3d4422017-08-03 08:27:51 -07002025int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002026 return FramerateCount(reason) + ResolutionCount(reason);
2027}
2028
mflodmancc3d4422017-08-03 08:27:51 -07002029int VideoStreamEncoder::AdaptCounter::Count(
2030 const std::vector<int>& counters) const {
Steve Antonbd631a02019-03-28 10:51:27 -07002031 return absl::c_accumulate(counters, 0);
asapersson09f05612017-05-15 23:40:18 -07002032}
2033
mflodmancc3d4422017-08-03 08:27:51 -07002034void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
2035 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002036 int to_reason = (from_reason + 1) % kScaleReasonSize;
2037 ++((*counters)[to_reason]);
2038 --((*counters)[from_reason]);
2039}
2040
mflodmancc3d4422017-08-03 08:27:51 -07002041std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07002042 const std::vector<int>& counters) const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02002043 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07002044 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
2045 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07002046 }
Jonas Olsson84df1c72018-09-14 16:59:32 +02002047 return ss.Release();
sprangc5d62e22017-04-02 23:53:04 -07002048}
2049
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00002050} // namespace webrtc