blob: e8fc47987615feb94884489802b63a02f5f07add [file] [log] [blame]
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00001/*
2 * libjingle
3 * Copyright 2010 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
henrike@webrtc.org28e20752013-07-10 00:45:36 +000027
28#include "talk/media/base/videoadapter.h"
29
30#include <limits.h> // For INT_MAX
31
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000032#include "talk/media/base/constants.h"
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +000033#include "talk/media/base/videocommon.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000034#include "talk/media/base/videoframe.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000035#include "webrtc/base/logging.h"
36#include "webrtc/base/timeutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000037
38namespace cricket {
39
40// TODO(fbarchard): Make downgrades settable
41static const int kMaxCpuDowngrades = 2; // Downgrade at most 2 times for CPU.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +000042// The number of cpu samples to require before adapting. This value depends on
43// the cpu monitor sampling frequency being 2000ms.
44static const int kCpuLoadMinSamples = 3;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000045// The amount of weight to give to each new cpu load sample. The lower the
46// value, the slower we'll adapt to changing cpu conditions.
47static const float kCpuLoadWeightCoefficient = 0.4f;
48// The seed value for the cpu load moving average.
49static const float kCpuLoadInitialAverage = 0.5f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051// Desktop needs 1/8 scale for HD (1280 x 720) to QQVGA (160 x 90)
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000052static const float kScaleFactors[] = {
53 1.f / 1.f, // Full size.
54 3.f / 4.f, // 3/4 scale.
55 1.f / 2.f, // 1/2 scale.
56 3.f / 8.f, // 3/8 scale.
57 1.f / 4.f, // 1/4 scale.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058 3.f / 16.f, // 3/16 scale.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000059 1.f / 8.f, // 1/8 scale.
60 0.f // End of table.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000061};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000063// TODO(fbarchard): Use this table (optionally) for CPU and GD as well.
64static const float kViewScaleFactors[] = {
65 1.f / 1.f, // Full size.
66 3.f / 4.f, // 3/4 scale.
67 2.f / 3.f, // 2/3 scale. // Allow 1080p to 720p.
68 1.f / 2.f, // 1/2 scale.
69 3.f / 8.f, // 3/8 scale.
70 1.f / 3.f, // 1/3 scale. // Allow 1080p to 360p.
71 1.f / 4.f, // 1/4 scale.
72 3.f / 16.f, // 3/16 scale.
73 1.f / 8.f, // 1/8 scale.
74 0.f // End of table.
75};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000077const float* VideoAdapter::GetViewScaleFactors() const {
78 return scale_third_ ? kViewScaleFactors : kScaleFactors;
79}
80
81// For resolutions that would scale down a little instead of up a little,
82// bias toward scaling up a little. This will tend to choose 3/4 scale instead
83// of 2/3 scale, when the 2/3 is not an exact match.
84static const float kUpBias = -0.9f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000085// Find the scale factor that, when applied to width and height, is closest
86// to num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000087float VideoAdapter::FindScale(const float* scale_factors,
88 const float upbias,
89 int width, int height,
90 int target_num_pixels) {
91 const float kMinNumPixels = 160 * 90;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092 if (!target_num_pixels) {
93 return 0.f;
94 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000095 float best_distance = static_cast<float>(INT_MAX);
96 float best_scale = 1.f; // Default to unscaled if nothing matches.
97 float pixels = static_cast<float>(width * height);
98 for (int i = 0; ; ++i) {
99 float scale = scale_factors[i];
100 float test_num_pixels = pixels * scale * scale;
101 // Do not consider scale factors that produce too small images.
102 // Scale factor of 0 at end of table will also exit here.
103 if (test_num_pixels < kMinNumPixels) {
104 break;
105 }
106 float diff = target_num_pixels - test_num_pixels;
107 // If resolution is higher than desired, bias the difference based on
108 // preference for slightly larger for nearest, or avoid completely if
109 // looking for lower resolutions only.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 if (diff < 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000111 diff = diff * kUpBias;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 }
113 if (diff < best_distance) {
114 best_distance = diff;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000115 best_scale = scale;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 if (best_distance == 0) { // Found exact match.
117 break;
118 }
119 }
120 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000121 return best_scale;
122}
123
124// Find the closest scale factor.
125float VideoAdapter::FindClosestScale(int width, int height,
126 int target_num_pixels) {
127 return FindScale(kScaleFactors, kUpBias,
128 width, height, target_num_pixels);
129}
130
131// Find the closest view scale factor.
132float VideoAdapter::FindClosestViewScale(int width, int height,
133 int target_num_pixels) {
134 return FindScale(GetViewScaleFactors(), kUpBias,
135 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136}
137
138// Finds the scale factor that, when applied to width and height, produces
139// fewer than num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000140static const float kUpAvoidBias = -1000000000.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000141float VideoAdapter::FindLowerScale(int width, int height,
142 int target_num_pixels) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000143 return FindScale(GetViewScaleFactors(), kUpAvoidBias,
144 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000145}
146
147// There are several frame sizes used by Adapter. This explains them
148// input_format - set once by server to frame size expected from the camera.
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000149// The input frame size is also updated in every call to AdaptFrame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150// output_format - size that output would like to be. Includes framerate.
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000151// The output frame size is also updated in every call to AdaptFrame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000152// output_num_pixels - size that output should be constrained to. Used to
153// compute output_format from in_frame.
154// in_frame - actual camera captured frame size, which is typically the same
155// as input_format. This can also be rotated or cropped for aspect ratio.
156// out_frame - actual frame output by adapter. Should be a direct scale of
157// in_frame maintaining rotation and aspect ratio.
158// OnOutputFormatRequest - server requests you send this resolution based on
159// view requests.
160// OnEncoderResolutionRequest - encoder requests you send this resolution based
161// on bandwidth
162// OnCpuLoadUpdated - cpu monitor requests you send this resolution based on
163// cpu load.
164
165///////////////////////////////////////////////////////////////////////
166// Implementation of VideoAdapter
167VideoAdapter::VideoAdapter()
168 : output_num_pixels_(INT_MAX),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000169 scale_third_(false),
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000170 frames_in_(0),
171 frames_out_(0),
172 frames_scaled_(0),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000173 adaption_changes_(0),
magjed@webrtc.orga73d7462014-11-14 13:25:25 +0000174 previous_width_(0),
175 previous_height_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176 black_output_(false),
177 is_black_(false),
178 interval_next_frame_(0) {
179}
180
181VideoAdapter::~VideoAdapter() {
182}
183
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000184void VideoAdapter::SetInputFormat(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000185 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000186 int64 old_input_interval = input_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 input_format_ = format;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000188 output_format_.interval = rtc::_max(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000189 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000190 if (old_input_interval != input_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000191 LOG(LS_INFO) << "VAdapt input interval changed from "
192 << old_input_interval << " to " << input_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000193 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000194}
195
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000196void CoordinatedVideoAdapter::SetInputFormat(const VideoFormat& format) {
197 int previous_width = input_format().width;
198 int previous_height = input_format().height;
199 bool is_resolution_change = previous_width > 0 && format.width > 0 &&
200 (previous_width != format.width ||
201 previous_height != format.height);
202 VideoAdapter::SetInputFormat(format);
203 if (is_resolution_change) {
204 int width, height;
205 // Trigger the adaptation logic again, to potentially reset the adaptation
206 // state for things like view requests that may not longer be capping
207 // output (or may now cap output).
208 AdaptToMinimumFormat(&width, &height);
209 LOG(LS_INFO) << "VAdapt Input Resolution Change: "
210 << "Previous input resolution: "
211 << previous_width << "x" << previous_height
212 << " New input resolution: "
213 << format.width << "x" << format.height
214 << " New output resolution: "
215 << width << "x" << height;
216 }
217}
218
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000219void CoordinatedVideoAdapter::set_cpu_smoothing(bool enable) {
220 LOG(LS_INFO) << "CPU smoothing is now "
221 << (enable ? "enabled" : "disabled");
222 cpu_smoothing_ = enable;
223}
224
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000225void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000226 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000227 int64 old_output_interval = output_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000228 output_format_ = format;
229 output_num_pixels_ = output_format_.width * output_format_.height;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000230 output_format_.interval = rtc::_max(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000232 if (old_output_interval != output_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000233 LOG(LS_INFO) << "VAdapt output interval changed from "
234 << old_output_interval << " to " << output_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000235 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000236}
237
238const VideoFormat& VideoAdapter::input_format() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000239 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000240 return input_format_;
241}
242
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000243bool VideoAdapter::drops_all_frames() const {
244 return output_num_pixels_ == 0;
245}
246
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000247const VideoFormat& VideoAdapter::output_format() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000248 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249 return output_format_;
250}
251
252void VideoAdapter::SetBlackOutput(bool black) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000253 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000254 black_output_ = black;
255}
256
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000257bool VideoAdapter::IsBlackOutput() {
258 rtc::CritScope cs(&critical_section_);
259 return black_output_;
260}
261
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000262// Constrain output resolution to this many pixels overall
263void VideoAdapter::SetOutputNumPixels(int num_pixels) {
264 output_num_pixels_ = num_pixels;
265}
266
267int VideoAdapter::GetOutputNumPixels() const {
268 return output_num_pixels_;
269}
270
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000271VideoFormat VideoAdapter::AdaptFrameResolution(int in_width, int in_height) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000272 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000273 ++frames_in_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000274
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000275 SetInputFormat(VideoFormat(
276 in_width, in_height, input_format_.interval, input_format_.fourcc));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000277
278 // Drop the input frame if necessary.
279 bool should_drop = false;
280 if (!output_num_pixels_) {
281 // Drop all frames as the output format is 0x0.
282 should_drop = true;
283 } else {
284 // Drop some frames based on input fps and output fps.
285 // Normally output fps is less than input fps.
286 // TODO(fbarchard): Consider adjusting interval to reflect the adjusted
287 // interval between frames after dropping some frames.
288 interval_next_frame_ += input_format_.interval;
289 if (output_format_.interval > 0) {
290 if (interval_next_frame_ >= output_format_.interval) {
291 interval_next_frame_ %= output_format_.interval;
292 } else {
293 should_drop = true;
294 }
295 }
296 }
297 if (should_drop) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000298 // Show VAdapt log every 90 frames dropped. (3 seconds)
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000299 if ((frames_in_ - frames_out_) % 90 == 0) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000300 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
301 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000302 LOG(LS_INFO) << "VAdapt Drop Frame: scaled " << frames_scaled_
303 << " / out " << frames_out_
304 << " / in " << frames_in_
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000305 << " Changes: " << adaption_changes_
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000306 << " Input: " << in_width
307 << "x" << in_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000308 << " i" << input_format_.interval
309 << " Output: i" << output_format_.interval;
310 }
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000311
312 return VideoFormat(); // Drop frame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000313 }
314
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000315 const float scale = VideoAdapter::FindClosestViewScale(
316 in_width, in_height, output_num_pixels_);
317 const int output_width = static_cast<int>(in_width * scale + .5f);
318 const int output_height = static_cast<int>(in_height * scale + .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000319
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000320 ++frames_out_;
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000321 if (scale != 1)
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000322 ++frames_scaled_;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000323 // Show VAdapt log every 90 frames output. (3 seconds)
324 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
325 // for LS_VERBOSE and more for LS_INFO.
326 bool show = (frames_out_) % 90 == 0;
327
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000328 // TODO(fbarchard): LOG the previous output resolution and track input
329 // resolution changes as well. Consider dropping the statistics into their
330 // own class which could be queried publically.
331 bool changed = false;
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000332 if (previous_width_ && (previous_width_ != output_width ||
333 previous_height_ != output_height)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000334 show = true;
335 ++adaption_changes_;
336 changed = true;
337 }
338 if (show) {
339 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
340 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000341 LOG(LS_INFO) << "VAdapt Frame: scaled " << frames_scaled_
342 << " / out " << frames_out_
343 << " / in " << frames_in_
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000344 << " Changes: " << adaption_changes_
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000345 << " Input: " << in_width
346 << "x" << in_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000347 << " i" << input_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000348 << " Scale: " << scale
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000349 << " Output: " << output_width
350 << "x" << output_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000351 << " i" << output_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000352 << " Changed: " << (changed ? "true" : "false");
353 }
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000354
355 output_format_.width = output_width;
356 output_format_.height = output_height;
357 previous_width_ = output_width;
358 previous_height_ = output_height;
359
360 return output_format_;
361}
362
363// TODO(fbarchard): Add AdaptFrameRate function that only drops frames but
364// not resolution.
365bool VideoAdapter::AdaptFrame(VideoFrame* in_frame, VideoFrame** out_frame) {
366 if (!in_frame || !out_frame)
367 return false;
368
369 const VideoFormat adapted_format =
370 AdaptFrameResolution(static_cast<int>(in_frame->GetWidth()),
371 static_cast<int>(in_frame->GetHeight()));
372
373 rtc::CritScope cs(&critical_section_);
374 if (adapted_format.IsSize0x0()) {
375 *out_frame = NULL;
376 return true;
377 }
378
379 if (!black_output_ &&
380 in_frame->GetWidth() == static_cast<size_t>(adapted_format.width) &&
381 in_frame->GetHeight() == static_cast<size_t>(adapted_format.height)) {
382 // The dimensions are correct and we aren't muting, so use the input frame.
383 *out_frame = in_frame;
384 } else {
385 if (!StretchToOutputFrame(in_frame)) {
386 LOG(LS_VERBOSE) << "VAdapt Stretch Failed.";
387 return false;
388 }
389
390 *out_frame = output_frame_.get();
391 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000392
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000393 return true;
394}
395
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000396void VideoAdapter::set_scale_third(bool enable) {
397 LOG(LS_INFO) << "Video Adapter third scaling is now "
398 << (enable ? "enabled" : "disabled");
399 scale_third_ = enable;
400}
401
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000402// Scale or Blacken the frame. Returns true if successful.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000403bool VideoAdapter::StretchToOutputFrame(const VideoFrame* in_frame) {
404 int output_width = output_format_.width;
405 int output_height = output_format_.height;
406
407 // Create and stretch the output frame if it has not been created yet or its
408 // size is not same as the expected.
409 bool stretched = false;
410 if (!output_frame_ ||
411 output_frame_->GetWidth() != static_cast<size_t>(output_width) ||
412 output_frame_->GetHeight() != static_cast<size_t>(output_height)) {
413 output_frame_.reset(
414 in_frame->Stretch(output_width, output_height, true, true));
415 if (!output_frame_) {
416 LOG(LS_WARNING) << "Adapter failed to stretch frame to "
417 << output_width << "x" << output_height;
418 return false;
419 }
420 stretched = true;
421 is_black_ = false;
422 }
423
424 if (!black_output_) {
425 if (!stretched) {
426 // The output frame does not need to be blacken and has not been stretched
427 // from the input frame yet, stretch the input frame. This is the most
428 // common case.
429 in_frame->StretchToFrame(output_frame_.get(), true, true);
430 }
431 is_black_ = false;
432 } else {
433 if (!is_black_) {
434 output_frame_->SetToBlack();
435 is_black_ = true;
436 }
437 output_frame_->SetElapsedTime(in_frame->GetElapsedTime());
438 output_frame_->SetTimeStamp(in_frame->GetTimeStamp());
439 }
440
441 return true;
442}
443
444///////////////////////////////////////////////////////////////////////
445// Implementation of CoordinatedVideoAdapter
446CoordinatedVideoAdapter::CoordinatedVideoAdapter()
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000447 : cpu_adaptation_(true),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000448 cpu_smoothing_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000449 gd_adaptation_(true),
450 view_adaptation_(true),
451 view_switch_(false),
452 cpu_downgrade_count_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000453 cpu_load_min_samples_(kCpuLoadMinSamples),
454 cpu_load_num_samples_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000455 high_system_threshold_(kHighSystemCpuThreshold),
456 low_system_threshold_(kLowSystemCpuThreshold),
457 process_threshold_(kProcessCpuThreshold),
458 view_desired_num_pixels_(INT_MAX),
459 view_desired_interval_(0),
460 encoder_desired_num_pixels_(INT_MAX),
461 cpu_desired_num_pixels_(INT_MAX),
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000462 adapt_reason_(ADAPTREASON_NONE),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000463 system_load_average_(kCpuLoadInitialAverage) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000464}
465
466// Helper function to UPGRADE or DOWNGRADE a number of pixels
467void CoordinatedVideoAdapter::StepPixelCount(
468 CoordinatedVideoAdapter::AdaptRequest request,
469 int* num_pixels) {
470 switch (request) {
471 case CoordinatedVideoAdapter::DOWNGRADE:
472 *num_pixels /= 2;
473 break;
474
475 case CoordinatedVideoAdapter::UPGRADE:
476 *num_pixels *= 2;
477 break;
478
479 default: // No change in pixel count
480 break;
481 }
482 return;
483}
484
485// Find the adaptation request of the cpu based on the load. Return UPGRADE if
486// the load is low, DOWNGRADE if the load is high, and KEEP otherwise.
487CoordinatedVideoAdapter::AdaptRequest CoordinatedVideoAdapter::FindCpuRequest(
488 int current_cpus, int max_cpus,
489 float process_load, float system_load) {
490 // Downgrade if system is high and plugin is at least more than midrange.
491 if (system_load >= high_system_threshold_ * max_cpus &&
492 process_load >= process_threshold_ * current_cpus) {
493 return CoordinatedVideoAdapter::DOWNGRADE;
494 // Upgrade if system is low.
495 } else if (system_load < low_system_threshold_ * max_cpus) {
496 return CoordinatedVideoAdapter::UPGRADE;
497 }
498 return CoordinatedVideoAdapter::KEEP;
499}
500
501// A remote view request for a new resolution.
502void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000503 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000504 if (!view_adaptation_) {
505 return;
506 }
507 // Set output for initial aspect ratio in mediachannel unittests.
508 int old_num_pixels = GetOutputNumPixels();
509 SetOutputFormat(format);
510 SetOutputNumPixels(old_num_pixels);
511 view_desired_num_pixels_ = format.width * format.height;
512 view_desired_interval_ = format.interval;
513 int new_width, new_height;
514 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
515 LOG(LS_INFO) << "VAdapt View Request: "
516 << format.width << "x" << format.height
517 << " Pixels: " << view_desired_num_pixels_
518 << " Changed: " << (changed ? "true" : "false")
519 << " To: " << new_width << "x" << new_height;
520}
521
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000522void CoordinatedVideoAdapter::set_cpu_load_min_samples(
523 int cpu_load_min_samples) {
524 if (cpu_load_min_samples_ != cpu_load_min_samples) {
525 LOG(LS_INFO) << "VAdapt Change Cpu Adapt Min Samples from: "
526 << cpu_load_min_samples_ << " to "
527 << cpu_load_min_samples;
528 cpu_load_min_samples_ = cpu_load_min_samples;
529 }
530}
531
532void CoordinatedVideoAdapter::set_high_system_threshold(
533 float high_system_threshold) {
534 ASSERT(high_system_threshold <= 1.0f);
535 ASSERT(high_system_threshold >= 0.0f);
536 if (high_system_threshold_ != high_system_threshold) {
537 LOG(LS_INFO) << "VAdapt Change High System Threshold from: "
538 << high_system_threshold_ << " to " << high_system_threshold;
539 high_system_threshold_ = high_system_threshold;
540 }
541}
542
543void CoordinatedVideoAdapter::set_low_system_threshold(
544 float low_system_threshold) {
545 ASSERT(low_system_threshold <= 1.0f);
546 ASSERT(low_system_threshold >= 0.0f);
547 if (low_system_threshold_ != low_system_threshold) {
548 LOG(LS_INFO) << "VAdapt Change Low System Threshold from: "
549 << low_system_threshold_ << " to " << low_system_threshold;
550 low_system_threshold_ = low_system_threshold;
551 }
552}
553
554void CoordinatedVideoAdapter::set_process_threshold(float process_threshold) {
555 ASSERT(process_threshold <= 1.0f);
556 ASSERT(process_threshold >= 0.0f);
557 if (process_threshold_ != process_threshold) {
558 LOG(LS_INFO) << "VAdapt Change High Process Threshold from: "
559 << process_threshold_ << " to " << process_threshold;
560 process_threshold_ = process_threshold;
561 }
562}
563
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000564// A Bandwidth GD request for new resolution
565void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
566 int width, int height, AdaptRequest request) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000567 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568 if (!gd_adaptation_) {
569 return;
570 }
571 int old_encoder_desired_num_pixels = encoder_desired_num_pixels_;
572 if (KEEP != request) {
573 int new_encoder_desired_num_pixels = width * height;
574 int old_num_pixels = GetOutputNumPixels();
575 if (new_encoder_desired_num_pixels != old_num_pixels) {
576 LOG(LS_VERBOSE) << "VAdapt GD resolution stale. Ignored";
577 } else {
578 // Update the encoder desired format based on the request.
579 encoder_desired_num_pixels_ = new_encoder_desired_num_pixels;
580 StepPixelCount(request, &encoder_desired_num_pixels_);
581 }
582 }
583 int new_width, new_height;
584 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
585
586 // Ignore up or keep if no change.
587 if (DOWNGRADE != request && view_switch_ && !changed) {
588 encoder_desired_num_pixels_ = old_encoder_desired_num_pixels;
589 LOG(LS_VERBOSE) << "VAdapt ignoring GD request.";
590 }
591
592 LOG(LS_INFO) << "VAdapt GD Request: "
593 << (DOWNGRADE == request ? "down" :
594 (UPGRADE == request ? "up" : "keep"))
595 << " From: " << width << "x" << height
596 << " Pixels: " << encoder_desired_num_pixels_
597 << " Changed: " << (changed ? "true" : "false")
598 << " To: " << new_width << "x" << new_height;
599}
600
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000601// A Bandwidth GD request for new resolution
602void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000603 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000604 if (!cpu_adaptation_) {
605 return;
606 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000607 // Update how many times we have downgraded due to the cpu load.
608 switch (request) {
609 case DOWNGRADE:
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000610 // Ignore downgrades if we have downgraded the maximum times.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000611 if (cpu_downgrade_count_ < kMaxCpuDowngrades) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000612 ++cpu_downgrade_count_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000613 } else {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000614 LOG(LS_VERBOSE) << "VAdapt CPU load high but do not downgrade "
615 "because maximum downgrades reached";
616 SignalCpuAdaptationUnable();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000617 }
618 break;
619 case UPGRADE:
620 if (cpu_downgrade_count_ > 0) {
621 bool is_min = IsMinimumFormat(cpu_desired_num_pixels_);
622 if (is_min) {
623 --cpu_downgrade_count_;
624 } else {
625 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
626 "because cpu is not limiting resolution";
627 }
628 } else {
629 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
630 "because minimum downgrades reached";
631 }
632 break;
633 case KEEP:
634 default:
635 break;
636 }
637 if (KEEP != request) {
638 // TODO(fbarchard): compute stepping up/down from OutputNumPixels but
639 // clamp to inputpixels / 4 (2 steps)
640 cpu_desired_num_pixels_ = cpu_downgrade_count_ == 0 ? INT_MAX :
641 static_cast<int>(input_format().width * input_format().height >>
642 cpu_downgrade_count_);
643 }
644 int new_width, new_height;
645 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
646 LOG(LS_INFO) << "VAdapt CPU Request: "
647 << (DOWNGRADE == request ? "down" :
648 (UPGRADE == request ? "up" : "keep"))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000649 << " Steps: " << cpu_downgrade_count_
650 << " Changed: " << (changed ? "true" : "false")
651 << " To: " << new_width << "x" << new_height;
652}
653
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000654// A CPU request for new resolution
655// TODO(fbarchard): Move outside adapter.
656void CoordinatedVideoAdapter::OnCpuLoadUpdated(
657 int current_cpus, int max_cpus, float process_load, float system_load) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000658 rtc::CritScope cs(&request_critical_section_);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000659 if (!cpu_adaptation_) {
660 return;
661 }
662 // Update the moving average of system load. Even if we aren't smoothing,
663 // we'll still calculate this information, in case smoothing is later enabled.
664 system_load_average_ = kCpuLoadWeightCoefficient * system_load +
665 (1.0f - kCpuLoadWeightCoefficient) * system_load_average_;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000666 ++cpu_load_num_samples_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000667 if (cpu_smoothing_) {
668 system_load = system_load_average_;
669 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000670 AdaptRequest request = FindCpuRequest(current_cpus, max_cpus,
671 process_load, system_load);
672 // Make sure we're not adapting too quickly.
673 if (request != KEEP) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000674 if (cpu_load_num_samples_ < cpu_load_min_samples_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000675 LOG(LS_VERBOSE) << "VAdapt CPU load high/low but do not adapt until "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000676 << (cpu_load_min_samples_ - cpu_load_num_samples_)
677 << " more samples";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000678 request = KEEP;
679 }
680 }
681
682 OnCpuResolutionRequest(request);
683}
684
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685// Called by cpu adapter on up requests.
686bool CoordinatedVideoAdapter::IsMinimumFormat(int pixels) {
687 // Find closest scale factor that matches input resolution to min_num_pixels
688 // and set that for output resolution. This is not needed for VideoAdapter,
689 // but provides feedback to unittests and users on expected resolution.
690 // Actual resolution is based on input frame.
691 VideoFormat new_output = output_format();
692 VideoFormat input = input_format();
693 if (input_format().IsSize0x0()) {
694 input = new_output;
695 }
696 float scale = 1.0f;
697 if (!input.IsSize0x0()) {
698 scale = FindClosestScale(input.width,
699 input.height,
700 pixels);
701 }
702 new_output.width = static_cast<int>(input.width * scale + .5f);
703 new_output.height = static_cast<int>(input.height * scale + .5f);
704 int new_pixels = new_output.width * new_output.height;
705 int num_pixels = GetOutputNumPixels();
706 return new_pixels <= num_pixels;
707}
708
709// Called by all coordinators when there is a change.
710bool CoordinatedVideoAdapter::AdaptToMinimumFormat(int* new_width,
711 int* new_height) {
712 VideoFormat new_output = output_format();
713 VideoFormat input = input_format();
714 if (input_format().IsSize0x0()) {
715 input = new_output;
716 }
717 int old_num_pixels = GetOutputNumPixels();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000718 int min_num_pixels = INT_MAX;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000719 adapt_reason_ = ADAPTREASON_NONE;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000720
721 // Reduce resolution based on encoder bandwidth (GD).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 if (encoder_desired_num_pixels_ &&
723 (encoder_desired_num_pixels_ < min_num_pixels)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000724 adapt_reason_ |= ADAPTREASON_BANDWIDTH;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725 min_num_pixels = encoder_desired_num_pixels_;
726 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000727 // Reduce resolution based on CPU.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 if (cpu_adaptation_ && cpu_desired_num_pixels_ &&
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000729 (cpu_desired_num_pixels_ <= min_num_pixels)) {
730 if (cpu_desired_num_pixels_ < min_num_pixels) {
731 adapt_reason_ = ADAPTREASON_CPU;
732 } else {
733 adapt_reason_ |= ADAPTREASON_CPU;
734 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735 min_num_pixels = cpu_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000737 // Round resolution for GD or CPU to allow 1/2 to map to 9/16.
738 if (!input.IsSize0x0() && min_num_pixels != INT_MAX) {
739 float scale = FindClosestScale(input.width, input.height, min_num_pixels);
740 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
741 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000742 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000743 // Reduce resolution based on View Request.
744 if (view_desired_num_pixels_ <= min_num_pixels) {
745 if (view_desired_num_pixels_ < min_num_pixels) {
746 adapt_reason_ = ADAPTREASON_VIEW;
747 } else {
748 adapt_reason_ |= ADAPTREASON_VIEW;
749 }
750 min_num_pixels = view_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000751 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000752 // Snap to a scale factor.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753 float scale = 1.0f;
754 if (!input.IsSize0x0()) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000755 scale = FindLowerScale(input.width, input.height, min_num_pixels);
756 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
757 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000758 }
759 if (scale == 1.0f) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000760 adapt_reason_ = ADAPTREASON_NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000761 }
762 *new_width = new_output.width = static_cast<int>(input.width * scale + .5f);
763 *new_height = new_output.height = static_cast<int>(input.height * scale +
764 .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000765 SetOutputNumPixels(min_num_pixels);
766
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000767 new_output.interval = view_desired_interval_;
768 SetOutputFormat(new_output);
769 int new_num_pixels = GetOutputNumPixels();
770 bool changed = new_num_pixels != old_num_pixels;
771
772 static const char* kReasons[8] = {
773 "None",
774 "CPU",
775 "BANDWIDTH",
776 "CPU+BANDWIDTH",
777 "VIEW",
778 "CPU+VIEW",
779 "BANDWIDTH+VIEW",
780 "CPU+BANDWIDTH+VIEW",
781 };
782
783 LOG(LS_VERBOSE) << "VAdapt Status View: " << view_desired_num_pixels_
784 << " GD: " << encoder_desired_num_pixels_
785 << " CPU: " << cpu_desired_num_pixels_
786 << " Pixels: " << min_num_pixels
787 << " Input: " << input.width
788 << "x" << input.height
789 << " Scale: " << scale
790 << " Resolution: " << new_output.width
791 << "x" << new_output.height
792 << " Changed: " << (changed ? "true" : "false")
793 << " Reason: " << kReasons[adapt_reason_];
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000794
795 if (changed) {
796 // When any adaptation occurs, historic CPU load levels are no longer
797 // accurate. Clear out our state so we can re-learn at the new normal.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000798 cpu_load_num_samples_ = 0;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000799 system_load_average_ = kCpuLoadInitialAverage;
800 }
801
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000802 return changed;
803}
804
805} // namespace cricket