blob: 9b437e4878046cb00e2a6cd6de13ac81df41ac1e [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
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000031#include <algorithm>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000032
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000033#include "talk/media/base/constants.h"
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +000034#include "talk/media/base/videocommon.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000035#include "talk/media/base/videoframe.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000036#include "webrtc/base/logging.h"
37#include "webrtc/base/timeutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000038
39namespace cricket {
40
41// TODO(fbarchard): Make downgrades settable
42static const int kMaxCpuDowngrades = 2; // Downgrade at most 2 times for CPU.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +000043// The number of cpu samples to require before adapting. This value depends on
44// the cpu monitor sampling frequency being 2000ms.
45static const int kCpuLoadMinSamples = 3;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000046// The amount of weight to give to each new cpu load sample. The lower the
47// value, the slower we'll adapt to changing cpu conditions.
48static const float kCpuLoadWeightCoefficient = 0.4f;
49// The seed value for the cpu load moving average.
50static const float kCpuLoadInitialAverage = 0.5f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052// Desktop needs 1/8 scale for HD (1280 x 720) to QQVGA (160 x 90)
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000053static const float kScaleFactors[] = {
54 1.f / 1.f, // Full size.
55 3.f / 4.f, // 3/4 scale.
56 1.f / 2.f, // 1/2 scale.
57 3.f / 8.f, // 3/8 scale.
58 1.f / 4.f, // 1/4 scale.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059 3.f / 16.f, // 3/16 scale.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000060 1.f / 8.f, // 1/8 scale.
61 0.f // End of table.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000064// TODO(fbarchard): Use this table (optionally) for CPU and GD as well.
65static const float kViewScaleFactors[] = {
66 1.f / 1.f, // Full size.
67 3.f / 4.f, // 3/4 scale.
68 2.f / 3.f, // 2/3 scale. // Allow 1080p to 720p.
69 1.f / 2.f, // 1/2 scale.
70 3.f / 8.f, // 3/8 scale.
71 1.f / 3.f, // 1/3 scale. // Allow 1080p to 360p.
72 1.f / 4.f, // 1/4 scale.
73 3.f / 16.f, // 3/16 scale.
74 1.f / 8.f, // 1/8 scale.
75 0.f // End of table.
76};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000077
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000078const float* VideoAdapter::GetViewScaleFactors() const {
79 return scale_third_ ? kViewScaleFactors : kScaleFactors;
80}
81
82// For resolutions that would scale down a little instead of up a little,
83// bias toward scaling up a little. This will tend to choose 3/4 scale instead
84// of 2/3 scale, when the 2/3 is not an exact match.
85static const float kUpBias = -0.9f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086// Find the scale factor that, when applied to width and height, is closest
87// to num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000088float VideoAdapter::FindScale(const float* scale_factors,
89 const float upbias,
90 int width, int height,
91 int target_num_pixels) {
92 const float kMinNumPixels = 160 * 90;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093 if (!target_num_pixels) {
94 return 0.f;
95 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000096 float best_distance = static_cast<float>(INT_MAX);
97 float best_scale = 1.f; // Default to unscaled if nothing matches.
98 float pixels = static_cast<float>(width * height);
99 for (int i = 0; ; ++i) {
100 float scale = scale_factors[i];
101 float test_num_pixels = pixels * scale * scale;
102 // Do not consider scale factors that produce too small images.
103 // Scale factor of 0 at end of table will also exit here.
104 if (test_num_pixels < kMinNumPixels) {
105 break;
106 }
107 float diff = target_num_pixels - test_num_pixels;
108 // If resolution is higher than desired, bias the difference based on
109 // preference for slightly larger for nearest, or avoid completely if
110 // looking for lower resolutions only.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111 if (diff < 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000112 diff = diff * kUpBias;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000113 }
114 if (diff < best_distance) {
115 best_distance = diff;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000116 best_scale = scale;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000117 if (best_distance == 0) { // Found exact match.
118 break;
119 }
120 }
121 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000122 return best_scale;
123}
124
125// Find the closest scale factor.
126float VideoAdapter::FindClosestScale(int width, int height,
127 int target_num_pixels) {
128 return FindScale(kScaleFactors, kUpBias,
129 width, height, target_num_pixels);
130}
131
132// Find the closest view scale factor.
133float VideoAdapter::FindClosestViewScale(int width, int height,
134 int target_num_pixels) {
135 return FindScale(GetViewScaleFactors(), kUpBias,
136 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137}
138
139// Finds the scale factor that, when applied to width and height, produces
140// fewer than num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000141static const float kUpAvoidBias = -1000000000.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000142float VideoAdapter::FindLowerScale(int width, int height,
143 int target_num_pixels) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000144 return FindScale(GetViewScaleFactors(), kUpAvoidBias,
145 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000146}
147
148// There are several frame sizes used by Adapter. This explains them
149// input_format - set once by server to frame size expected from the camera.
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000150// The input frame size is also updated in every call to AdaptFrame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000151// output_format - size that output would like to be. Includes framerate.
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000152// The output frame size is also updated in every call to AdaptFrame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000153// output_num_pixels - size that output should be constrained to. Used to
154// compute output_format from in_frame.
155// in_frame - actual camera captured frame size, which is typically the same
156// as input_format. This can also be rotated or cropped for aspect ratio.
157// out_frame - actual frame output by adapter. Should be a direct scale of
158// in_frame maintaining rotation and aspect ratio.
159// OnOutputFormatRequest - server requests you send this resolution based on
160// view requests.
161// OnEncoderResolutionRequest - encoder requests you send this resolution based
162// on bandwidth
163// OnCpuLoadUpdated - cpu monitor requests you send this resolution based on
164// cpu load.
165
166///////////////////////////////////////////////////////////////////////
167// Implementation of VideoAdapter
168VideoAdapter::VideoAdapter()
169 : output_num_pixels_(INT_MAX),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000170 scale_third_(false),
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000171 frames_in_(0),
172 frames_out_(0),
173 frames_scaled_(0),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000174 adaption_changes_(0),
magjed@webrtc.orga73d7462014-11-14 13:25:25 +0000175 previous_width_(0),
176 previous_height_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000177 black_output_(false),
178 is_black_(false),
179 interval_next_frame_(0) {
180}
181
182VideoAdapter::~VideoAdapter() {
183}
184
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000185void VideoAdapter::SetInputFormat(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000187 int64 old_input_interval = input_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000188 input_format_ = format;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000189 output_format_.interval =
190 std::max(output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000191 if (old_input_interval != input_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000192 LOG(LS_INFO) << "VAdapt input interval changed from "
193 << old_input_interval << " to " << input_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000194 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000195}
196
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000197void CoordinatedVideoAdapter::SetInputFormat(const VideoFormat& format) {
198 int previous_width = input_format().width;
199 int previous_height = input_format().height;
200 bool is_resolution_change = previous_width > 0 && format.width > 0 &&
201 (previous_width != format.width ||
202 previous_height != format.height);
203 VideoAdapter::SetInputFormat(format);
204 if (is_resolution_change) {
205 int width, height;
206 // Trigger the adaptation logic again, to potentially reset the adaptation
207 // state for things like view requests that may not longer be capping
208 // output (or may now cap output).
209 AdaptToMinimumFormat(&width, &height);
210 LOG(LS_INFO) << "VAdapt Input Resolution Change: "
211 << "Previous input resolution: "
212 << previous_width << "x" << previous_height
213 << " New input resolution: "
214 << format.width << "x" << format.height
215 << " New output resolution: "
216 << width << "x" << height;
217 }
218}
219
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000220void CoordinatedVideoAdapter::set_cpu_smoothing(bool enable) {
221 LOG(LS_INFO) << "CPU smoothing is now "
222 << (enable ? "enabled" : "disabled");
223 cpu_smoothing_ = enable;
224}
225
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000226void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000227 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000228 int64 old_output_interval = output_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000229 output_format_ = format;
230 output_num_pixels_ = output_format_.width * output_format_.height;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000231 output_format_.interval =
232 std::max(output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000233 if (old_output_interval != output_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000234 LOG(LS_INFO) << "VAdapt output interval changed from "
235 << old_output_interval << " to " << output_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000236 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000237}
238
239const VideoFormat& VideoAdapter::input_format() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000240 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000241 return input_format_;
242}
243
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000244bool VideoAdapter::drops_all_frames() const {
245 return output_num_pixels_ == 0;
246}
247
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000248const VideoFormat& VideoAdapter::output_format() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000249 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000250 return output_format_;
251}
252
253void VideoAdapter::SetBlackOutput(bool black) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000254 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000255 black_output_ = black;
256}
257
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000258bool VideoAdapter::IsBlackOutput() {
259 rtc::CritScope cs(&critical_section_);
260 return black_output_;
261}
262
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000263// Constrain output resolution to this many pixels overall
264void VideoAdapter::SetOutputNumPixels(int num_pixels) {
265 output_num_pixels_ = num_pixels;
266}
267
268int VideoAdapter::GetOutputNumPixels() const {
269 return output_num_pixels_;
270}
271
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000272VideoFormat VideoAdapter::AdaptFrameResolution(int in_width, int in_height) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000273 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000274 ++frames_in_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000276 SetInputFormat(VideoFormat(
277 in_width, in_height, input_format_.interval, input_format_.fourcc));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000278
279 // Drop the input frame if necessary.
280 bool should_drop = false;
281 if (!output_num_pixels_) {
282 // Drop all frames as the output format is 0x0.
283 should_drop = true;
284 } else {
285 // Drop some frames based on input fps and output fps.
286 // Normally output fps is less than input fps.
287 // TODO(fbarchard): Consider adjusting interval to reflect the adjusted
288 // interval between frames after dropping some frames.
289 interval_next_frame_ += input_format_.interval;
290 if (output_format_.interval > 0) {
291 if (interval_next_frame_ >= output_format_.interval) {
292 interval_next_frame_ %= output_format_.interval;
293 } else {
294 should_drop = true;
295 }
296 }
297 }
298 if (should_drop) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000299 // Show VAdapt log every 90 frames dropped. (3 seconds)
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000300 if ((frames_in_ - frames_out_) % 90 == 0) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000301 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
302 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000303 LOG(LS_INFO) << "VAdapt Drop Frame: scaled " << frames_scaled_
304 << " / out " << frames_out_
305 << " / in " << frames_in_
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000306 << " Changes: " << adaption_changes_
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000307 << " Input: " << in_width
308 << "x" << in_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000309 << " i" << input_format_.interval
310 << " Output: i" << output_format_.interval;
311 }
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000312
313 return VideoFormat(); // Drop frame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000314 }
315
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000316 const float scale = VideoAdapter::FindClosestViewScale(
317 in_width, in_height, output_num_pixels_);
318 const int output_width = static_cast<int>(in_width * scale + .5f);
319 const int output_height = static_cast<int>(in_height * scale + .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000320
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000321 ++frames_out_;
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000322 if (scale != 1)
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000323 ++frames_scaled_;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000324 // Show VAdapt log every 90 frames output. (3 seconds)
325 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
326 // for LS_VERBOSE and more for LS_INFO.
327 bool show = (frames_out_) % 90 == 0;
328
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000329 // TODO(fbarchard): LOG the previous output resolution and track input
330 // resolution changes as well. Consider dropping the statistics into their
331 // own class which could be queried publically.
332 bool changed = false;
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000333 if (previous_width_ && (previous_width_ != output_width ||
334 previous_height_ != output_height)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000335 show = true;
336 ++adaption_changes_;
337 changed = true;
338 }
339 if (show) {
340 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
341 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000342 LOG(LS_INFO) << "VAdapt Frame: scaled " << frames_scaled_
343 << " / out " << frames_out_
344 << " / in " << frames_in_
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000345 << " Changes: " << adaption_changes_
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000346 << " Input: " << in_width
347 << "x" << in_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000348 << " i" << input_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000349 << " Scale: " << scale
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000350 << " Output: " << output_width
351 << "x" << output_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000352 << " i" << output_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000353 << " Changed: " << (changed ? "true" : "false");
354 }
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000355
356 output_format_.width = output_width;
357 output_format_.height = output_height;
358 previous_width_ = output_width;
359 previous_height_ = output_height;
360
361 return output_format_;
362}
363
364// TODO(fbarchard): Add AdaptFrameRate function that only drops frames but
365// not resolution.
366bool VideoAdapter::AdaptFrame(VideoFrame* in_frame, VideoFrame** out_frame) {
367 if (!in_frame || !out_frame)
368 return false;
369
370 const VideoFormat adapted_format =
371 AdaptFrameResolution(static_cast<int>(in_frame->GetWidth()),
372 static_cast<int>(in_frame->GetHeight()));
373
374 rtc::CritScope cs(&critical_section_);
375 if (adapted_format.IsSize0x0()) {
376 *out_frame = NULL;
377 return true;
378 }
379
380 if (!black_output_ &&
381 in_frame->GetWidth() == static_cast<size_t>(adapted_format.width) &&
382 in_frame->GetHeight() == static_cast<size_t>(adapted_format.height)) {
383 // The dimensions are correct and we aren't muting, so use the input frame.
384 *out_frame = in_frame;
385 } else {
386 if (!StretchToOutputFrame(in_frame)) {
387 LOG(LS_VERBOSE) << "VAdapt Stretch Failed.";
388 return false;
389 }
390
391 *out_frame = output_frame_.get();
392 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000393
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000394 return true;
395}
396
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000397void VideoAdapter::set_scale_third(bool enable) {
398 LOG(LS_INFO) << "Video Adapter third scaling is now "
399 << (enable ? "enabled" : "disabled");
400 scale_third_ = enable;
401}
402
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000403// Scale or Blacken the frame. Returns true if successful.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000404bool VideoAdapter::StretchToOutputFrame(const VideoFrame* in_frame) {
405 int output_width = output_format_.width;
406 int output_height = output_format_.height;
407
408 // Create and stretch the output frame if it has not been created yet or its
409 // size is not same as the expected.
410 bool stretched = false;
411 if (!output_frame_ ||
412 output_frame_->GetWidth() != static_cast<size_t>(output_width) ||
413 output_frame_->GetHeight() != static_cast<size_t>(output_height)) {
414 output_frame_.reset(
415 in_frame->Stretch(output_width, output_height, true, true));
416 if (!output_frame_) {
417 LOG(LS_WARNING) << "Adapter failed to stretch frame to "
418 << output_width << "x" << output_height;
419 return false;
420 }
421 stretched = true;
422 is_black_ = false;
423 }
424
425 if (!black_output_) {
426 if (!stretched) {
427 // The output frame does not need to be blacken and has not been stretched
428 // from the input frame yet, stretch the input frame. This is the most
429 // common case.
430 in_frame->StretchToFrame(output_frame_.get(), true, true);
431 }
432 is_black_ = false;
433 } else {
434 if (!is_black_) {
435 output_frame_->SetToBlack();
436 is_black_ = true;
437 }
438 output_frame_->SetElapsedTime(in_frame->GetElapsedTime());
439 output_frame_->SetTimeStamp(in_frame->GetTimeStamp());
440 }
441
442 return true;
443}
444
445///////////////////////////////////////////////////////////////////////
446// Implementation of CoordinatedVideoAdapter
447CoordinatedVideoAdapter::CoordinatedVideoAdapter()
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000448 : cpu_adaptation_(true),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000449 cpu_smoothing_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000450 gd_adaptation_(true),
451 view_adaptation_(true),
452 view_switch_(false),
453 cpu_downgrade_count_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000454 cpu_load_min_samples_(kCpuLoadMinSamples),
455 cpu_load_num_samples_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000456 high_system_threshold_(kHighSystemCpuThreshold),
457 low_system_threshold_(kLowSystemCpuThreshold),
458 process_threshold_(kProcessCpuThreshold),
459 view_desired_num_pixels_(INT_MAX),
460 view_desired_interval_(0),
461 encoder_desired_num_pixels_(INT_MAX),
462 cpu_desired_num_pixels_(INT_MAX),
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000463 adapt_reason_(ADAPTREASON_NONE),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000464 system_load_average_(kCpuLoadInitialAverage) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000465}
466
467// Helper function to UPGRADE or DOWNGRADE a number of pixels
468void CoordinatedVideoAdapter::StepPixelCount(
469 CoordinatedVideoAdapter::AdaptRequest request,
470 int* num_pixels) {
471 switch (request) {
472 case CoordinatedVideoAdapter::DOWNGRADE:
473 *num_pixels /= 2;
474 break;
475
476 case CoordinatedVideoAdapter::UPGRADE:
477 *num_pixels *= 2;
478 break;
479
480 default: // No change in pixel count
481 break;
482 }
483 return;
484}
485
486// Find the adaptation request of the cpu based on the load. Return UPGRADE if
487// the load is low, DOWNGRADE if the load is high, and KEEP otherwise.
488CoordinatedVideoAdapter::AdaptRequest CoordinatedVideoAdapter::FindCpuRequest(
489 int current_cpus, int max_cpus,
490 float process_load, float system_load) {
491 // Downgrade if system is high and plugin is at least more than midrange.
492 if (system_load >= high_system_threshold_ * max_cpus &&
493 process_load >= process_threshold_ * current_cpus) {
494 return CoordinatedVideoAdapter::DOWNGRADE;
495 // Upgrade if system is low.
496 } else if (system_load < low_system_threshold_ * max_cpus) {
497 return CoordinatedVideoAdapter::UPGRADE;
498 }
499 return CoordinatedVideoAdapter::KEEP;
500}
501
502// A remote view request for a new resolution.
503void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000504 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000505 if (!view_adaptation_) {
506 return;
507 }
508 // Set output for initial aspect ratio in mediachannel unittests.
509 int old_num_pixels = GetOutputNumPixels();
510 SetOutputFormat(format);
511 SetOutputNumPixels(old_num_pixels);
512 view_desired_num_pixels_ = format.width * format.height;
513 view_desired_interval_ = format.interval;
514 int new_width, new_height;
515 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
516 LOG(LS_INFO) << "VAdapt View Request: "
517 << format.width << "x" << format.height
518 << " Pixels: " << view_desired_num_pixels_
519 << " Changed: " << (changed ? "true" : "false")
520 << " To: " << new_width << "x" << new_height;
521}
522
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000523void CoordinatedVideoAdapter::set_cpu_load_min_samples(
524 int cpu_load_min_samples) {
525 if (cpu_load_min_samples_ != cpu_load_min_samples) {
526 LOG(LS_INFO) << "VAdapt Change Cpu Adapt Min Samples from: "
527 << cpu_load_min_samples_ << " to "
528 << cpu_load_min_samples;
529 cpu_load_min_samples_ = cpu_load_min_samples;
530 }
531}
532
533void CoordinatedVideoAdapter::set_high_system_threshold(
534 float high_system_threshold) {
535 ASSERT(high_system_threshold <= 1.0f);
536 ASSERT(high_system_threshold >= 0.0f);
537 if (high_system_threshold_ != high_system_threshold) {
538 LOG(LS_INFO) << "VAdapt Change High System Threshold from: "
539 << high_system_threshold_ << " to " << high_system_threshold;
540 high_system_threshold_ = high_system_threshold;
541 }
542}
543
544void CoordinatedVideoAdapter::set_low_system_threshold(
545 float low_system_threshold) {
546 ASSERT(low_system_threshold <= 1.0f);
547 ASSERT(low_system_threshold >= 0.0f);
548 if (low_system_threshold_ != low_system_threshold) {
549 LOG(LS_INFO) << "VAdapt Change Low System Threshold from: "
550 << low_system_threshold_ << " to " << low_system_threshold;
551 low_system_threshold_ = low_system_threshold;
552 }
553}
554
555void CoordinatedVideoAdapter::set_process_threshold(float process_threshold) {
556 ASSERT(process_threshold <= 1.0f);
557 ASSERT(process_threshold >= 0.0f);
558 if (process_threshold_ != process_threshold) {
559 LOG(LS_INFO) << "VAdapt Change High Process Threshold from: "
560 << process_threshold_ << " to " << process_threshold;
561 process_threshold_ = process_threshold;
562 }
563}
564
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000565// A Bandwidth GD request for new resolution
566void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
567 int width, int height, AdaptRequest request) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000568 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000569 if (!gd_adaptation_) {
570 return;
571 }
572 int old_encoder_desired_num_pixels = encoder_desired_num_pixels_;
573 if (KEEP != request) {
574 int new_encoder_desired_num_pixels = width * height;
575 int old_num_pixels = GetOutputNumPixels();
576 if (new_encoder_desired_num_pixels != old_num_pixels) {
577 LOG(LS_VERBOSE) << "VAdapt GD resolution stale. Ignored";
578 } else {
579 // Update the encoder desired format based on the request.
580 encoder_desired_num_pixels_ = new_encoder_desired_num_pixels;
581 StepPixelCount(request, &encoder_desired_num_pixels_);
582 }
583 }
584 int new_width, new_height;
585 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
586
587 // Ignore up or keep if no change.
588 if (DOWNGRADE != request && view_switch_ && !changed) {
589 encoder_desired_num_pixels_ = old_encoder_desired_num_pixels;
590 LOG(LS_VERBOSE) << "VAdapt ignoring GD request.";
591 }
592
593 LOG(LS_INFO) << "VAdapt GD Request: "
594 << (DOWNGRADE == request ? "down" :
595 (UPGRADE == request ? "up" : "keep"))
596 << " From: " << width << "x" << height
597 << " Pixels: " << encoder_desired_num_pixels_
598 << " Changed: " << (changed ? "true" : "false")
599 << " To: " << new_width << "x" << new_height;
600}
601
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000602// A Bandwidth GD request for new resolution
603void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000604 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605 if (!cpu_adaptation_) {
606 return;
607 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000608 // Update how many times we have downgraded due to the cpu load.
609 switch (request) {
610 case DOWNGRADE:
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000611 // Ignore downgrades if we have downgraded the maximum times.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000612 if (cpu_downgrade_count_ < kMaxCpuDowngrades) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000613 ++cpu_downgrade_count_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000614 } else {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000615 LOG(LS_VERBOSE) << "VAdapt CPU load high but do not downgrade "
616 "because maximum downgrades reached";
617 SignalCpuAdaptationUnable();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000618 }
619 break;
620 case UPGRADE:
621 if (cpu_downgrade_count_ > 0) {
622 bool is_min = IsMinimumFormat(cpu_desired_num_pixels_);
623 if (is_min) {
624 --cpu_downgrade_count_;
625 } else {
626 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
627 "because cpu is not limiting resolution";
628 }
629 } else {
630 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
631 "because minimum downgrades reached";
632 }
633 break;
634 case KEEP:
635 default:
636 break;
637 }
638 if (KEEP != request) {
639 // TODO(fbarchard): compute stepping up/down from OutputNumPixels but
640 // clamp to inputpixels / 4 (2 steps)
641 cpu_desired_num_pixels_ = cpu_downgrade_count_ == 0 ? INT_MAX :
642 static_cast<int>(input_format().width * input_format().height >>
643 cpu_downgrade_count_);
644 }
645 int new_width, new_height;
646 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
647 LOG(LS_INFO) << "VAdapt CPU Request: "
648 << (DOWNGRADE == request ? "down" :
649 (UPGRADE == request ? "up" : "keep"))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000650 << " Steps: " << cpu_downgrade_count_
651 << " Changed: " << (changed ? "true" : "false")
652 << " To: " << new_width << "x" << new_height;
653}
654
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000655// A CPU request for new resolution
656// TODO(fbarchard): Move outside adapter.
657void CoordinatedVideoAdapter::OnCpuLoadUpdated(
658 int current_cpus, int max_cpus, float process_load, float system_load) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000659 rtc::CritScope cs(&request_critical_section_);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000660 if (!cpu_adaptation_) {
661 return;
662 }
663 // Update the moving average of system load. Even if we aren't smoothing,
664 // we'll still calculate this information, in case smoothing is later enabled.
665 system_load_average_ = kCpuLoadWeightCoefficient * system_load +
666 (1.0f - kCpuLoadWeightCoefficient) * system_load_average_;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000667 ++cpu_load_num_samples_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000668 if (cpu_smoothing_) {
669 system_load = system_load_average_;
670 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000671 AdaptRequest request = FindCpuRequest(current_cpus, max_cpus,
672 process_load, system_load);
673 // Make sure we're not adapting too quickly.
674 if (request != KEEP) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000675 if (cpu_load_num_samples_ < cpu_load_min_samples_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000676 LOG(LS_VERBOSE) << "VAdapt CPU load high/low but do not adapt until "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000677 << (cpu_load_min_samples_ - cpu_load_num_samples_)
678 << " more samples";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000679 request = KEEP;
680 }
681 }
682
683 OnCpuResolutionRequest(request);
684}
685
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000686// Called by cpu adapter on up requests.
687bool CoordinatedVideoAdapter::IsMinimumFormat(int pixels) {
688 // Find closest scale factor that matches input resolution to min_num_pixels
689 // and set that for output resolution. This is not needed for VideoAdapter,
690 // but provides feedback to unittests and users on expected resolution.
691 // Actual resolution is based on input frame.
692 VideoFormat new_output = output_format();
693 VideoFormat input = input_format();
694 if (input_format().IsSize0x0()) {
695 input = new_output;
696 }
697 float scale = 1.0f;
698 if (!input.IsSize0x0()) {
699 scale = FindClosestScale(input.width,
700 input.height,
701 pixels);
702 }
703 new_output.width = static_cast<int>(input.width * scale + .5f);
704 new_output.height = static_cast<int>(input.height * scale + .5f);
705 int new_pixels = new_output.width * new_output.height;
706 int num_pixels = GetOutputNumPixels();
707 return new_pixels <= num_pixels;
708}
709
710// Called by all coordinators when there is a change.
711bool CoordinatedVideoAdapter::AdaptToMinimumFormat(int* new_width,
712 int* new_height) {
713 VideoFormat new_output = output_format();
714 VideoFormat input = input_format();
715 if (input_format().IsSize0x0()) {
716 input = new_output;
717 }
718 int old_num_pixels = GetOutputNumPixels();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000719 int min_num_pixels = INT_MAX;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000720 adapt_reason_ = ADAPTREASON_NONE;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000721
722 // Reduce resolution based on encoder bandwidth (GD).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 if (encoder_desired_num_pixels_ &&
724 (encoder_desired_num_pixels_ < min_num_pixels)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000725 adapt_reason_ |= ADAPTREASON_BANDWIDTH;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726 min_num_pixels = encoder_desired_num_pixels_;
727 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000728 // Reduce resolution based on CPU.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729 if (cpu_adaptation_ && cpu_desired_num_pixels_ &&
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000730 (cpu_desired_num_pixels_ <= min_num_pixels)) {
731 if (cpu_desired_num_pixels_ < min_num_pixels) {
732 adapt_reason_ = ADAPTREASON_CPU;
733 } else {
734 adapt_reason_ |= ADAPTREASON_CPU;
735 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736 min_num_pixels = cpu_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000737 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000738 // Round resolution for GD or CPU to allow 1/2 to map to 9/16.
739 if (!input.IsSize0x0() && min_num_pixels != INT_MAX) {
740 float scale = FindClosestScale(input.width, input.height, min_num_pixels);
741 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
742 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000744 // Reduce resolution based on View Request.
745 if (view_desired_num_pixels_ <= min_num_pixels) {
746 if (view_desired_num_pixels_ < min_num_pixels) {
747 adapt_reason_ = ADAPTREASON_VIEW;
748 } else {
749 adapt_reason_ |= ADAPTREASON_VIEW;
750 }
751 min_num_pixels = view_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000753 // Snap to a scale factor.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754 float scale = 1.0f;
755 if (!input.IsSize0x0()) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000756 scale = FindLowerScale(input.width, input.height, min_num_pixels);
757 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
758 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000759 }
760 if (scale == 1.0f) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000761 adapt_reason_ = ADAPTREASON_NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762 }
763 *new_width = new_output.width = static_cast<int>(input.width * scale + .5f);
764 *new_height = new_output.height = static_cast<int>(input.height * scale +
765 .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000766 SetOutputNumPixels(min_num_pixels);
767
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000768 new_output.interval = view_desired_interval_;
769 SetOutputFormat(new_output);
770 int new_num_pixels = GetOutputNumPixels();
771 bool changed = new_num_pixels != old_num_pixels;
772
773 static const char* kReasons[8] = {
774 "None",
775 "CPU",
776 "BANDWIDTH",
777 "CPU+BANDWIDTH",
778 "VIEW",
779 "CPU+VIEW",
780 "BANDWIDTH+VIEW",
781 "CPU+BANDWIDTH+VIEW",
782 };
783
784 LOG(LS_VERBOSE) << "VAdapt Status View: " << view_desired_num_pixels_
785 << " GD: " << encoder_desired_num_pixels_
786 << " CPU: " << cpu_desired_num_pixels_
787 << " Pixels: " << min_num_pixels
788 << " Input: " << input.width
789 << "x" << input.height
790 << " Scale: " << scale
791 << " Resolution: " << new_output.width
792 << "x" << new_output.height
793 << " Changed: " << (changed ? "true" : "false")
794 << " Reason: " << kReasons[adapt_reason_];
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000795
796 if (changed) {
797 // When any adaptation occurs, historic CPU load levels are no longer
798 // accurate. Clear out our state so we can re-learn at the new normal.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000799 cpu_load_num_samples_ = 0;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000800 system_load_average_ = kCpuLoadInitialAverage;
801 }
802
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000803 return changed;
804}
805
806} // namespace cricket