blob: f5f0ca5cf3a1b5262d1cd25ccd6eb342dc2608d0 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/video/i420_buffer.h"
19#include "common_video/include/video_bitrate_allocator.h"
20#include "common_video/include/video_frame.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "modules/video_coding/include/video_codec_initializer.h"
22#include "modules/video_coding/include/video_coding.h"
23#include "modules/video_coding/include/video_coding_defines.h"
24#include "rtc_base/arraysize.h"
25#include "rtc_base/checks.h"
26#include "rtc_base/location.h"
27#include "rtc_base/logging.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010028#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/timeutils.h"
30#include "rtc_base/trace_event.h"
31#include "video/overuse_frame_detector.h"
32#include "video/send_statistics_proxy.h"
nisseea3a7982017-05-15 02:42:11 -070033
niklase@google.com470e71d2011-07-07 08:21:25 +000034namespace webrtc {
35
perkj26091b12016-09-01 01:17:40 -070036namespace {
sprangb1ca0732017-02-01 08:38:12 -080037
asapersson6ffb67d2016-09-12 00:10:45 -070038// Time interval for logging frame counts.
39const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070040const int kMinFramerateFps = 2;
sprangfda496a2017-06-15 04:21:07 -070041const int kMaxFramerateFps = 120;
perkj26091b12016-09-01 01:17:40 -070042
kthelgason2bc68642017-02-07 07:02:22 -080043// The maximum number of frames to drop at beginning of stream
44// to try and achieve desired bitrate.
45const int kMaxInitialFramedrop = 4;
46
kthelgason2bc68642017-02-07 07:02:22 -080047uint32_t MaximumFrameSizeForBitrate(uint32_t kbps) {
48 if (kbps > 0) {
49 if (kbps < 300 /* qvga */) {
50 return 320 * 240;
51 } else if (kbps < 500 /* vga */) {
52 return 640 * 480;
53 }
54 }
55 return std::numeric_limits<uint32_t>::max();
56}
57
asaperssonf7e294d2017-06-13 23:25:22 -070058// Initial limits for kBalanced degradation preference.
59int MinFps(int pixels) {
60 if (pixels <= 320 * 240) {
61 return 7;
62 } else if (pixels <= 480 * 270) {
63 return 10;
64 } else if (pixels <= 640 * 480) {
65 return 15;
66 } else {
67 return std::numeric_limits<int>::max();
68 }
69}
70
71int MaxFps(int pixels) {
72 if (pixels <= 320 * 240) {
73 return 10;
74 } else if (pixels <= 480 * 270) {
75 return 15;
76 } else {
77 return std::numeric_limits<int>::max();
78 }
79}
80
asapersson09f05612017-05-15 23:40:18 -070081bool IsResolutionScalingEnabled(
82 VideoSendStream::DegradationPreference degradation_preference) {
83 return degradation_preference ==
84 VideoSendStream::DegradationPreference::kMaintainFramerate ||
85 degradation_preference ==
86 VideoSendStream::DegradationPreference::kBalanced;
87}
88
89bool IsFramerateScalingEnabled(
90 VideoSendStream::DegradationPreference degradation_preference) {
91 return degradation_preference ==
92 VideoSendStream::DegradationPreference::kMaintainResolution ||
93 degradation_preference ==
94 VideoSendStream::DegradationPreference::kBalanced;
95}
96
perkj26091b12016-09-01 01:17:40 -070097} // namespace
98
mflodmancc3d4422017-08-03 08:27:51 -070099class VideoStreamEncoder::EncodeTask : public rtc::QueuedTask {
perkj26091b12016-09-01 01:17:40 -0700100 public:
perkjd52063f2016-09-07 06:32:18 -0700101 EncodeTask(const VideoFrame& frame,
mflodmancc3d4422017-08-03 08:27:51 -0700102 VideoStreamEncoder* video_stream_encoder,
nissee0e3bdf2017-01-18 02:16:20 -0800103 int64_t time_when_posted_us,
asapersson6ffb67d2016-09-12 00:10:45 -0700104 bool log_stats)
nissedf2ceb82016-12-15 06:29:53 -0800105 : frame_(frame),
mflodmancc3d4422017-08-03 08:27:51 -0700106 video_stream_encoder_(video_stream_encoder),
nissee0e3bdf2017-01-18 02:16:20 -0800107 time_when_posted_us_(time_when_posted_us),
asapersson6ffb67d2016-09-12 00:10:45 -0700108 log_stats_(log_stats) {
mflodmancc3d4422017-08-03 08:27:51 -0700109 ++video_stream_encoder_->posted_frames_waiting_for_encode_;
perkj26091b12016-09-01 01:17:40 -0700110 }
111
112 private:
113 bool Run() override {
mflodmancc3d4422017-08-03 08:27:51 -0700114 RTC_DCHECK_RUN_ON(&video_stream_encoder_->encoder_queue_);
mflodmancc3d4422017-08-03 08:27:51 -0700115 video_stream_encoder_->stats_proxy_->OnIncomingFrame(frame_.width(),
116 frame_.height());
117 ++video_stream_encoder_->captured_frame_count_;
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700118 const int posted_frames_waiting_for_encode =
119 video_stream_encoder_->posted_frames_waiting_for_encode_.fetch_sub(1);
120 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
121 if (posted_frames_waiting_for_encode == 1) {
mflodmancc3d4422017-08-03 08:27:51 -0700122 video_stream_encoder_->EncodeVideoFrame(frame_, time_when_posted_us_);
perkj26091b12016-09-01 01:17:40 -0700123 } else {
124 // There is a newer frame in flight. Do not encode this frame.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100125 RTC_LOG(LS_VERBOSE)
perkj26091b12016-09-01 01:17:40 -0700126 << "Incoming frame dropped due to that the encoder is blocked.";
mflodmancc3d4422017-08-03 08:27:51 -0700127 ++video_stream_encoder_->dropped_frame_count_;
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200128 video_stream_encoder_->stats_proxy_->OnFrameDroppedInEncoderQueue();
asapersson6ffb67d2016-09-12 00:10:45 -0700129 }
130 if (log_stats_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100131 RTC_LOG(LS_INFO) << "Number of frames: captured "
132 << video_stream_encoder_->captured_frame_count_
133 << ", dropped (due to encoder blocked) "
134 << video_stream_encoder_->dropped_frame_count_
135 << ", interval_ms " << kFrameLogIntervalMs;
mflodmancc3d4422017-08-03 08:27:51 -0700136 video_stream_encoder_->captured_frame_count_ = 0;
137 video_stream_encoder_->dropped_frame_count_ = 0;
perkj26091b12016-09-01 01:17:40 -0700138 }
139 return true;
140 }
141 VideoFrame frame_;
mflodmancc3d4422017-08-03 08:27:51 -0700142 VideoStreamEncoder* const video_stream_encoder_;
nissee0e3bdf2017-01-18 02:16:20 -0800143 const int64_t time_when_posted_us_;
asapersson6ffb67d2016-09-12 00:10:45 -0700144 const bool log_stats_;
perkj26091b12016-09-01 01:17:40 -0700145};
146
perkja49cbd32016-09-16 07:53:41 -0700147// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700148// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
149// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700150// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700151class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700152 public:
mflodmancc3d4422017-08-03 08:27:51 -0700153 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
154 : video_stream_encoder_(video_stream_encoder),
hbos8d609f62017-04-10 07:39:05 -0700155 degradation_preference_(
156 VideoSendStream::DegradationPreference::kDegradationDisabled),
perkj803d97f2016-11-01 11:45:46 -0700157 source_(nullptr) {}
perkja49cbd32016-09-16 07:53:41 -0700158
hbos8d609f62017-04-10 07:39:05 -0700159 void SetSource(
160 rtc::VideoSourceInterface<VideoFrame>* source,
161 const VideoSendStream::DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700162 // Called on libjingle's worker thread.
perkja49cbd32016-09-16 07:53:41 -0700163 RTC_DCHECK_CALLED_SEQUENTIALLY(&main_checker_);
164 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700165 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700166 {
167 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700168 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700169 old_source = source_;
170 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700171 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700172 }
173
174 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700175 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700176 }
177
178 if (!source) {
179 return;
180 }
181
mflodmancc3d4422017-08-03 08:27:51 -0700182 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700183 }
184
perkj803d97f2016-11-01 11:45:46 -0700185 void SetWantsRotationApplied(bool rotation_applied) {
186 rtc::CritScope lock(&crit_);
187 sink_wants_.rotation_applied = rotation_applied;
sprangc5d62e22017-04-02 23:53:04 -0700188 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700189 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
sprangc5d62e22017-04-02 23:53:04 -0700190 }
191
sprangfda496a2017-06-15 04:21:07 -0700192 rtc::VideoSinkWants GetActiveSinkWants() {
193 rtc::CritScope lock(&crit_);
194 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700195 }
196
asaperssonf7e294d2017-06-13 23:25:22 -0700197 void ResetPixelFpsCount() {
198 rtc::CritScope lock(&crit_);
199 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
200 sink_wants_.target_pixel_count.reset();
201 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
202 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700203 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
asaperssonf7e294d2017-06-13 23:25:22 -0700204 }
205
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100206 bool RequestResolutionLowerThan(int pixel_count,
207 int min_pixels_per_frame,
208 bool* min_pixels_reached) {
perkj803d97f2016-11-01 11:45:46 -0700209 // Called on the encoder task queue.
210 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700211 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700212 // This can happen since |degradation_preference_| is set on libjingle's
213 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700214 return false;
perkj803d97f2016-11-01 11:45:46 -0700215 }
asapersson13874762017-06-07 00:01:02 -0700216 // The input video frame size will have a resolution less than or equal to
217 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800218 const int pixels_wanted = (pixel_count * 3) / 5;
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100219 if (pixels_wanted >= sink_wants_.max_pixel_count) {
220 return false;
221 }
222 if (pixels_wanted < min_pixels_per_frame) {
223 *min_pixels_reached = true;
asaperssond0de2952017-04-21 01:47:31 -0700224 return false;
asapersson13874762017-06-07 00:01:02 -0700225 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100226 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
227 << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700228 sink_wants_.max_pixel_count = pixels_wanted;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100229 sink_wants_.target_pixel_count = rtc::nullopt;
mflodmancc3d4422017-08-03 08:27:51 -0700230 source_->AddOrUpdateSink(video_stream_encoder_,
231 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700232 return true;
sprangc5d62e22017-04-02 23:53:04 -0700233 }
234
sprangfda496a2017-06-15 04:21:07 -0700235 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700236 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700237 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700238 int framerate_wanted = (fps * 2) / 3;
239 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700240 }
241
asapersson13874762017-06-07 00:01:02 -0700242 bool RequestHigherResolutionThan(int pixel_count) {
243 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700244 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700245 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700246 // This can happen since |degradation_preference_| is set on libjingle's
247 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700248 return false;
perkj803d97f2016-11-01 11:45:46 -0700249 }
asapersson13874762017-06-07 00:01:02 -0700250 int max_pixels_wanted = pixel_count;
251 if (max_pixels_wanted != std::numeric_limits<int>::max())
252 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700253
asapersson13874762017-06-07 00:01:02 -0700254 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
255 return false;
256
257 sink_wants_.max_pixel_count = max_pixels_wanted;
258 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700259 // Remove any constraints.
260 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700261 } else {
262 // On step down we request at most 3/5 the pixel count of the previous
263 // resolution, so in order to take "one step up" we request a resolution
264 // as close as possible to 5/3 of the current resolution. The actual pixel
265 // count selected depends on the capabilities of the source. In order to
266 // not take a too large step up, we cap the requested pixel count to be at
267 // most four time the current number of pixels.
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100268 sink_wants_.target_pixel_count = (pixel_count * 5) / 3;
sprangc5d62e22017-04-02 23:53:04 -0700269 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100270 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
271 << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700272 source_->AddOrUpdateSink(video_stream_encoder_,
273 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700274 return true;
sprangc5d62e22017-04-02 23:53:04 -0700275 }
276
sprangfda496a2017-06-15 04:21:07 -0700277 // Request upgrade in framerate. Returns the new requested frame, or -1 if
278 // no change requested. Note that maxint may be returned if limits due to
279 // adaptation requests are removed completely. In that case, consider
280 // |max_framerate_| to be the current limit (assuming the capturer complies).
281 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700282 // Called on the encoder task queue.
283 // The input frame rate will be scaled up to the last step, with rounding.
284 int framerate_wanted = fps;
285 if (fps != std::numeric_limits<int>::max())
286 framerate_wanted = (fps * 3) / 2;
287
sprangfda496a2017-06-15 04:21:07 -0700288 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700289 }
290
291 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700292 // Called on the encoder task queue.
293 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700294 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
295 return false;
296
297 const int fps_wanted = std::max(kMinFramerateFps, fps);
298 if (fps_wanted >= sink_wants_.max_framerate_fps)
299 return false;
300
Mirko Bonadei675513b2017-11-09 11:09:25 +0100301 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700302 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700303 source_->AddOrUpdateSink(video_stream_encoder_,
304 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700305 return true;
306 }
307
308 bool IncreaseFramerate(int fps) {
309 // Called on the encoder task queue.
310 rtc::CritScope lock(&crit_);
311 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
312 return false;
313
314 const int fps_wanted = std::max(kMinFramerateFps, fps);
315 if (fps_wanted <= sink_wants_.max_framerate_fps)
316 return false;
317
Mirko Bonadei675513b2017-11-09 11:09:25 +0100318 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700319 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700320 source_->AddOrUpdateSink(video_stream_encoder_,
321 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700322 return true;
perkj803d97f2016-11-01 11:45:46 -0700323 }
324
perkja49cbd32016-09-16 07:53:41 -0700325 private:
sprangfda496a2017-06-15 04:21:07 -0700326 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700327 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700328 rtc::VideoSinkWants wants = sink_wants_;
329 // Clear any constraints from the current sink wants that don't apply to
330 // the used degradation_preference.
331 switch (degradation_preference_) {
332 case VideoSendStream::DegradationPreference::kBalanced:
333 break;
334 case VideoSendStream::DegradationPreference::kMaintainFramerate:
335 wants.max_framerate_fps = std::numeric_limits<int>::max();
336 break;
337 case VideoSendStream::DegradationPreference::kMaintainResolution:
338 wants.max_pixel_count = std::numeric_limits<int>::max();
339 wants.target_pixel_count.reset();
340 break;
341 case VideoSendStream::DegradationPreference::kDegradationDisabled:
342 wants.max_pixel_count = std::numeric_limits<int>::max();
343 wants.target_pixel_count.reset();
344 wants.max_framerate_fps = std::numeric_limits<int>::max();
345 }
346 return wants;
347 }
348
perkja49cbd32016-09-16 07:53:41 -0700349 rtc::CriticalSection crit_;
350 rtc::SequencedTaskChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700351 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700352 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
hbos8d609f62017-04-10 07:39:05 -0700353 VideoSendStream::DegradationPreference degradation_preference_
danilchapa37de392017-09-09 04:17:22 -0700354 RTC_GUARDED_BY(&crit_);
355 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700356
357 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
358};
359
Ã…sa Persson0122e842017-10-16 12:19:23 +0200360VideoStreamEncoder::VideoStreamEncoder(
361 uint32_t number_of_cores,
362 SendStatisticsProxy* stats_proxy,
363 const VideoSendStream::Config::EncoderSettings& settings,
364 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
Ã…sa Persson0122e842017-10-16 12:19:23 +0200365 std::unique_ptr<OveruseFrameDetector> overuse_detector)
perkj26091b12016-09-01 01:17:40 -0700366 : shutdown_event_(true /* manual_reset */, false),
367 number_of_cores_(number_of_cores),
kthelgason2bc68642017-02-07 07:02:22 -0800368 initial_rampup_(0),
perkja49cbd32016-09-16 07:53:41 -0700369 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200370 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700371 settings_(settings),
Niels Möllera0565992017-10-24 11:37:08 +0200372 video_sender_(Clock::GetRealTimeClock(), this),
Niels Möller73f29cb2018-01-31 16:09:31 +0100373 overuse_detector_(std::move(overuse_detector)),
Peter Boström7083e112015-09-22 16:28:51 +0200374 stats_proxy_(stats_proxy),
perkj26091b12016-09-01 01:17:40 -0700375 pre_encode_callback_(pre_encode_callback),
sprangfda496a2017-06-15 04:21:07 -0700376 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700377 pending_encoder_reconfiguration_(false),
perkj26091b12016-09-01 01:17:40 -0700378 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 11:48:50 +0200379 max_data_payload_length_(0),
asapersson5f7226f2016-11-25 04:37:00 -0800380 nack_enabled_(false),
pbos@webrtc.org143451d2015-03-18 14:40:03 +0000381 last_observed_bitrate_bps_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000382 encoder_paused_and_dropped_frame_(false),
perkj26091b12016-09-01 01:17:40 -0700383 clock_(Clock::GetRealTimeClock()),
hbos8d609f62017-04-10 07:39:05 -0700384 degradation_preference_(
385 VideoSendStream::DegradationPreference::kDegradationDisabled),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700386 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700387 last_captured_timestamp_(0),
388 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
389 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700390 last_frame_log_ms_(clock_->TimeInMilliseconds()),
391 captured_frame_count_(0),
392 dropped_frame_count_(0),
sprang1a646ee2016-12-01 06:34:11 -0800393 bitrate_observer_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700394 encoder_queue_("EncoderQueue") {
sprang552c7c72017-02-13 04:41:45 -0800395 RTC_DCHECK(stats_proxy);
Niels Möller73f29cb2018-01-31 16:09:31 +0100396 RTC_DCHECK(overuse_detector_);
perkj803d97f2016-11-01 11:45:46 -0700397 encoder_queue_.PostTask([this] {
perkj26091b12016-09-01 01:17:40 -0700398 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller73f29cb2018-01-31 16:09:31 +0100399 overuse_detector_->StartCheckForOveruse(this);
perkj26091b12016-09-01 01:17:40 -0700400 video_sender_.RegisterExternalEncoder(
Niels Möllerbf3dbb42018-03-16 13:38:46 +0100401 settings_.encoder, settings_.internal_source);
perkj26091b12016-09-01 01:17:40 -0700402 });
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000403}
404
mflodmancc3d4422017-08-03 08:27:51 -0700405VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700406 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700407 RTC_DCHECK(shutdown_event_.Wait(0))
408 << "Must call ::Stop() before destruction.";
409}
410
mflodmancc3d4422017-08-03 08:27:51 -0700411void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700412 RTC_DCHECK_RUN_ON(&thread_checker_);
hbos8d609f62017-04-10 07:39:05 -0700413 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700414 encoder_queue_.PostTask([this] {
415 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700416 overuse_detector_->StopCheckForOveruse();
Erik Språng08127a92016-11-16 16:41:30 +0100417 rate_allocator_.reset();
sprang1a646ee2016-12-01 06:34:11 -0800418 bitrate_observer_ = nullptr;
Niels Möllerbf3dbb42018-03-16 13:38:46 +0100419 video_sender_.RegisterExternalEncoder(nullptr, false);
kthelgason876222f2016-11-29 01:44:11 -0800420 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700421 shutdown_event_.Set();
422 });
423
424 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700425}
426
mflodmancc3d4422017-08-03 08:27:51 -0700427void VideoStreamEncoder::SetBitrateObserver(
sprang1a646ee2016-12-01 06:34:11 -0800428 VideoBitrateAllocationObserver* bitrate_observer) {
429 RTC_DCHECK_RUN_ON(&thread_checker_);
430 encoder_queue_.PostTask([this, bitrate_observer] {
431 RTC_DCHECK_RUN_ON(&encoder_queue_);
432 RTC_DCHECK(!bitrate_observer_);
433 bitrate_observer_ = bitrate_observer;
434 });
435}
436
mflodmancc3d4422017-08-03 08:27:51 -0700437void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700438 rtc::VideoSourceInterface<VideoFrame>* source,
asapersson09f05612017-05-15 23:40:18 -0700439 const VideoSendStream::DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700440 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700441 source_proxy_->SetSource(source, degradation_preference);
442 encoder_queue_.PostTask([this, degradation_preference] {
443 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700444 if (degradation_preference_ != degradation_preference) {
445 // Reset adaptation state, so that we're not tricked into thinking there's
446 // an already pending request of the same type.
447 last_adaptation_request_.reset();
asaperssonf7e294d2017-06-13 23:25:22 -0700448 if (degradation_preference ==
449 VideoSendStream::DegradationPreference::kBalanced ||
450 degradation_preference_ ==
451 VideoSendStream::DegradationPreference::kBalanced) {
452 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
453 // AdaptCounter for all modes.
454 source_proxy_->ResetPixelFpsCount();
455 adapt_counters_.clear();
456 }
sprangc5d62e22017-04-02 23:53:04 -0700457 }
sprangb1ca0732017-02-01 08:38:12 -0800458 degradation_preference_ = degradation_preference;
asapersson91914e22017-06-01 00:34:08 -0700459 bool allow_scaling = IsResolutionScalingEnabled(degradation_preference_);
sprangc5d62e22017-04-02 23:53:04 -0700460 initial_rampup_ = allow_scaling ? 0 : kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -0800461 ConfigureQualityScaler();
Niels Möller7dc26b72017-12-06 10:27:48 +0100462 if (!IsFramerateScalingEnabled(degradation_preference) &&
463 max_framerate_ != -1) {
464 // If frame rate scaling is no longer allowed, remove any potential
465 // allowance for longer frame intervals.
466 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
467 }
perkj803d97f2016-11-01 11:45:46 -0700468 });
perkja49cbd32016-09-16 07:53:41 -0700469}
470
mflodmancc3d4422017-08-03 08:27:51 -0700471void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700472 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700473 encoder_queue_.PostTask([this, sink] {
474 RTC_DCHECK_RUN_ON(&encoder_queue_);
475 sink_ = sink;
476 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000477}
478
mflodmancc3d4422017-08-03 08:27:51 -0700479void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700480 encoder_queue_.PostTask([this, start_bitrate_bps] {
481 RTC_DCHECK_RUN_ON(&encoder_queue_);
482 encoder_start_bitrate_bps_ = start_bitrate_bps;
483 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000484}
Peter Boström00b9d212016-05-19 16:59:03 +0200485
mflodmancc3d4422017-08-03 08:27:51 -0700486void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
487 size_t max_data_payload_length,
488 bool nack_enabled) {
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100489 // TODO(srte): This struct should be replaced by a lambda with move capture
490 // when C++14 lambda is allowed.
491 struct ConfigureEncoderTask {
492 void operator()() {
493 encoder->ConfigureEncoderOnTaskQueue(
494 std::move(config), max_data_payload_length, nack_enabled);
495 }
496 VideoStreamEncoder* encoder;
497 VideoEncoderConfig config;
498 size_t max_data_payload_length;
499 bool nack_enabled;
500 };
501 encoder_queue_.PostTask(ConfigureEncoderTask{
502 this, std::move(config), max_data_payload_length, nack_enabled});
perkj26091b12016-09-01 01:17:40 -0700503}
504
mflodmancc3d4422017-08-03 08:27:51 -0700505void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
506 VideoEncoderConfig config,
507 size_t max_data_payload_length,
508 bool nack_enabled) {
perkj26091b12016-09-01 01:17:40 -0700509 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700510 RTC_DCHECK(sink_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100511 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200512
513 max_data_payload_length_ = max_data_payload_length;
asapersson5f7226f2016-11-25 04:37:00 -0800514 nack_enabled_ = nack_enabled;
Pera48ddb72016-09-29 11:48:50 +0200515 encoder_config_ = std::move(config);
perkjfa10b552016-10-02 23:45:26 -0700516 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200517
perkjfa10b552016-10-02 23:45:26 -0700518 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100519 // if the frame resolution is known. Otherwise, the reconfiguration is
520 // deferred until the next frame to minimize the number of reconfigurations.
521 // The codec configuration depends on incoming video frame size.
522 if (last_frame_info_) {
523 ReconfigureEncoder();
524 } else if (settings_.internal_source) {
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100525 last_frame_info_ = VideoFrameInfo(176, 144, false);
perkjfa10b552016-10-02 23:45:26 -0700526 ReconfigureEncoder();
527 }
528}
perkj26091b12016-09-01 01:17:40 -0700529
Seth Hampsoncc7125f2018-02-02 08:46:16 -0800530// TODO(bugs.webrtc.org/8807): Currently this always does a hard
531// reconfiguration, but this isn't always necessary. Add in logic to only update
532// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
533// "soft" reconfiguration.
mflodmancc3d4422017-08-03 08:27:51 -0700534void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700535 RTC_DCHECK(pending_encoder_reconfiguration_);
536 std::vector<VideoStream> streams =
537 encoder_config_.video_stream_factory->CreateEncoderStreams(
538 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700539
ilnik6b826ef2017-06-16 06:53:48 -0700540 // TODO(ilnik): If configured resolution is significantly less than provided,
541 // e.g. because there are not enough SSRCs for all simulcast streams,
542 // signal new resolutions via SinkWants to video source.
543
544 // Stream dimensions may be not equal to given because of a simulcast
545 // restrictions.
546 int highest_stream_width = static_cast<int>(streams.back().width);
547 int highest_stream_height = static_cast<int>(streams.back().height);
548 // Dimension may be reduced to be, e.g. divisible by 4.
549 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
550 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
551 crop_width_ = last_frame_info_->width - highest_stream_width;
552 crop_height_ = last_frame_info_->height - highest_stream_height;
553
Erik Språng08127a92016-11-16 16:41:30 +0100554 VideoCodec codec;
Niels Möller6c2c13a2018-03-29 13:06:51 +0200555 if (!VideoCodecInitializer::SetupCodec(encoder_config_, settings_, streams,
556 nack_enabled_, &codec,
557 &rate_allocator_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100558 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100559 }
perkjfa10b552016-10-02 23:45:26 -0700560
561 codec.startBitrate =
562 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
563 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
564 codec.expect_encode_from_texture = last_frame_info_->is_texture;
sprangfda496a2017-06-15 04:21:07 -0700565 max_framerate_ = codec.maxFramerate;
566 RTC_DCHECK_LE(max_framerate_, kMaxFramerateFps);
Stefan Holmere5904162015-03-26 11:11:06 +0100567
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200568 bool success = video_sender_.RegisterSendCodec(
perkjfa10b552016-10-02 23:45:26 -0700569 &codec, number_of_cores_,
570 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
Peter Boström905f8e72016-03-02 16:59:56 +0100571 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100572 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 08:24:59 -0700573 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000574 }
Peter Boström905f8e72016-03-02 16:59:56 +0100575
Niels Möller96d7f762018-01-30 11:27:16 +0100576 video_sender_.UpdateChannelParameters(rate_allocator_.get(),
ilnik35b7de42017-03-15 04:24:21 -0700577 bitrate_observer_);
578
sprangfda496a2017-06-15 04:21:07 -0700579 // Get the current actual framerate, as measured by the stats proxy. This is
580 // used to get the correct bitrate layer allocation.
581 int current_framerate = stats_proxy_->GetSendFrameRate();
582 if (current_framerate == 0)
583 current_framerate = codec.maxFramerate;
sprang552c7c72017-02-13 04:41:45 -0800584 stats_proxy_->OnEncoderReconfigured(
Ã…sa Perssonaa329e72017-12-15 15:54:44 +0100585 encoder_config_, streams,
sprangfda496a2017-06-15 04:21:07 -0700586 rate_allocator_.get()
587 ? rate_allocator_->GetPreferredBitrateBps(current_framerate)
588 : codec.maxBitrate);
Per512ecb32016-09-23 15:52:06 +0200589
perkjfa10b552016-10-02 23:45:26 -0700590 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100591
Pera48ddb72016-09-29 11:48:50 +0200592 sink_->OnEncoderConfigurationChanged(
perkjfa10b552016-10-02 23:45:26 -0700593 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800594
Niels Möller7dc26b72017-12-06 10:27:48 +0100595 // Get the current target framerate, ie the maximum framerate as specified by
596 // the current codec configuration, or any limit imposed by cpu adaption in
597 // maintain-resolution or balanced mode. This is used to make sure overuse
598 // detection doesn't needlessly trigger in low and/or variable framerate
599 // scenarios.
600 int target_framerate = std::min(
601 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
602 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
603
kthelgason2bc68642017-02-07 07:02:22 -0800604 ConfigureQualityScaler();
605}
606
mflodmancc3d4422017-08-03 08:27:51 -0700607void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 07:02:22 -0800608 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800609 const auto scaling_settings = settings_.encoder->GetScalingSettings();
asapersson36e9eb42017-03-31 05:29:12 -0700610 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700611 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +0100612 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -0700613
asapersson36e9eb42017-03-31 05:29:12 -0700614 if (quality_scaling_allowed) {
asapersson09f05612017-05-15 23:40:18 -0700615 if (quality_scaler_.get() == nullptr) {
616 // Quality scaler has not already been configured.
617 // Drop frames and scale down until desired quality is achieved.
Niels Möller225c7872018-02-22 15:03:53 +0100618
619 // Since the interface is non-public, MakeUnique can't do this upcast.
620 AdaptationObserverInterface* observer = this;
621 quality_scaler_ = rtc::MakeUnique<QualityScaler>(
622 observer, *(scaling_settings.thresholds));
kthelgason876222f2016-11-29 01:44:11 -0800623 }
624 } else {
625 quality_scaler_.reset(nullptr);
kthelgasonad9010c2017-02-14 00:46:51 -0800626 initial_rampup_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800627 }
asapersson09f05612017-05-15 23:40:18 -0700628
629 stats_proxy_->SetAdaptationStats(GetActiveCounts(kCpu),
630 GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000631}
632
mflodmancc3d4422017-08-03 08:27:51 -0700633void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700634 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700635 VideoFrame incoming_frame = video_frame;
636
637 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700638 int64_t current_time_us = clock_->TimeInMicroseconds();
639 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
640 // In some cases, e.g., when the frame from decoder is fed to encoder,
641 // the timestamp may be set to the future. As the encoding pipeline assumes
642 // capture time to be less than present time, we should reset the capture
643 // timestamps here. Otherwise there may be issues with RTP send stream.
644 if (incoming_frame.timestamp_us() > current_time_us)
645 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700646
647 // Capture time may come from clock with an offset and drift from clock_.
648 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800649 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700650 capture_ntp_time_ms = video_frame.ntp_time_ms();
651 } else if (video_frame.render_time_ms() != 0) {
652 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
653 } else {
nisse1c0dea82017-01-30 02:43:18 -0800654 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700655 }
656 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
657
658 // Convert NTP time, in ms, to RTP timestamp.
659 const int kMsToRtpTimestamp = 90;
660 incoming_frame.set_timestamp(
661 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
662
663 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
664 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100665 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
666 << incoming_frame.ntp_time_ms()
667 << " <= " << last_captured_timestamp_
668 << ") for incoming frame. Dropping.";
perkj26091b12016-09-01 01:17:40 -0700669 return;
670 }
671
asapersson6ffb67d2016-09-12 00:10:45 -0700672 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800673 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
674 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700675 log_stats = true;
676 }
677
perkj26091b12016-09-01 01:17:40 -0700678 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
asapersson6ffb67d2016-09-12 00:10:45 -0700679 encoder_queue_.PostTask(std::unique_ptr<rtc::QueuedTask>(new EncodeTask(
nissee0e3bdf2017-01-18 02:16:20 -0800680 incoming_frame, this, rtc::TimeMicros(), log_stats)));
perkj26091b12016-09-01 01:17:40 -0700681}
682
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200683void VideoStreamEncoder::OnDiscardedFrame() {
684 stats_proxy_->OnFrameDroppedBySource();
685}
686
mflodmancc3d4422017-08-03 08:27:51 -0700687bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700688 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000689 // Pause video if paused by caller or as long as the network is down or the
690 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700691 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 00:58:48 -0700692 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 01:17:40 -0700693 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000694}
695
mflodmancc3d4422017-08-03 08:27:51 -0700696void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -0700697 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000698 // Start trace event only on the first frame after encoder is paused.
699 if (!encoder_paused_and_dropped_frame_) {
700 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
701 }
702 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000703}
704
mflodmancc3d4422017-08-03 08:27:51 -0700705void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -0700706 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000707 // End trace event on first frame after encoder resumes, if frame was dropped.
708 if (encoder_paused_and_dropped_frame_) {
709 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
710 }
711 encoder_paused_and_dropped_frame_ = false;
712}
713
mflodmancc3d4422017-08-03 08:27:51 -0700714void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
715 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -0700716 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800717
perkj26091b12016-09-01 01:17:40 -0700718 if (pre_encode_callback_)
719 pre_encode_callback_->OnFrame(video_frame);
720
Per21d45d22016-10-30 21:37:57 +0100721 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -0700722 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -0700723 video_frame.is_texture() != last_frame_info_->is_texture) {
724 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100725 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
726 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100727 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
728 << last_frame_info_->width << "x"
729 << last_frame_info_->height
730 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-02 23:45:26 -0700731 }
732
kthelgason2bc68642017-02-07 07:02:22 -0800733 if (initial_rampup_ < kMaxInitialFramedrop &&
734 video_frame.size() >
735 MaximumFrameSizeForBitrate(encoder_start_bitrate_bps_ / 1000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100736 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Ã…sa Persson875841d2018-01-08 08:49:53 +0100737 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -0800738 AdaptDown(kQuality);
Ã…sa Persson875841d2018-01-08 08:49:53 +0100739 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
740 stats_proxy_->OnInitialQualityResolutionAdaptDown();
741 }
kthelgason2bc68642017-02-07 07:02:22 -0800742 ++initial_rampup_;
743 return;
744 }
745 initial_rampup_ = kMaxInitialFramedrop;
746
sprang57c2fff2017-01-16 06:24:02 -0800747 int64_t now_ms = clock_->TimeInMilliseconds();
perkjfa10b552016-10-02 23:45:26 -0700748 if (pending_encoder_reconfiguration_) {
749 ReconfigureEncoder();
sprang4847ae62017-06-27 07:06:52 -0700750 last_parameters_update_ms_.emplace(now_ms);
sprang57c2fff2017-01-16 06:24:02 -0800751 } else if (!last_parameters_update_ms_ ||
752 now_ms - *last_parameters_update_ms_ >=
753 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
Niels Möller96d7f762018-01-30 11:27:16 +0100754 video_sender_.UpdateChannelParameters(rate_allocator_.get(),
sprang57c2fff2017-01-16 06:24:02 -0800755 bitrate_observer_);
sprang4847ae62017-06-27 07:06:52 -0700756 last_parameters_update_ms_.emplace(now_ms);
perkjfa10b552016-10-02 23:45:26 -0700757 }
758
perkj26091b12016-09-01 01:17:40 -0700759 if (EncoderPaused()) {
760 TraceFrameDropStart();
761 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000762 }
perkj26091b12016-09-01 01:17:40 -0700763 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +0000764
ilnik6b826ef2017-06-16 06:53:48 -0700765 VideoFrame out_frame(video_frame);
766 // Crop frame if needed.
767 if (crop_width_ > 0 || crop_height_ > 0) {
768 int cropped_width = video_frame.width() - crop_width_;
769 int cropped_height = video_frame.height() - crop_height_;
770 rtc::scoped_refptr<I420Buffer> cropped_buffer =
771 I420Buffer::Create(cropped_width, cropped_height);
772 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
773 // happen after SinkWants signaled correctly from ReconfigureEncoder.
774 if (crop_width_ < 4 && crop_height_ < 4) {
775 cropped_buffer->CropAndScaleFrom(
776 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
777 crop_height_ / 2, cropped_width, cropped_height);
778 } else {
779 cropped_buffer->ScaleFrom(
780 *video_frame.video_frame_buffer()->ToI420().get());
781 }
782 out_frame =
783 VideoFrame(cropped_buffer, video_frame.timestamp(),
784 video_frame.render_time_ms(), video_frame.rotation());
785 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
786 }
787
Magnus Jedvert26679d62015-04-07 14:07:41 +0200788 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +0000789 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +0000790
Niels Möller7dc26b72017-12-06 10:27:48 +0100791 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -0700792
ilnik6b826ef2017-06-16 06:53:48 -0700793 video_sender_.AddVideoFrame(out_frame, nullptr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000794}
niklase@google.com470e71d2011-07-07 08:21:25 +0000795
mflodmancc3d4422017-08-03 08:27:51 -0700796void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -0700797 if (!encoder_queue_.IsCurrent()) {
798 encoder_queue_.PostTask([this] { SendKeyFrame(); });
799 return;
800 }
801 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +0100802 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200803 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48 +0000804}
805
mflodmancc3d4422017-08-03 08:27:51 -0700806EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700807 const EncodedImage& encoded_image,
808 const CodecSpecificInfo* codec_specific_info,
809 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 01:17:40 -0700810 // Encoded is called on whatever thread the real encoder implementation run
811 // on. In the case of hardware encoders, there might be several encoders
812 // running in parallel on different threads.
sprang552c7c72017-02-13 04:41:45 -0800813 stats_proxy_->OnSendEncodedImage(encoded_image, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -0700814
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700815 EncodedImageCallback::Result result =
816 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 06:31:25 -0700817
Niels Möller7dc26b72017-12-06 10:27:48 +0100818 int64_t time_sent_us = rtc::TimeMicros();
819 uint32_t timestamp = encoded_image._timeStamp;
kthelgason876222f2016-11-29 01:44:11 -0800820 const int qp = encoded_image.qp_;
Niels Möller83dbeac2017-12-14 16:39:44 +0100821 int64_t capture_time_us =
822 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec;
823
824 rtc::Optional<int> encode_duration_us;
825 if (encoded_image.timing_.flags != TimingFrameFlags::kInvalid) {
826 encode_duration_us.emplace(
827 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
828 rtc::kNumMicrosecsPerMillisec *
829 (encoded_image.timing_.encode_finish_ms -
830 encoded_image.timing_.encode_start_ms));
831 }
832
833 encoder_queue_.PostTask(
834 [this, timestamp, time_sent_us, qp, capture_time_us, encode_duration_us] {
835 RTC_DCHECK_RUN_ON(&encoder_queue_);
836 overuse_detector_->FrameSent(timestamp, time_sent_us, capture_time_us,
837 encode_duration_us);
838 if (quality_scaler_ && qp >= 0)
839 quality_scaler_->ReportQP(qp);
840 });
perkj803d97f2016-11-01 11:45:46 -0700841
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700842 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +0100843}
844
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200845void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
846 switch (reason) {
847 case DropReason::kDroppedByMediaOptimizations:
848 stats_proxy_->OnFrameDroppedByMediaOptimizations();
849 encoder_queue_.PostTask([this] {
850 RTC_DCHECK_RUN_ON(&encoder_queue_);
851 if (quality_scaler_)
852 quality_scaler_->ReportDroppedFrame();
853 });
854 break;
855 case DropReason::kDroppedByEncoder:
856 stats_proxy_->OnFrameDroppedByEncoder();
857 break;
858 }
kthelgason876222f2016-11-29 01:44:11 -0800859}
860
mflodmancc3d4422017-08-03 08:27:51 -0700861void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
862 uint8_t fraction_lost,
863 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 01:17:40 -0700864 if (!encoder_queue_.IsCurrent()) {
865 encoder_queue_.PostTask(
866 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
867 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
868 });
869 return;
870 }
871 RTC_DCHECK_RUN_ON(&encoder_queue_);
872 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
873
Mirko Bonadei675513b2017-11-09 11:09:25 +0100874 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
875 << " packet loss " << static_cast<int>(fraction_lost)
876 << " rtt " << round_trip_time_ms;
perkj26091b12016-09-01 01:17:40 -0700877
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200878 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
sprang1a646ee2016-12-01 06:34:11 -0800879 round_trip_time_ms, rate_allocator_.get(),
880 bitrate_observer_);
perkj26091b12016-09-01 01:17:40 -0700881
882 encoder_start_bitrate_bps_ =
883 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 17:21:19 +0200884 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 16:41:30 +0100885 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 01:17:40 -0700886 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12 +0000887
sprang552c7c72017-02-13 04:41:45 -0800888 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100889 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
890 << (video_is_suspended ? "suspended" : "not suspended");
Peter Boström7083e112015-09-22 16:28:51 +0200891 stats_proxy_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +0200892 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000893}
894
mflodmancc3d4422017-08-03 08:27:51 -0700895void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -0700896 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700897 AdaptationRequest adaptation_request = {
898 last_frame_info_->pixel_count(),
899 stats_proxy_->GetStats().input_frame_rate,
900 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -0700901
sprangc5d62e22017-04-02 23:53:04 -0700902 bool downgrade_requested =
903 last_adaptation_request_ &&
904 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
905
sprangc5d62e22017-04-02 23:53:04 -0700906 switch (degradation_preference_) {
hbos8d609f62017-04-10 07:39:05 -0700907 case VideoSendStream::DegradationPreference::kBalanced:
asaperssonf7e294d2017-06-13 23:25:22 -0700908 break;
hbos8d609f62017-04-10 07:39:05 -0700909 case VideoSendStream::DegradationPreference::kMaintainFramerate:
sprangc5d62e22017-04-02 23:53:04 -0700910 if (downgrade_requested &&
911 adaptation_request.input_pixel_count_ >=
912 last_adaptation_request_->input_pixel_count_) {
913 // Don't request lower resolution if the current resolution is not
914 // lower than the last time we asked for the resolution to be lowered.
915 return;
916 }
917 break;
hbos8d609f62017-04-10 07:39:05 -0700918 case VideoSendStream::DegradationPreference::kMaintainResolution:
sprangc5d62e22017-04-02 23:53:04 -0700919 if (adaptation_request.framerate_fps_ <= 0 ||
920 (downgrade_requested &&
921 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
922 // If no input fps estimate available, can't determine how to scale down
923 // framerate. Otherwise, don't request lower framerate if we don't have
924 // a valid frame rate. Since framerate, unlike resolution, is a measure
925 // we have to estimate, and can fluctuate naturally over time, don't
926 // make the same kind of limitations as for resolution, but trust the
927 // overuse detector to not trigger too often.
928 return;
929 }
930 break;
hbos8d609f62017-04-10 07:39:05 -0700931 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -0700932 return;
sprang84a37592017-02-10 07:04:27 -0800933 }
sprangc5d62e22017-04-02 23:53:04 -0700934
sprangc5d62e22017-04-02 23:53:04 -0700935 switch (degradation_preference_) {
asaperssonf7e294d2017-06-13 23:25:22 -0700936 case VideoSendStream::DegradationPreference::kBalanced: {
937 // Try scale down framerate, if lower.
938 int fps = MinFps(last_frame_info_->pixel_count());
939 if (source_proxy_->RestrictFramerate(fps)) {
940 GetAdaptCounter().IncrementFramerate(reason);
941 break;
942 }
943 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +0100944 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -0700945 }
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100946 case VideoSendStream::DegradationPreference::kMaintainFramerate: {
asapersson13874762017-06-07 00:01:02 -0700947 // Scale down resolution.
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100948 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -0700949 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -0700950 adaptation_request.input_pixel_count_,
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100951 settings_.encoder->GetScalingSettings().min_pixels_per_frame,
952 &min_pixels_reached)) {
953 if (min_pixels_reached)
954 stats_proxy_->OnMinPixelLimitReached();
asaperssond0de2952017-04-21 01:47:31 -0700955 return;
956 }
asaperssonf7e294d2017-06-13 23:25:22 -0700957 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -0700958 break;
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100959 }
sprangfda496a2017-06-15 04:21:07 -0700960 case VideoSendStream::DegradationPreference::kMaintainResolution: {
asapersson13874762017-06-07 00:01:02 -0700961 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -0700962 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
963 adaptation_request.framerate_fps_);
964 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -0700965 return;
sprangfda496a2017-06-15 04:21:07 -0700966 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +0100967 overuse_detector_->OnTargetFramerateUpdated(
968 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -0700969 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -0700970 break;
sprangfda496a2017-06-15 04:21:07 -0700971 }
hbos8d609f62017-04-10 07:39:05 -0700972 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -0700973 RTC_NOTREACHED();
974 }
975
asaperssond0de2952017-04-21 01:47:31 -0700976 last_adaptation_request_.emplace(adaptation_request);
977
asapersson09f05612017-05-15 23:40:18 -0700978 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -0700979
Mirko Bonadei675513b2017-11-09 11:09:25 +0100980 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -0700981}
982
mflodmancc3d4422017-08-03 08:27:51 -0700983void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -0700984 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -0700985
986 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
987 int num_downgrades = adapt_counter.TotalCount(reason);
988 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -0700989 return;
asapersson09f05612017-05-15 23:40:18 -0700990 RTC_DCHECK_GT(num_downgrades, 0);
991
sprangc5d62e22017-04-02 23:53:04 -0700992 AdaptationRequest adaptation_request = {
993 last_frame_info_->pixel_count(),
994 stats_proxy_->GetStats().input_frame_rate,
995 AdaptationRequest::Mode::kAdaptUp};
996
997 bool adapt_up_requested =
998 last_adaptation_request_ &&
999 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001000
asaperssonf7e294d2017-06-13 23:25:22 -07001001 if (degradation_preference_ ==
1002 VideoSendStream::DegradationPreference::kMaintainFramerate) {
1003 if (adapt_up_requested &&
1004 adaptation_request.input_pixel_count_ <=
1005 last_adaptation_request_->input_pixel_count_) {
1006 // Don't request higher resolution if the current resolution is not
1007 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001008 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001009 }
sprangb1ca0732017-02-01 08:38:12 -08001010 }
sprangc5d62e22017-04-02 23:53:04 -07001011
sprangc5d62e22017-04-02 23:53:04 -07001012 switch (degradation_preference_) {
asaperssonf7e294d2017-06-13 23:25:22 -07001013 case VideoSendStream::DegradationPreference::kBalanced: {
1014 // Try scale up framerate, if higher.
1015 int fps = MaxFps(last_frame_info_->pixel_count());
1016 if (source_proxy_->IncreaseFramerate(fps)) {
1017 GetAdaptCounter().DecrementFramerate(reason, fps);
1018 // Reset framerate in case of fewer fps steps down than up.
1019 if (adapt_counter.FramerateCount() == 0 &&
1020 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001021 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001022 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1023 }
1024 break;
1025 }
1026 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001027 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001028 }
asapersson13874762017-06-07 00:01:02 -07001029 case VideoSendStream::DegradationPreference::kMaintainFramerate: {
1030 // Scale up resolution.
1031 int pixel_count = adaptation_request.input_pixel_count_;
1032 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001033 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001034 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001035 }
asapersson13874762017-06-07 00:01:02 -07001036 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1037 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001038 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001039 break;
asapersson13874762017-06-07 00:01:02 -07001040 }
1041 case VideoSendStream::DegradationPreference::kMaintainResolution: {
1042 // Scale up framerate.
1043 int fps = adaptation_request.framerate_fps_;
1044 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001045 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001046 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001047 }
sprangfda496a2017-06-15 04:21:07 -07001048
1049 const int requested_framerate =
1050 source_proxy_->RequestHigherFramerateThan(fps);
1051 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001052 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001053 return;
sprangfda496a2017-06-15 04:21:07 -07001054 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001055 overuse_detector_->OnTargetFramerateUpdated(
1056 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001057 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001058 break;
asapersson13874762017-06-07 00:01:02 -07001059 }
hbos8d609f62017-04-10 07:39:05 -07001060 case VideoSendStream::DegradationPreference::kDegradationDisabled:
asaperssonf7e294d2017-06-13 23:25:22 -07001061 return;
sprangc5d62e22017-04-02 23:53:04 -07001062 }
1063
asaperssond0de2952017-04-21 01:47:31 -07001064 last_adaptation_request_.emplace(adaptation_request);
1065
asapersson09f05612017-05-15 23:40:18 -07001066 UpdateAdaptationStats(reason);
1067
Mirko Bonadei675513b2017-11-09 11:09:25 +01001068 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001069}
1070
mflodmancc3d4422017-08-03 08:27:51 -07001071void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001072 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001073 case kCpu:
asapersson09f05612017-05-15 23:40:18 -07001074 stats_proxy_->OnCpuAdaptationChanged(GetActiveCounts(kCpu),
1075 GetActiveCounts(kQuality));
1076 break;
1077 case kQuality:
1078 stats_proxy_->OnQualityAdaptationChanged(GetActiveCounts(kCpu),
1079 GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001080 break;
1081 }
perkj26091b12016-09-01 01:17:40 -07001082}
1083
mflodmancc3d4422017-08-03 08:27:51 -07001084VideoStreamEncoder::AdaptCounts VideoStreamEncoder::GetActiveCounts(
1085 AdaptReason reason) {
1086 VideoStreamEncoder::AdaptCounts counts =
1087 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001088 switch (reason) {
1089 case kCpu:
1090 if (!IsFramerateScalingEnabled(degradation_preference_))
1091 counts.fps = -1;
1092 if (!IsResolutionScalingEnabled(degradation_preference_))
1093 counts.resolution = -1;
1094 break;
1095 case kQuality:
1096 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1097 !quality_scaler_) {
1098 counts.fps = -1;
1099 }
1100 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1101 !quality_scaler_) {
1102 counts.resolution = -1;
1103 }
1104 break;
sprangc5d62e22017-04-02 23:53:04 -07001105 }
asapersson09f05612017-05-15 23:40:18 -07001106 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001107}
1108
mflodmancc3d4422017-08-03 08:27:51 -07001109VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001110 return adapt_counters_[degradation_preference_];
1111}
1112
mflodmancc3d4422017-08-03 08:27:51 -07001113const VideoStreamEncoder::AdaptCounter&
1114VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001115 return adapt_counters_[degradation_preference_];
1116}
1117
1118// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001119VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001120 fps_counters_.resize(kScaleReasonSize);
1121 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001122 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001123}
1124
mflodmancc3d4422017-08-03 08:27:51 -07001125VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001126
mflodmancc3d4422017-08-03 08:27:51 -07001127std::string VideoStreamEncoder::AdaptCounter::ToString() const {
asapersson09f05612017-05-15 23:40:18 -07001128 std::stringstream ss;
1129 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1130 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
1131 return ss.str();
1132}
1133
mflodmancc3d4422017-08-03 08:27:51 -07001134VideoStreamEncoder::AdaptCounts VideoStreamEncoder::AdaptCounter::Counts(
1135 int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001136 AdaptCounts counts;
1137 counts.fps = fps_counters_[reason];
1138 counts.resolution = resolution_counters_[reason];
1139 return counts;
1140}
1141
mflodmancc3d4422017-08-03 08:27:51 -07001142void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001143 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001144}
1145
mflodmancc3d4422017-08-03 08:27:51 -07001146void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001147 ++(resolution_counters_[reason]);
1148}
1149
mflodmancc3d4422017-08-03 08:27:51 -07001150void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001151 if (fps_counters_[reason] == 0) {
1152 // Balanced mode: Adapt up is in a different order, switch reason.
1153 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1154 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1155 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1156 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1157 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1158 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1159 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1160 MoveCount(&resolution_counters_, reason);
1161 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1162 }
1163 --(fps_counters_[reason]);
1164 RTC_DCHECK_GE(fps_counters_[reason], 0);
1165}
1166
mflodmancc3d4422017-08-03 08:27:51 -07001167void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001168 if (resolution_counters_[reason] == 0) {
1169 // Balanced mode: Adapt up is in a different order, switch reason.
1170 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1171 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1172 MoveCount(&fps_counters_, reason);
1173 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1174 }
1175 --(resolution_counters_[reason]);
1176 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1177}
1178
mflodmancc3d4422017-08-03 08:27:51 -07001179void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1180 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07001181 DecrementFramerate(reason);
1182 // Reset if at max fps (i.e. in case of fewer steps up than down).
1183 if (cur_fps == std::numeric_limits<int>::max())
1184 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-15 23:40:18 -07001185}
1186
mflodmancc3d4422017-08-03 08:27:51 -07001187int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07001188 return Count(fps_counters_);
1189}
1190
mflodmancc3d4422017-08-03 08:27:51 -07001191int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07001192 return Count(resolution_counters_);
1193}
1194
mflodmancc3d4422017-08-03 08:27:51 -07001195int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001196 return fps_counters_[reason];
1197}
1198
mflodmancc3d4422017-08-03 08:27:51 -07001199int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001200 return resolution_counters_[reason];
1201}
1202
mflodmancc3d4422017-08-03 08:27:51 -07001203int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001204 return FramerateCount(reason) + ResolutionCount(reason);
1205}
1206
mflodmancc3d4422017-08-03 08:27:51 -07001207int VideoStreamEncoder::AdaptCounter::Count(
1208 const std::vector<int>& counters) const {
asapersson09f05612017-05-15 23:40:18 -07001209 return std::accumulate(counters.begin(), counters.end(), 0);
1210}
1211
mflodmancc3d4422017-08-03 08:27:51 -07001212void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1213 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001214 int to_reason = (from_reason + 1) % kScaleReasonSize;
1215 ++((*counters)[to_reason]);
1216 --((*counters)[from_reason]);
1217}
1218
mflodmancc3d4422017-08-03 08:27:51 -07001219std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07001220 const std::vector<int>& counters) const {
1221 std::stringstream ss;
1222 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1223 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07001224 }
asapersson09f05612017-05-15 23:40:18 -07001225 return ss.str();
sprangc5d62e22017-04-02 23:53:04 -07001226}
1227
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001228} // namespace webrtc