blob: 961a38e88112b7f6cb63194abc0b3f9bc906a8dc [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"
21#include "modules/pacing/paced_sender.h"
22#include "modules/video_coding/codecs/vp8/temporal_layers.h"
23#include "modules/video_coding/include/video_codec_initializer.h"
24#include "modules/video_coding/include/video_coding.h"
25#include "modules/video_coding/include/video_coding_defines.h"
26#include "rtc_base/arraysize.h"
27#include "rtc_base/checks.h"
28#include "rtc_base/location.h"
29#include "rtc_base/logging.h"
30#include "rtc_base/timeutils.h"
31#include "rtc_base/trace_event.h"
32#include "video/overuse_frame_detector.h"
33#include "video/send_statistics_proxy.h"
nisseea3a7982017-05-15 02:42:11 -070034
niklase@google.com470e71d2011-07-07 08:21:25 +000035namespace webrtc {
36
perkj26091b12016-09-01 01:17:40 -070037namespace {
sprangb1ca0732017-02-01 08:38:12 -080038
asapersson6ffb67d2016-09-12 00:10:45 -070039// Time interval for logging frame counts.
40const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070041const int kMinFramerateFps = 2;
sprangfda496a2017-06-15 04:21:07 -070042const int kMaxFramerateFps = 120;
perkj26091b12016-09-01 01:17:40 -070043
kthelgason2bc68642017-02-07 07:02:22 -080044// The maximum number of frames to drop at beginning of stream
45// to try and achieve desired bitrate.
46const int kMaxInitialFramedrop = 4;
47
kthelgason2bc68642017-02-07 07:02:22 -080048uint32_t MaximumFrameSizeForBitrate(uint32_t kbps) {
49 if (kbps > 0) {
50 if (kbps < 300 /* qvga */) {
51 return 320 * 240;
52 } else if (kbps < 500 /* vga */) {
53 return 640 * 480;
54 }
55 }
56 return std::numeric_limits<uint32_t>::max();
57}
58
asaperssonf7e294d2017-06-13 23:25:22 -070059// Initial limits for kBalanced degradation preference.
60int MinFps(int pixels) {
61 if (pixels <= 320 * 240) {
62 return 7;
63 } else if (pixels <= 480 * 270) {
64 return 10;
65 } else if (pixels <= 640 * 480) {
66 return 15;
67 } else {
68 return std::numeric_limits<int>::max();
69 }
70}
71
72int MaxFps(int pixels) {
73 if (pixels <= 320 * 240) {
74 return 10;
75 } else if (pixels <= 480 * 270) {
76 return 15;
77 } else {
78 return std::numeric_limits<int>::max();
79 }
80}
81
asapersson09f05612017-05-15 23:40:18 -070082bool IsResolutionScalingEnabled(
83 VideoSendStream::DegradationPreference degradation_preference) {
84 return degradation_preference ==
85 VideoSendStream::DegradationPreference::kMaintainFramerate ||
86 degradation_preference ==
87 VideoSendStream::DegradationPreference::kBalanced;
88}
89
90bool IsFramerateScalingEnabled(
91 VideoSendStream::DegradationPreference degradation_preference) {
92 return degradation_preference ==
93 VideoSendStream::DegradationPreference::kMaintainResolution ||
94 degradation_preference ==
95 VideoSendStream::DegradationPreference::kBalanced;
96}
97
perkj26091b12016-09-01 01:17:40 -070098} // namespace
99
mflodmancc3d4422017-08-03 08:27:51 -0700100class VideoStreamEncoder::ConfigureEncoderTask : public rtc::QueuedTask {
Pera48ddb72016-09-29 11:48:50 +0200101 public:
mflodmancc3d4422017-08-03 08:27:51 -0700102 ConfigureEncoderTask(VideoStreamEncoder* video_stream_encoder,
Pera48ddb72016-09-29 11:48:50 +0200103 VideoEncoderConfig config,
asapersson5f7226f2016-11-25 04:37:00 -0800104 size_t max_data_payload_length,
105 bool nack_enabled)
mflodmancc3d4422017-08-03 08:27:51 -0700106 : video_stream_encoder_(video_stream_encoder),
Pera48ddb72016-09-29 11:48:50 +0200107 config_(std::move(config)),
asapersson5f7226f2016-11-25 04:37:00 -0800108 max_data_payload_length_(max_data_payload_length),
109 nack_enabled_(nack_enabled) {}
Pera48ddb72016-09-29 11:48:50 +0200110
111 private:
112 bool Run() override {
mflodmancc3d4422017-08-03 08:27:51 -0700113 video_stream_encoder_->ConfigureEncoderOnTaskQueue(
asapersson5f7226f2016-11-25 04:37:00 -0800114 std::move(config_), max_data_payload_length_, nack_enabled_);
Pera48ddb72016-09-29 11:48:50 +0200115 return true;
116 }
117
mflodmancc3d4422017-08-03 08:27:51 -0700118 VideoStreamEncoder* const video_stream_encoder_;
Pera48ddb72016-09-29 11:48:50 +0200119 VideoEncoderConfig config_;
120 size_t max_data_payload_length_;
asapersson5f7226f2016-11-25 04:37:00 -0800121 bool nack_enabled_;
Pera48ddb72016-09-29 11:48:50 +0200122};
123
mflodmancc3d4422017-08-03 08:27:51 -0700124class VideoStreamEncoder::EncodeTask : public rtc::QueuedTask {
perkj26091b12016-09-01 01:17:40 -0700125 public:
perkjd52063f2016-09-07 06:32:18 -0700126 EncodeTask(const VideoFrame& frame,
mflodmancc3d4422017-08-03 08:27:51 -0700127 VideoStreamEncoder* video_stream_encoder,
nissee0e3bdf2017-01-18 02:16:20 -0800128 int64_t time_when_posted_us,
asapersson6ffb67d2016-09-12 00:10:45 -0700129 bool log_stats)
nissedf2ceb82016-12-15 06:29:53 -0800130 : frame_(frame),
mflodmancc3d4422017-08-03 08:27:51 -0700131 video_stream_encoder_(video_stream_encoder),
nissee0e3bdf2017-01-18 02:16:20 -0800132 time_when_posted_us_(time_when_posted_us),
asapersson6ffb67d2016-09-12 00:10:45 -0700133 log_stats_(log_stats) {
mflodmancc3d4422017-08-03 08:27:51 -0700134 ++video_stream_encoder_->posted_frames_waiting_for_encode_;
perkj26091b12016-09-01 01:17:40 -0700135 }
136
137 private:
138 bool Run() override {
mflodmancc3d4422017-08-03 08:27:51 -0700139 RTC_DCHECK_RUN_ON(&video_stream_encoder_->encoder_queue_);
mflodmancc3d4422017-08-03 08:27:51 -0700140 video_stream_encoder_->stats_proxy_->OnIncomingFrame(frame_.width(),
141 frame_.height());
142 ++video_stream_encoder_->captured_frame_count_;
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700143 const int posted_frames_waiting_for_encode =
144 video_stream_encoder_->posted_frames_waiting_for_encode_.fetch_sub(1);
145 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
146 if (posted_frames_waiting_for_encode == 1) {
mflodmancc3d4422017-08-03 08:27:51 -0700147 video_stream_encoder_->EncodeVideoFrame(frame_, time_when_posted_us_);
perkj26091b12016-09-01 01:17:40 -0700148 } else {
149 // There is a newer frame in flight. Do not encode this frame.
150 LOG(LS_VERBOSE)
151 << "Incoming frame dropped due to that the encoder is blocked.";
mflodmancc3d4422017-08-03 08:27:51 -0700152 ++video_stream_encoder_->dropped_frame_count_;
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200153 video_stream_encoder_->stats_proxy_->OnFrameDroppedInEncoderQueue();
asapersson6ffb67d2016-09-12 00:10:45 -0700154 }
155 if (log_stats_) {
156 LOG(LS_INFO) << "Number of frames: captured "
mflodmancc3d4422017-08-03 08:27:51 -0700157 << video_stream_encoder_->captured_frame_count_
asapersson6ffb67d2016-09-12 00:10:45 -0700158 << ", dropped (due to encoder blocked) "
mflodmancc3d4422017-08-03 08:27:51 -0700159 << video_stream_encoder_->dropped_frame_count_
160 << ", interval_ms "
asapersson6ffb67d2016-09-12 00:10:45 -0700161 << kFrameLogIntervalMs;
mflodmancc3d4422017-08-03 08:27:51 -0700162 video_stream_encoder_->captured_frame_count_ = 0;
163 video_stream_encoder_->dropped_frame_count_ = 0;
perkj26091b12016-09-01 01:17:40 -0700164 }
165 return true;
166 }
167 VideoFrame frame_;
mflodmancc3d4422017-08-03 08:27:51 -0700168 VideoStreamEncoder* const video_stream_encoder_;
nissee0e3bdf2017-01-18 02:16:20 -0800169 const int64_t time_when_posted_us_;
asapersson6ffb67d2016-09-12 00:10:45 -0700170 const bool log_stats_;
perkj26091b12016-09-01 01:17:40 -0700171};
172
perkja49cbd32016-09-16 07:53:41 -0700173// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700174// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
175// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700176// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700177class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700178 public:
mflodmancc3d4422017-08-03 08:27:51 -0700179 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
180 : video_stream_encoder_(video_stream_encoder),
hbos8d609f62017-04-10 07:39:05 -0700181 degradation_preference_(
182 VideoSendStream::DegradationPreference::kDegradationDisabled),
perkj803d97f2016-11-01 11:45:46 -0700183 source_(nullptr) {}
perkja49cbd32016-09-16 07:53:41 -0700184
hbos8d609f62017-04-10 07:39:05 -0700185 void SetSource(
186 rtc::VideoSourceInterface<VideoFrame>* source,
187 const VideoSendStream::DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700188 // Called on libjingle's worker thread.
perkja49cbd32016-09-16 07:53:41 -0700189 RTC_DCHECK_CALLED_SEQUENTIALLY(&main_checker_);
190 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700191 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700192 {
193 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700194 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700195 old_source = source_;
196 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700197 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700198 }
199
200 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700201 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700202 }
203
204 if (!source) {
205 return;
206 }
207
mflodmancc3d4422017-08-03 08:27:51 -0700208 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700209 }
210
perkj803d97f2016-11-01 11:45:46 -0700211 void SetWantsRotationApplied(bool rotation_applied) {
212 rtc::CritScope lock(&crit_);
213 sink_wants_.rotation_applied = rotation_applied;
sprangc5d62e22017-04-02 23:53:04 -0700214 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700215 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
sprangc5d62e22017-04-02 23:53:04 -0700216 }
217
sprangfda496a2017-06-15 04:21:07 -0700218 rtc::VideoSinkWants GetActiveSinkWants() {
219 rtc::CritScope lock(&crit_);
220 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700221 }
222
asaperssonf7e294d2017-06-13 23:25:22 -0700223 void ResetPixelFpsCount() {
224 rtc::CritScope lock(&crit_);
225 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
226 sink_wants_.target_pixel_count.reset();
227 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
228 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700229 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
asaperssonf7e294d2017-06-13 23:25:22 -0700230 }
231
asapersson142fcc92017-08-17 08:58:54 -0700232 bool RequestResolutionLowerThan(int pixel_count, int min_pixels_per_frame) {
perkj803d97f2016-11-01 11:45:46 -0700233 // Called on the encoder task queue.
234 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700235 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700236 // This can happen since |degradation_preference_| is set on libjingle's
237 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700238 return false;
perkj803d97f2016-11-01 11:45:46 -0700239 }
asapersson13874762017-06-07 00:01:02 -0700240 // The input video frame size will have a resolution less than or equal to
241 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800242 const int pixels_wanted = (pixel_count * 3) / 5;
asapersson142fcc92017-08-17 08:58:54 -0700243 if (pixels_wanted < min_pixels_per_frame ||
asapersson13874762017-06-07 00:01:02 -0700244 pixels_wanted >= sink_wants_.max_pixel_count) {
asaperssond0de2952017-04-21 01:47:31 -0700245 return false;
asapersson13874762017-06-07 00:01:02 -0700246 }
247 LOG(LS_INFO) << "Scaling down resolution, max pixels: " << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700248 sink_wants_.max_pixel_count = pixels_wanted;
sprang84a37592017-02-10 07:04:27 -0800249 sink_wants_.target_pixel_count = rtc::Optional<int>();
mflodmancc3d4422017-08-03 08:27:51 -0700250 source_->AddOrUpdateSink(video_stream_encoder_,
251 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700252 return true;
sprangc5d62e22017-04-02 23:53:04 -0700253 }
254
sprangfda496a2017-06-15 04:21:07 -0700255 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700256 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700257 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700258 int framerate_wanted = (fps * 2) / 3;
259 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700260 }
261
asapersson13874762017-06-07 00:01:02 -0700262 bool RequestHigherResolutionThan(int pixel_count) {
263 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700264 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700265 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700266 // This can happen since |degradation_preference_| is set on libjingle's
267 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700268 return false;
perkj803d97f2016-11-01 11:45:46 -0700269 }
asapersson13874762017-06-07 00:01:02 -0700270 int max_pixels_wanted = pixel_count;
271 if (max_pixels_wanted != std::numeric_limits<int>::max())
272 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700273
asapersson13874762017-06-07 00:01:02 -0700274 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
275 return false;
276
277 sink_wants_.max_pixel_count = max_pixels_wanted;
278 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700279 // Remove any constraints.
280 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700281 } else {
282 // On step down we request at most 3/5 the pixel count of the previous
283 // resolution, so in order to take "one step up" we request a resolution
284 // as close as possible to 5/3 of the current resolution. The actual pixel
285 // count selected depends on the capabilities of the source. In order to
286 // not take a too large step up, we cap the requested pixel count to be at
287 // most four time the current number of pixels.
288 sink_wants_.target_pixel_count =
289 rtc::Optional<int>((pixel_count * 5) / 3);
sprangc5d62e22017-04-02 23:53:04 -0700290 }
asapersson13874762017-06-07 00:01:02 -0700291 LOG(LS_INFO) << "Scaling up resolution, max pixels: " << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700292 source_->AddOrUpdateSink(video_stream_encoder_,
293 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700294 return true;
sprangc5d62e22017-04-02 23:53:04 -0700295 }
296
sprangfda496a2017-06-15 04:21:07 -0700297 // Request upgrade in framerate. Returns the new requested frame, or -1 if
298 // no change requested. Note that maxint may be returned if limits due to
299 // adaptation requests are removed completely. In that case, consider
300 // |max_framerate_| to be the current limit (assuming the capturer complies).
301 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700302 // Called on the encoder task queue.
303 // The input frame rate will be scaled up to the last step, with rounding.
304 int framerate_wanted = fps;
305 if (fps != std::numeric_limits<int>::max())
306 framerate_wanted = (fps * 3) / 2;
307
sprangfda496a2017-06-15 04:21:07 -0700308 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700309 }
310
311 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700312 // Called on the encoder task queue.
313 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700314 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
315 return false;
316
317 const int fps_wanted = std::max(kMinFramerateFps, fps);
318 if (fps_wanted >= sink_wants_.max_framerate_fps)
319 return false;
320
321 LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
322 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700323 source_->AddOrUpdateSink(video_stream_encoder_,
324 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700325 return true;
326 }
327
328 bool IncreaseFramerate(int fps) {
329 // Called on the encoder task queue.
330 rtc::CritScope lock(&crit_);
331 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
332 return false;
333
334 const int fps_wanted = std::max(kMinFramerateFps, fps);
335 if (fps_wanted <= sink_wants_.max_framerate_fps)
336 return false;
337
338 LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
339 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700340 source_->AddOrUpdateSink(video_stream_encoder_,
341 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700342 return true;
perkj803d97f2016-11-01 11:45:46 -0700343 }
344
perkja49cbd32016-09-16 07:53:41 -0700345 private:
sprangfda496a2017-06-15 04:21:07 -0700346 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700347 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700348 rtc::VideoSinkWants wants = sink_wants_;
349 // Clear any constraints from the current sink wants that don't apply to
350 // the used degradation_preference.
351 switch (degradation_preference_) {
352 case VideoSendStream::DegradationPreference::kBalanced:
353 break;
354 case VideoSendStream::DegradationPreference::kMaintainFramerate:
355 wants.max_framerate_fps = std::numeric_limits<int>::max();
356 break;
357 case VideoSendStream::DegradationPreference::kMaintainResolution:
358 wants.max_pixel_count = std::numeric_limits<int>::max();
359 wants.target_pixel_count.reset();
360 break;
361 case VideoSendStream::DegradationPreference::kDegradationDisabled:
362 wants.max_pixel_count = std::numeric_limits<int>::max();
363 wants.target_pixel_count.reset();
364 wants.max_framerate_fps = std::numeric_limits<int>::max();
365 }
366 return wants;
367 }
368
perkja49cbd32016-09-16 07:53:41 -0700369 rtc::CriticalSection crit_;
370 rtc::SequencedTaskChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700371 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700372 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
hbos8d609f62017-04-10 07:39:05 -0700373 VideoSendStream::DegradationPreference degradation_preference_
danilchapa37de392017-09-09 04:17:22 -0700374 RTC_GUARDED_BY(&crit_);
375 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700376
377 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
378};
379
Ã…sa Persson0122e842017-10-16 12:19:23 +0200380VideoStreamEncoder::VideoStreamEncoder(
381 uint32_t number_of_cores,
382 SendStatisticsProxy* stats_proxy,
383 const VideoSendStream::Config::EncoderSettings& settings,
384 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
385 EncodedFrameObserver* encoder_timing,
386 std::unique_ptr<OveruseFrameDetector> overuse_detector)
perkj26091b12016-09-01 01:17:40 -0700387 : shutdown_event_(true /* manual_reset */, false),
388 number_of_cores_(number_of_cores),
kthelgason2bc68642017-02-07 07:02:22 -0800389 initial_rampup_(0),
perkja49cbd32016-09-16 07:53:41 -0700390 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200391 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700392 settings_(settings),
kthelgason1cdddc92017-08-24 03:52:48 -0700393 codec_type_(PayloadStringToCodecType(settings.payload_name)),
Ã…sa Persson0122e842017-10-16 12:19:23 +0200394 video_sender_(Clock::GetRealTimeClock(), this, nullptr),
sprangfda496a2017-06-15 04:21:07 -0700395 overuse_detector_(
396 overuse_detector.get()
397 ? overuse_detector.release()
398 : new OveruseFrameDetector(
399 GetCpuOveruseOptions(settings.full_overuse_time),
400 this,
401 encoder_timing,
402 stats_proxy)),
Peter Boström7083e112015-09-22 16:28:51 +0200403 stats_proxy_(stats_proxy),
perkj26091b12016-09-01 01:17:40 -0700404 pre_encode_callback_(pre_encode_callback),
405 module_process_thread_(nullptr),
sprangfda496a2017-06-15 04:21:07 -0700406 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700407 pending_encoder_reconfiguration_(false),
perkj26091b12016-09-01 01:17:40 -0700408 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 11:48:50 +0200409 max_data_payload_length_(0),
asapersson5f7226f2016-11-25 04:37:00 -0800410 nack_enabled_(false),
pbos@webrtc.org143451d2015-03-18 14:40:03 +0000411 last_observed_bitrate_bps_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000412 encoder_paused_and_dropped_frame_(false),
perkj26091b12016-09-01 01:17:40 -0700413 clock_(Clock::GetRealTimeClock()),
hbos8d609f62017-04-10 07:39:05 -0700414 degradation_preference_(
415 VideoSendStream::DegradationPreference::kDegradationDisabled),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700416 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700417 last_captured_timestamp_(0),
418 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
419 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700420 last_frame_log_ms_(clock_->TimeInMilliseconds()),
421 captured_frame_count_(0),
422 dropped_frame_count_(0),
sprang1a646ee2016-12-01 06:34:11 -0800423 bitrate_observer_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700424 encoder_queue_("EncoderQueue") {
sprang552c7c72017-02-13 04:41:45 -0800425 RTC_DCHECK(stats_proxy);
perkj803d97f2016-11-01 11:45:46 -0700426 encoder_queue_.PostTask([this] {
perkj26091b12016-09-01 01:17:40 -0700427 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700428 overuse_detector_->StartCheckForOveruse();
perkj26091b12016-09-01 01:17:40 -0700429 video_sender_.RegisterExternalEncoder(
430 settings_.encoder, settings_.payload_type, settings_.internal_source);
431 });
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000432}
433
mflodmancc3d4422017-08-03 08:27:51 -0700434VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700435 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700436 RTC_DCHECK(shutdown_event_.Wait(0))
437 << "Must call ::Stop() before destruction.";
438}
439
sprangfda496a2017-06-15 04:21:07 -0700440// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
441// pipelining encoders better (multiple input frames before something comes
442// out). This should effectively turn off CPU adaptations for systems that
443// remotely cope with the load right now.
mflodmancc3d4422017-08-03 08:27:51 -0700444CpuOveruseOptions VideoStreamEncoder::GetCpuOveruseOptions(
445 bool full_overuse_time) {
sprangfda496a2017-06-15 04:21:07 -0700446 CpuOveruseOptions options;
447 if (full_overuse_time) {
448 options.low_encode_usage_threshold_percent = 150;
449 options.high_encode_usage_threshold_percent = 200;
450 }
451 return options;
452}
453
mflodmancc3d4422017-08-03 08:27:51 -0700454void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700455 RTC_DCHECK_RUN_ON(&thread_checker_);
hbos8d609f62017-04-10 07:39:05 -0700456 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700457 encoder_queue_.PostTask([this] {
458 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700459 overuse_detector_->StopCheckForOveruse();
Erik Språng08127a92016-11-16 16:41:30 +0100460 rate_allocator_.reset();
sprang1a646ee2016-12-01 06:34:11 -0800461 bitrate_observer_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700462 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type,
463 false);
kthelgason876222f2016-11-29 01:44:11 -0800464 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700465 shutdown_event_.Set();
466 });
467
468 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700469}
470
mflodmancc3d4422017-08-03 08:27:51 -0700471void VideoStreamEncoder::RegisterProcessThread(
472 ProcessThread* module_process_thread) {
perkja49cbd32016-09-16 07:53:41 -0700473 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700474 RTC_DCHECK(!module_process_thread_);
475 module_process_thread_ = module_process_thread;
tommidea489f2017-03-03 03:20:24 -0800476 module_process_thread_->RegisterModule(&video_sender_, RTC_FROM_HERE);
perkj26091b12016-09-01 01:17:40 -0700477 module_process_thread_checker_.DetachFromThread();
478}
479
mflodmancc3d4422017-08-03 08:27:51 -0700480void VideoStreamEncoder::DeRegisterProcessThread() {
perkja49cbd32016-09-16 07:53:41 -0700481 RTC_DCHECK_RUN_ON(&thread_checker_);
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200482 module_process_thread_->DeRegisterModule(&video_sender_);
asapersson@webrtc.org96dc6852014-11-03 14:40:38 +0000483}
484
mflodmancc3d4422017-08-03 08:27:51 -0700485void VideoStreamEncoder::SetBitrateObserver(
sprang1a646ee2016-12-01 06:34:11 -0800486 VideoBitrateAllocationObserver* bitrate_observer) {
487 RTC_DCHECK_RUN_ON(&thread_checker_);
488 encoder_queue_.PostTask([this, bitrate_observer] {
489 RTC_DCHECK_RUN_ON(&encoder_queue_);
490 RTC_DCHECK(!bitrate_observer_);
491 bitrate_observer_ = bitrate_observer;
492 });
493}
494
mflodmancc3d4422017-08-03 08:27:51 -0700495void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700496 rtc::VideoSourceInterface<VideoFrame>* source,
asapersson09f05612017-05-15 23:40:18 -0700497 const VideoSendStream::DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700498 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700499 source_proxy_->SetSource(source, degradation_preference);
500 encoder_queue_.PostTask([this, degradation_preference] {
501 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700502 if (degradation_preference_ != degradation_preference) {
503 // Reset adaptation state, so that we're not tricked into thinking there's
504 // an already pending request of the same type.
505 last_adaptation_request_.reset();
asaperssonf7e294d2017-06-13 23:25:22 -0700506 if (degradation_preference ==
507 VideoSendStream::DegradationPreference::kBalanced ||
508 degradation_preference_ ==
509 VideoSendStream::DegradationPreference::kBalanced) {
510 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
511 // AdaptCounter for all modes.
512 source_proxy_->ResetPixelFpsCount();
513 adapt_counters_.clear();
514 }
sprangc5d62e22017-04-02 23:53:04 -0700515 }
sprangb1ca0732017-02-01 08:38:12 -0800516 degradation_preference_ = degradation_preference;
asapersson91914e22017-06-01 00:34:08 -0700517 bool allow_scaling = IsResolutionScalingEnabled(degradation_preference_);
sprangc5d62e22017-04-02 23:53:04 -0700518 initial_rampup_ = allow_scaling ? 0 : kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -0800519 ConfigureQualityScaler();
sprangfda496a2017-06-15 04:21:07 -0700520 if (!IsFramerateScalingEnabled(degradation_preference) &&
521 max_framerate_ != -1) {
522 // If frame rate scaling is no longer allowed, remove any potential
523 // allowance for longer frame intervals.
524 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
525 }
perkj803d97f2016-11-01 11:45:46 -0700526 });
perkja49cbd32016-09-16 07:53:41 -0700527}
528
mflodmancc3d4422017-08-03 08:27:51 -0700529void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700530 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700531 encoder_queue_.PostTask([this, sink] {
532 RTC_DCHECK_RUN_ON(&encoder_queue_);
533 sink_ = sink;
534 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000535}
536
mflodmancc3d4422017-08-03 08:27:51 -0700537void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700538 encoder_queue_.PostTask([this, start_bitrate_bps] {
539 RTC_DCHECK_RUN_ON(&encoder_queue_);
540 encoder_start_bitrate_bps_ = start_bitrate_bps;
541 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000542}
Peter Boström00b9d212016-05-19 16:59:03 +0200543
mflodmancc3d4422017-08-03 08:27:51 -0700544void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
545 size_t max_data_payload_length,
546 bool nack_enabled) {
Pera48ddb72016-09-29 11:48:50 +0200547 encoder_queue_.PostTask(
548 std::unique_ptr<rtc::QueuedTask>(new ConfigureEncoderTask(
asapersson5f7226f2016-11-25 04:37:00 -0800549 this, std::move(config), max_data_payload_length, nack_enabled)));
perkj26091b12016-09-01 01:17:40 -0700550}
551
mflodmancc3d4422017-08-03 08:27:51 -0700552void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
553 VideoEncoderConfig config,
554 size_t max_data_payload_length,
555 bool nack_enabled) {
perkj26091b12016-09-01 01:17:40 -0700556 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700557 RTC_DCHECK(sink_);
perkjfa10b552016-10-02 23:45:26 -0700558 LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200559
560 max_data_payload_length_ = max_data_payload_length;
asapersson5f7226f2016-11-25 04:37:00 -0800561 nack_enabled_ = nack_enabled;
Pera48ddb72016-09-29 11:48:50 +0200562 encoder_config_ = std::move(config);
perkjfa10b552016-10-02 23:45:26 -0700563 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200564
perkjfa10b552016-10-02 23:45:26 -0700565 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100566 // if the frame resolution is known. Otherwise, the reconfiguration is
567 // deferred until the next frame to minimize the number of reconfigurations.
568 // The codec configuration depends on incoming video frame size.
569 if (last_frame_info_) {
570 ReconfigureEncoder();
571 } else if (settings_.internal_source) {
brandtra3241662017-05-03 04:55:51 -0700572 last_frame_info_ =
573 rtc::Optional<VideoFrameInfo>(VideoFrameInfo(176, 144, false));
perkjfa10b552016-10-02 23:45:26 -0700574 ReconfigureEncoder();
575 }
576}
perkj26091b12016-09-01 01:17:40 -0700577
mflodmancc3d4422017-08-03 08:27:51 -0700578void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700579 RTC_DCHECK_RUN_ON(&encoder_queue_);
580 RTC_DCHECK(pending_encoder_reconfiguration_);
581 std::vector<VideoStream> streams =
582 encoder_config_.video_stream_factory->CreateEncoderStreams(
583 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700584
ilnik6b826ef2017-06-16 06:53:48 -0700585 // TODO(ilnik): If configured resolution is significantly less than provided,
586 // e.g. because there are not enough SSRCs for all simulcast streams,
587 // signal new resolutions via SinkWants to video source.
588
589 // Stream dimensions may be not equal to given because of a simulcast
590 // restrictions.
591 int highest_stream_width = static_cast<int>(streams.back().width);
592 int highest_stream_height = static_cast<int>(streams.back().height);
593 // Dimension may be reduced to be, e.g. divisible by 4.
594 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
595 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
596 crop_width_ = last_frame_info_->width - highest_stream_width;
597 crop_height_ = last_frame_info_->height - highest_stream_height;
598
Erik Språng08127a92016-11-16 16:41:30 +0100599 VideoCodec codec;
600 if (!VideoCodecInitializer::SetupCodec(encoder_config_, settings_, streams,
asapersson5f7226f2016-11-25 04:37:00 -0800601 nack_enabled_, &codec,
602 &rate_allocator_)) {
Erik Språng08127a92016-11-16 16:41:30 +0100603 LOG(LS_ERROR) << "Failed to create encoder configuration.";
604 }
perkjfa10b552016-10-02 23:45:26 -0700605
606 codec.startBitrate =
607 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
608 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
609 codec.expect_encode_from_texture = last_frame_info_->is_texture;
sprangfda496a2017-06-15 04:21:07 -0700610 max_framerate_ = codec.maxFramerate;
611 RTC_DCHECK_LE(max_framerate_, kMaxFramerateFps);
Stefan Holmere5904162015-03-26 11:11:06 +0100612
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200613 bool success = video_sender_.RegisterSendCodec(
perkjfa10b552016-10-02 23:45:26 -0700614 &codec, number_of_cores_,
615 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
Peter Boström905f8e72016-03-02 16:59:56 +0100616 if (!success) {
617 LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 08:24:59 -0700618 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000619 }
Peter Boström905f8e72016-03-02 16:59:56 +0100620
ilnik35b7de42017-03-15 04:24:21 -0700621 video_sender_.UpdateChannelParemeters(rate_allocator_.get(),
622 bitrate_observer_);
623
sprangfda496a2017-06-15 04:21:07 -0700624 // Get the current actual framerate, as measured by the stats proxy. This is
625 // used to get the correct bitrate layer allocation.
626 int current_framerate = stats_proxy_->GetSendFrameRate();
627 if (current_framerate == 0)
628 current_framerate = codec.maxFramerate;
sprang552c7c72017-02-13 04:41:45 -0800629 stats_proxy_->OnEncoderReconfigured(
sprangfda496a2017-06-15 04:21:07 -0700630 encoder_config_,
631 rate_allocator_.get()
632 ? rate_allocator_->GetPreferredBitrateBps(current_framerate)
633 : codec.maxBitrate);
Per512ecb32016-09-23 15:52:06 +0200634
perkjfa10b552016-10-02 23:45:26 -0700635 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100636
Pera48ddb72016-09-29 11:48:50 +0200637 sink_->OnEncoderConfigurationChanged(
perkjfa10b552016-10-02 23:45:26 -0700638 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800639
sprangfda496a2017-06-15 04:21:07 -0700640 // Get the current target framerate, ie the maximum framerate as specified by
641 // the current codec configuration, or any limit imposed by cpu adaption in
642 // maintain-resolution or balanced mode. This is used to make sure overuse
643 // detection doesn't needlessly trigger in low and/or variable framerate
644 // scenarios.
645 int target_framerate = std::min(
646 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
647 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
648
kthelgason2bc68642017-02-07 07:02:22 -0800649 ConfigureQualityScaler();
650}
651
mflodmancc3d4422017-08-03 08:27:51 -0700652void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 07:02:22 -0800653 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800654 const auto scaling_settings = settings_.encoder->GetScalingSettings();
asapersson36e9eb42017-03-31 05:29:12 -0700655 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700656 IsResolutionScalingEnabled(degradation_preference_) &&
657 scaling_settings.enabled;
kthelgason3af6cc02017-03-22 00:25:28 -0700658
asapersson36e9eb42017-03-31 05:29:12 -0700659 if (quality_scaling_allowed) {
asapersson09f05612017-05-15 23:40:18 -0700660 if (quality_scaler_.get() == nullptr) {
661 // Quality scaler has not already been configured.
662 // Drop frames and scale down until desired quality is achieved.
663 if (scaling_settings.thresholds) {
664 quality_scaler_.reset(
665 new QualityScaler(this, *(scaling_settings.thresholds)));
666 } else {
667 quality_scaler_.reset(new QualityScaler(this, codec_type_));
668 }
kthelgason876222f2016-11-29 01:44:11 -0800669 }
670 } else {
671 quality_scaler_.reset(nullptr);
kthelgasonad9010c2017-02-14 00:46:51 -0800672 initial_rampup_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800673 }
asapersson09f05612017-05-15 23:40:18 -0700674
675 stats_proxy_->SetAdaptationStats(GetActiveCounts(kCpu),
676 GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000677}
678
mflodmancc3d4422017-08-03 08:27:51 -0700679void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700680 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700681 VideoFrame incoming_frame = video_frame;
682
683 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700684 int64_t current_time_us = clock_->TimeInMicroseconds();
685 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
686 // In some cases, e.g., when the frame from decoder is fed to encoder,
687 // the timestamp may be set to the future. As the encoding pipeline assumes
688 // capture time to be less than present time, we should reset the capture
689 // timestamps here. Otherwise there may be issues with RTP send stream.
690 if (incoming_frame.timestamp_us() > current_time_us)
691 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700692
693 // Capture time may come from clock with an offset and drift from clock_.
694 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800695 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700696 capture_ntp_time_ms = video_frame.ntp_time_ms();
697 } else if (video_frame.render_time_ms() != 0) {
698 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
699 } else {
nisse1c0dea82017-01-30 02:43:18 -0800700 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700701 }
702 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
703
704 // Convert NTP time, in ms, to RTP timestamp.
705 const int kMsToRtpTimestamp = 90;
706 incoming_frame.set_timestamp(
707 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
708
709 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
710 // We don't allow the same capture time for two frames, drop this one.
711 LOG(LS_WARNING) << "Same/old NTP timestamp ("
712 << incoming_frame.ntp_time_ms()
713 << " <= " << last_captured_timestamp_
714 << ") for incoming frame. Dropping.";
715 return;
716 }
717
asapersson6ffb67d2016-09-12 00:10:45 -0700718 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800719 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
720 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700721 log_stats = true;
722 }
723
perkj26091b12016-09-01 01:17:40 -0700724 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
asapersson6ffb67d2016-09-12 00:10:45 -0700725 encoder_queue_.PostTask(std::unique_ptr<rtc::QueuedTask>(new EncodeTask(
nissee0e3bdf2017-01-18 02:16:20 -0800726 incoming_frame, this, rtc::TimeMicros(), log_stats)));
perkj26091b12016-09-01 01:17:40 -0700727}
728
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200729void VideoStreamEncoder::OnDiscardedFrame() {
730 stats_proxy_->OnFrameDroppedBySource();
731}
732
mflodmancc3d4422017-08-03 08:27:51 -0700733bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700734 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000735 // Pause video if paused by caller or as long as the network is down or the
736 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700737 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 00:58:48 -0700738 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 01:17:40 -0700739 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000740}
741
mflodmancc3d4422017-08-03 08:27:51 -0700742void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -0700743 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000744 // Start trace event only on the first frame after encoder is paused.
745 if (!encoder_paused_and_dropped_frame_) {
746 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
747 }
748 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000749}
750
mflodmancc3d4422017-08-03 08:27:51 -0700751void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -0700752 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000753 // End trace event on first frame after encoder resumes, if frame was dropped.
754 if (encoder_paused_and_dropped_frame_) {
755 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
756 }
757 encoder_paused_and_dropped_frame_ = false;
758}
759
mflodmancc3d4422017-08-03 08:27:51 -0700760void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
761 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -0700762 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800763
perkj26091b12016-09-01 01:17:40 -0700764 if (pre_encode_callback_)
765 pre_encode_callback_->OnFrame(video_frame);
766
Per21d45d22016-10-30 21:37:57 +0100767 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -0700768 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -0700769 video_frame.is_texture() != last_frame_info_->is_texture) {
770 pending_encoder_reconfiguration_ = true;
brandtra3241662017-05-03 04:55:51 -0700771 last_frame_info_ = rtc::Optional<VideoFrameInfo>(VideoFrameInfo(
772 video_frame.width(), video_frame.height(), video_frame.is_texture()));
perkjfa10b552016-10-02 23:45:26 -0700773 LOG(LS_INFO) << "Video frame parameters changed: dimensions="
774 << last_frame_info_->width << "x" << last_frame_info_->height
brandtra3241662017-05-03 04:55:51 -0700775 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-02 23:45:26 -0700776 }
777
kthelgason2bc68642017-02-07 07:02:22 -0800778 if (initial_rampup_ < kMaxInitialFramedrop &&
779 video_frame.size() >
780 MaximumFrameSizeForBitrate(encoder_start_bitrate_bps_ / 1000)) {
781 LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
782 AdaptDown(kQuality);
783 ++initial_rampup_;
784 return;
785 }
786 initial_rampup_ = kMaxInitialFramedrop;
787
sprang57c2fff2017-01-16 06:24:02 -0800788 int64_t now_ms = clock_->TimeInMilliseconds();
perkjfa10b552016-10-02 23:45:26 -0700789 if (pending_encoder_reconfiguration_) {
790 ReconfigureEncoder();
sprang4847ae62017-06-27 07:06:52 -0700791 last_parameters_update_ms_.emplace(now_ms);
sprang57c2fff2017-01-16 06:24:02 -0800792 } else if (!last_parameters_update_ms_ ||
793 now_ms - *last_parameters_update_ms_ >=
794 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
795 video_sender_.UpdateChannelParemeters(rate_allocator_.get(),
796 bitrate_observer_);
sprang4847ae62017-06-27 07:06:52 -0700797 last_parameters_update_ms_.emplace(now_ms);
perkjfa10b552016-10-02 23:45:26 -0700798 }
799
perkj26091b12016-09-01 01:17:40 -0700800 if (EncoderPaused()) {
801 TraceFrameDropStart();
802 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000803 }
perkj26091b12016-09-01 01:17:40 -0700804 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +0000805
ilnik6b826ef2017-06-16 06:53:48 -0700806 VideoFrame out_frame(video_frame);
807 // Crop frame if needed.
808 if (crop_width_ > 0 || crop_height_ > 0) {
809 int cropped_width = video_frame.width() - crop_width_;
810 int cropped_height = video_frame.height() - crop_height_;
811 rtc::scoped_refptr<I420Buffer> cropped_buffer =
812 I420Buffer::Create(cropped_width, cropped_height);
813 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
814 // happen after SinkWants signaled correctly from ReconfigureEncoder.
815 if (crop_width_ < 4 && crop_height_ < 4) {
816 cropped_buffer->CropAndScaleFrom(
817 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
818 crop_height_ / 2, cropped_width, cropped_height);
819 } else {
820 cropped_buffer->ScaleFrom(
821 *video_frame.video_frame_buffer()->ToI420().get());
822 }
823 out_frame =
824 VideoFrame(cropped_buffer, video_frame.timestamp(),
825 video_frame.render_time_ms(), video_frame.rotation());
826 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
827 }
828
Magnus Jedvert26679d62015-04-07 14:07:41 +0200829 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +0000830 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +0000831
ilnik6b826ef2017-06-16 06:53:48 -0700832 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -0700833
ilnik6b826ef2017-06-16 06:53:48 -0700834 video_sender_.AddVideoFrame(out_frame, nullptr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000835}
niklase@google.com470e71d2011-07-07 08:21:25 +0000836
mflodmancc3d4422017-08-03 08:27:51 -0700837void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -0700838 if (!encoder_queue_.IsCurrent()) {
839 encoder_queue_.PostTask([this] { SendKeyFrame(); });
840 return;
841 }
842 RTC_DCHECK_RUN_ON(&encoder_queue_);
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200843 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48 +0000844}
845
mflodmancc3d4422017-08-03 08:27:51 -0700846EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700847 const EncodedImage& encoded_image,
848 const CodecSpecificInfo* codec_specific_info,
849 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 01:17:40 -0700850 // Encoded is called on whatever thread the real encoder implementation run
851 // on. In the case of hardware encoders, there might be several encoders
852 // running in parallel on different threads.
sprang552c7c72017-02-13 04:41:45 -0800853 stats_proxy_->OnSendEncodedImage(encoded_image, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -0700854
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700855 EncodedImageCallback::Result result =
856 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 06:31:25 -0700857
nissee0e3bdf2017-01-18 02:16:20 -0800858 int64_t time_sent_us = rtc::TimeMicros();
perkjd52063f2016-09-07 06:32:18 -0700859 uint32_t timestamp = encoded_image._timeStamp;
kthelgason876222f2016-11-29 01:44:11 -0800860 const int qp = encoded_image.qp_;
nissee0e3bdf2017-01-18 02:16:20 -0800861 encoder_queue_.PostTask([this, timestamp, time_sent_us, qp] {
perkjd52063f2016-09-07 06:32:18 -0700862 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700863 overuse_detector_->FrameSent(timestamp, time_sent_us);
sprang84a37592017-02-10 07:04:27 -0800864 if (quality_scaler_ && qp >= 0)
kthelgason876222f2016-11-29 01:44:11 -0800865 quality_scaler_->ReportQP(qp);
perkjd52063f2016-09-07 06:32:18 -0700866 });
perkj803d97f2016-11-01 11:45:46 -0700867
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700868 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +0100869}
870
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200871void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
872 switch (reason) {
873 case DropReason::kDroppedByMediaOptimizations:
874 stats_proxy_->OnFrameDroppedByMediaOptimizations();
875 encoder_queue_.PostTask([this] {
876 RTC_DCHECK_RUN_ON(&encoder_queue_);
877 if (quality_scaler_)
878 quality_scaler_->ReportDroppedFrame();
879 });
880 break;
881 case DropReason::kDroppedByEncoder:
882 stats_proxy_->OnFrameDroppedByEncoder();
883 break;
884 }
kthelgason876222f2016-11-29 01:44:11 -0800885}
886
mflodmancc3d4422017-08-03 08:27:51 -0700887void VideoStreamEncoder::OnReceivedIntraFrameRequest(size_t stream_index) {
perkj26091b12016-09-01 01:17:40 -0700888 if (!encoder_queue_.IsCurrent()) {
889 encoder_queue_.PostTask(
890 [this, stream_index] { OnReceivedIntraFrameRequest(stream_index); });
891 return;
892 }
893 RTC_DCHECK_RUN_ON(&encoder_queue_);
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000894 // Key frame request from remote side, signal to VCM.
justinlin@chromium.org7bfb3a32013-05-13 22:59:00 +0000895 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
perkj600246e2016-05-04 11:26:51 -0700896 video_sender_.IntraFrameRequest(stream_index);
mflodman@webrtc.orgaca26292012-10-05 16:17:41 +0000897}
898
mflodmancc3d4422017-08-03 08:27:51 -0700899void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
900 uint8_t fraction_lost,
901 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 01:17:40 -0700902 if (!encoder_queue_.IsCurrent()) {
903 encoder_queue_.PostTask(
904 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
905 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
906 });
907 return;
908 }
909 RTC_DCHECK_RUN_ON(&encoder_queue_);
910 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
911
perkjec81bcd2016-05-11 06:01:13 -0700912 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
mflodman8602a3d2015-05-20 15:54:42 -0700913 << " packet loss " << static_cast<int>(fraction_lost)
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000914 << " rtt " << round_trip_time_ms;
perkj26091b12016-09-01 01:17:40 -0700915
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200916 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
sprang1a646ee2016-12-01 06:34:11 -0800917 round_trip_time_ms, rate_allocator_.get(),
918 bitrate_observer_);
perkj26091b12016-09-01 01:17:40 -0700919
920 encoder_start_bitrate_bps_ =
921 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 17:21:19 +0200922 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 16:41:30 +0100923 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 01:17:40 -0700924 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12 +0000925
sprang552c7c72017-02-13 04:41:45 -0800926 if (video_suspension_changed) {
mflodman522739c2016-06-22 17:42:30 +0200927 LOG(LS_INFO) << "Video suspend state changed to: "
928 << (video_is_suspended ? "suspended" : "not suspended");
Peter Boström7083e112015-09-22 16:28:51 +0200929 stats_proxy_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +0200930 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000931}
932
mflodmancc3d4422017-08-03 08:27:51 -0700933void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -0700934 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700935 AdaptationRequest adaptation_request = {
936 last_frame_info_->pixel_count(),
937 stats_proxy_->GetStats().input_frame_rate,
938 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -0700939
sprangc5d62e22017-04-02 23:53:04 -0700940 bool downgrade_requested =
941 last_adaptation_request_ &&
942 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
943
sprangc5d62e22017-04-02 23:53:04 -0700944 switch (degradation_preference_) {
hbos8d609f62017-04-10 07:39:05 -0700945 case VideoSendStream::DegradationPreference::kBalanced:
asaperssonf7e294d2017-06-13 23:25:22 -0700946 break;
hbos8d609f62017-04-10 07:39:05 -0700947 case VideoSendStream::DegradationPreference::kMaintainFramerate:
sprangc5d62e22017-04-02 23:53:04 -0700948 if (downgrade_requested &&
949 adaptation_request.input_pixel_count_ >=
950 last_adaptation_request_->input_pixel_count_) {
951 // Don't request lower resolution if the current resolution is not
952 // lower than the last time we asked for the resolution to be lowered.
953 return;
954 }
955 break;
hbos8d609f62017-04-10 07:39:05 -0700956 case VideoSendStream::DegradationPreference::kMaintainResolution:
sprangc5d62e22017-04-02 23:53:04 -0700957 if (adaptation_request.framerate_fps_ <= 0 ||
958 (downgrade_requested &&
959 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
960 // If no input fps estimate available, can't determine how to scale down
961 // framerate. Otherwise, don't request lower framerate if we don't have
962 // a valid frame rate. Since framerate, unlike resolution, is a measure
963 // we have to estimate, and can fluctuate naturally over time, don't
964 // make the same kind of limitations as for resolution, but trust the
965 // overuse detector to not trigger too often.
966 return;
967 }
968 break;
hbos8d609f62017-04-10 07:39:05 -0700969 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -0700970 return;
sprang84a37592017-02-10 07:04:27 -0800971 }
sprangc5d62e22017-04-02 23:53:04 -0700972
asaperssond0de2952017-04-21 01:47:31 -0700973 if (reason == kCpu) {
asaperssonf7e294d2017-06-13 23:25:22 -0700974 if (GetConstAdaptCounter().ResolutionCount(kCpu) >=
975 kMaxCpuResolutionDowngrades ||
976 GetConstAdaptCounter().FramerateCount(kCpu) >=
977 kMaxCpuFramerateDowngrades) {
asaperssond0de2952017-04-21 01:47:31 -0700978 return;
asaperssonf7e294d2017-06-13 23:25:22 -0700979 }
kthelgason876222f2016-11-29 01:44:11 -0800980 }
sprangc5d62e22017-04-02 23:53:04 -0700981
sprangc5d62e22017-04-02 23:53:04 -0700982 switch (degradation_preference_) {
asaperssonf7e294d2017-06-13 23:25:22 -0700983 case VideoSendStream::DegradationPreference::kBalanced: {
984 // Try scale down framerate, if lower.
985 int fps = MinFps(last_frame_info_->pixel_count());
986 if (source_proxy_->RestrictFramerate(fps)) {
987 GetAdaptCounter().IncrementFramerate(reason);
988 break;
989 }
990 // Scale down resolution.
kjellanderbdf30722017-09-08 11:00:21 -0700991 FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -0700992 }
hbos8d609f62017-04-10 07:39:05 -0700993 case VideoSendStream::DegradationPreference::kMaintainFramerate:
asapersson13874762017-06-07 00:01:02 -0700994 // Scale down resolution.
asaperssond0de2952017-04-21 01:47:31 -0700995 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -0700996 adaptation_request.input_pixel_count_,
997 settings_.encoder->GetScalingSettings().min_pixels_per_frame)) {
asaperssond0de2952017-04-21 01:47:31 -0700998 return;
999 }
asaperssonf7e294d2017-06-13 23:25:22 -07001000 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001001 break;
sprangfda496a2017-06-15 04:21:07 -07001002 case VideoSendStream::DegradationPreference::kMaintainResolution: {
asapersson13874762017-06-07 00:01:02 -07001003 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001004 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1005 adaptation_request.framerate_fps_);
1006 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -07001007 return;
sprangfda496a2017-06-15 04:21:07 -07001008 RTC_DCHECK_NE(max_framerate_, -1);
1009 overuse_detector_->OnTargetFramerateUpdated(
1010 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001011 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001012 break;
sprangfda496a2017-06-15 04:21:07 -07001013 }
hbos8d609f62017-04-10 07:39:05 -07001014 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -07001015 RTC_NOTREACHED();
1016 }
1017
asaperssond0de2952017-04-21 01:47:31 -07001018 last_adaptation_request_.emplace(adaptation_request);
1019
asapersson09f05612017-05-15 23:40:18 -07001020 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001021
asapersson09f05612017-05-15 23:40:18 -07001022 LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -07001023}
1024
mflodmancc3d4422017-08-03 08:27:51 -07001025void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001026 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001027
1028 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1029 int num_downgrades = adapt_counter.TotalCount(reason);
1030 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001031 return;
asapersson09f05612017-05-15 23:40:18 -07001032 RTC_DCHECK_GT(num_downgrades, 0);
1033
sprangc5d62e22017-04-02 23:53:04 -07001034 AdaptationRequest adaptation_request = {
1035 last_frame_info_->pixel_count(),
1036 stats_proxy_->GetStats().input_frame_rate,
1037 AdaptationRequest::Mode::kAdaptUp};
1038
1039 bool adapt_up_requested =
1040 last_adaptation_request_ &&
1041 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001042
asaperssonf7e294d2017-06-13 23:25:22 -07001043 if (degradation_preference_ ==
1044 VideoSendStream::DegradationPreference::kMaintainFramerate) {
1045 if (adapt_up_requested &&
1046 adaptation_request.input_pixel_count_ <=
1047 last_adaptation_request_->input_pixel_count_) {
1048 // Don't request higher resolution if the current resolution is not
1049 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001050 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001051 }
sprangb1ca0732017-02-01 08:38:12 -08001052 }
sprangc5d62e22017-04-02 23:53:04 -07001053
sprangc5d62e22017-04-02 23:53:04 -07001054 switch (degradation_preference_) {
asaperssonf7e294d2017-06-13 23:25:22 -07001055 case VideoSendStream::DegradationPreference::kBalanced: {
1056 // Try scale up framerate, if higher.
1057 int fps = MaxFps(last_frame_info_->pixel_count());
1058 if (source_proxy_->IncreaseFramerate(fps)) {
1059 GetAdaptCounter().DecrementFramerate(reason, fps);
1060 // Reset framerate in case of fewer fps steps down than up.
1061 if (adapt_counter.FramerateCount() == 0 &&
1062 fps != std::numeric_limits<int>::max()) {
1063 LOG(LS_INFO) << "Removing framerate down-scaling setting.";
1064 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1065 }
1066 break;
1067 }
1068 // Scale up resolution.
kjellanderbdf30722017-09-08 11:00:21 -07001069 FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001070 }
asapersson13874762017-06-07 00:01:02 -07001071 case VideoSendStream::DegradationPreference::kMaintainFramerate: {
1072 // Scale up resolution.
1073 int pixel_count = adaptation_request.input_pixel_count_;
1074 if (adapt_counter.ResolutionCount() == 1) {
sprangc5d62e22017-04-02 23:53:04 -07001075 LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001076 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001077 }
asapersson13874762017-06-07 00:01:02 -07001078 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1079 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001080 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001081 break;
asapersson13874762017-06-07 00:01:02 -07001082 }
1083 case VideoSendStream::DegradationPreference::kMaintainResolution: {
1084 // Scale up framerate.
1085 int fps = adaptation_request.framerate_fps_;
1086 if (adapt_counter.FramerateCount() == 1) {
sprangc5d62e22017-04-02 23:53:04 -07001087 LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001088 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001089 }
sprangfda496a2017-06-15 04:21:07 -07001090
1091 const int requested_framerate =
1092 source_proxy_->RequestHigherFramerateThan(fps);
1093 if (requested_framerate == -1) {
1094 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001095 return;
sprangfda496a2017-06-15 04:21:07 -07001096 }
1097 overuse_detector_->OnTargetFramerateUpdated(
1098 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001099 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001100 break;
asapersson13874762017-06-07 00:01:02 -07001101 }
hbos8d609f62017-04-10 07:39:05 -07001102 case VideoSendStream::DegradationPreference::kDegradationDisabled:
asaperssonf7e294d2017-06-13 23:25:22 -07001103 return;
sprangc5d62e22017-04-02 23:53:04 -07001104 }
1105
asaperssond0de2952017-04-21 01:47:31 -07001106 last_adaptation_request_.emplace(adaptation_request);
1107
asapersson09f05612017-05-15 23:40:18 -07001108 UpdateAdaptationStats(reason);
1109
1110 LOG(LS_INFO) << adapt_counter.ToString();
1111}
1112
mflodmancc3d4422017-08-03 08:27:51 -07001113void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001114 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001115 case kCpu:
asapersson09f05612017-05-15 23:40:18 -07001116 stats_proxy_->OnCpuAdaptationChanged(GetActiveCounts(kCpu),
1117 GetActiveCounts(kQuality));
1118 break;
1119 case kQuality:
1120 stats_proxy_->OnQualityAdaptationChanged(GetActiveCounts(kCpu),
1121 GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001122 break;
1123 }
perkj26091b12016-09-01 01:17:40 -07001124}
1125
mflodmancc3d4422017-08-03 08:27:51 -07001126VideoStreamEncoder::AdaptCounts VideoStreamEncoder::GetActiveCounts(
1127 AdaptReason reason) {
1128 VideoStreamEncoder::AdaptCounts counts =
1129 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001130 switch (reason) {
1131 case kCpu:
1132 if (!IsFramerateScalingEnabled(degradation_preference_))
1133 counts.fps = -1;
1134 if (!IsResolutionScalingEnabled(degradation_preference_))
1135 counts.resolution = -1;
1136 break;
1137 case kQuality:
1138 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1139 !quality_scaler_) {
1140 counts.fps = -1;
1141 }
1142 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1143 !quality_scaler_) {
1144 counts.resolution = -1;
1145 }
1146 break;
sprangc5d62e22017-04-02 23:53:04 -07001147 }
asapersson09f05612017-05-15 23:40:18 -07001148 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001149}
1150
mflodmancc3d4422017-08-03 08:27:51 -07001151VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001152 return adapt_counters_[degradation_preference_];
1153}
1154
mflodmancc3d4422017-08-03 08:27:51 -07001155const VideoStreamEncoder::AdaptCounter&
1156VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001157 return adapt_counters_[degradation_preference_];
1158}
1159
1160// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001161VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001162 fps_counters_.resize(kScaleReasonSize);
1163 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001164 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001165}
1166
mflodmancc3d4422017-08-03 08:27:51 -07001167VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001168
mflodmancc3d4422017-08-03 08:27:51 -07001169std::string VideoStreamEncoder::AdaptCounter::ToString() const {
asapersson09f05612017-05-15 23:40:18 -07001170 std::stringstream ss;
1171 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1172 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
1173 return ss.str();
1174}
1175
mflodmancc3d4422017-08-03 08:27:51 -07001176VideoStreamEncoder::AdaptCounts VideoStreamEncoder::AdaptCounter::Counts(
1177 int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001178 AdaptCounts counts;
1179 counts.fps = fps_counters_[reason];
1180 counts.resolution = resolution_counters_[reason];
1181 return counts;
1182}
1183
mflodmancc3d4422017-08-03 08:27:51 -07001184void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001185 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001186}
1187
mflodmancc3d4422017-08-03 08:27:51 -07001188void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001189 ++(resolution_counters_[reason]);
1190}
1191
mflodmancc3d4422017-08-03 08:27:51 -07001192void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001193 if (fps_counters_[reason] == 0) {
1194 // Balanced mode: Adapt up is in a different order, switch reason.
1195 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1196 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1197 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1198 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1199 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1200 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1201 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1202 MoveCount(&resolution_counters_, reason);
1203 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1204 }
1205 --(fps_counters_[reason]);
1206 RTC_DCHECK_GE(fps_counters_[reason], 0);
1207}
1208
mflodmancc3d4422017-08-03 08:27:51 -07001209void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001210 if (resolution_counters_[reason] == 0) {
1211 // Balanced mode: Adapt up is in a different order, switch reason.
1212 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1213 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1214 MoveCount(&fps_counters_, reason);
1215 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1216 }
1217 --(resolution_counters_[reason]);
1218 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1219}
1220
mflodmancc3d4422017-08-03 08:27:51 -07001221void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1222 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07001223 DecrementFramerate(reason);
1224 // Reset if at max fps (i.e. in case of fewer steps up than down).
1225 if (cur_fps == std::numeric_limits<int>::max())
1226 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-15 23:40:18 -07001227}
1228
mflodmancc3d4422017-08-03 08:27:51 -07001229int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07001230 return Count(fps_counters_);
1231}
1232
mflodmancc3d4422017-08-03 08:27:51 -07001233int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07001234 return Count(resolution_counters_);
1235}
1236
mflodmancc3d4422017-08-03 08:27:51 -07001237int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001238 return fps_counters_[reason];
1239}
1240
mflodmancc3d4422017-08-03 08:27:51 -07001241int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001242 return resolution_counters_[reason];
1243}
1244
mflodmancc3d4422017-08-03 08:27:51 -07001245int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001246 return FramerateCount(reason) + ResolutionCount(reason);
1247}
1248
mflodmancc3d4422017-08-03 08:27:51 -07001249int VideoStreamEncoder::AdaptCounter::Count(
1250 const std::vector<int>& counters) const {
asapersson09f05612017-05-15 23:40:18 -07001251 return std::accumulate(counters.begin(), counters.end(), 0);
1252}
1253
mflodmancc3d4422017-08-03 08:27:51 -07001254void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1255 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001256 int to_reason = (from_reason + 1) % kScaleReasonSize;
1257 ++((*counters)[to_reason]);
1258 --((*counters)[from_reason]);
1259}
1260
mflodmancc3d4422017-08-03 08:27:51 -07001261std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07001262 const std::vector<int>& counters) const {
1263 std::stringstream ss;
1264 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1265 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07001266 }
asapersson09f05612017-05-15 23:40:18 -07001267 return ss.str();
sprangc5d62e22017-04-02 23:53:04 -07001268}
1269
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001270} // namespace webrtc