blob: 7fdf25446e5e5763165f80fa68c5c3df7b2946e4 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001// libjingle
2// Copyright 2010 Google Inc.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are met:
6//
7// 1. Redistributions of source code must retain the above copyright notice,
8// this list of conditions and the following disclaimer.
9// 2. Redistributions in binary form must reproduce the above copyright notice,
10// this list of conditions and the following disclaimer in the documentation
11// and/or other materials provided with the distribution.
12// 3. The name of the author may not be used to endorse or promote products
13// derived from this software without specific prior written permission.
14//
15// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
16// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
17// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
18// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
21// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
24// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
26#include "talk/media/base/videoadapter.h"
27
28#include <limits.h> // For INT_MAX
29
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000030#include "talk/media/base/constants.h"
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +000031#include "talk/media/base/videocommon.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000032#include "talk/media/base/videoframe.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000033#include "webrtc/base/logging.h"
34#include "webrtc/base/timeutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000035
36namespace cricket {
37
38// TODO(fbarchard): Make downgrades settable
39static const int kMaxCpuDowngrades = 2; // Downgrade at most 2 times for CPU.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +000040// The number of cpu samples to require before adapting. This value depends on
41// the cpu monitor sampling frequency being 2000ms.
42static const int kCpuLoadMinSamples = 3;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000043// The amount of weight to give to each new cpu load sample. The lower the
44// value, the slower we'll adapt to changing cpu conditions.
45static const float kCpuLoadWeightCoefficient = 0.4f;
46// The seed value for the cpu load moving average.
47static const float kCpuLoadInitialAverage = 0.5f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000048
henrike@webrtc.org28e20752013-07-10 00:45:36 +000049// Desktop needs 1/8 scale for HD (1280 x 720) to QQVGA (160 x 90)
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000050static const float kScaleFactors[] = {
51 1.f / 1.f, // Full size.
52 3.f / 4.f, // 3/4 scale.
53 1.f / 2.f, // 1/2 scale.
54 3.f / 8.f, // 3/8 scale.
55 1.f / 4.f, // 1/4 scale.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056 3.f / 16.f, // 3/16 scale.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000057 1.f / 8.f, // 1/8 scale.
58 0.f // End of table.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000061// TODO(fbarchard): Use this table (optionally) for CPU and GD as well.
62static const float kViewScaleFactors[] = {
63 1.f / 1.f, // Full size.
64 3.f / 4.f, // 3/4 scale.
65 2.f / 3.f, // 2/3 scale. // Allow 1080p to 720p.
66 1.f / 2.f, // 1/2 scale.
67 3.f / 8.f, // 3/8 scale.
68 1.f / 3.f, // 1/3 scale. // Allow 1080p to 360p.
69 1.f / 4.f, // 1/4 scale.
70 3.f / 16.f, // 3/16 scale.
71 1.f / 8.f, // 1/8 scale.
72 0.f // End of table.
73};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000075const float* VideoAdapter::GetViewScaleFactors() const {
76 return scale_third_ ? kViewScaleFactors : kScaleFactors;
77}
78
79// For resolutions that would scale down a little instead of up a little,
80// bias toward scaling up a little. This will tend to choose 3/4 scale instead
81// of 2/3 scale, when the 2/3 is not an exact match.
82static const float kUpBias = -0.9f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000083// Find the scale factor that, when applied to width and height, is closest
84// to num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000085float VideoAdapter::FindScale(const float* scale_factors,
86 const float upbias,
87 int width, int height,
88 int target_num_pixels) {
89 const float kMinNumPixels = 160 * 90;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090 if (!target_num_pixels) {
91 return 0.f;
92 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000093 float best_distance = static_cast<float>(INT_MAX);
94 float best_scale = 1.f; // Default to unscaled if nothing matches.
95 float pixels = static_cast<float>(width * height);
96 for (int i = 0; ; ++i) {
97 float scale = scale_factors[i];
98 float test_num_pixels = pixels * scale * scale;
99 // Do not consider scale factors that produce too small images.
100 // Scale factor of 0 at end of table will also exit here.
101 if (test_num_pixels < kMinNumPixels) {
102 break;
103 }
104 float diff = target_num_pixels - test_num_pixels;
105 // If resolution is higher than desired, bias the difference based on
106 // preference for slightly larger for nearest, or avoid completely if
107 // looking for lower resolutions only.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 if (diff < 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000109 diff = diff * kUpBias;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 }
111 if (diff < best_distance) {
112 best_distance = diff;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000113 best_scale = scale;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114 if (best_distance == 0) { // Found exact match.
115 break;
116 }
117 }
118 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000119 return best_scale;
120}
121
122// Find the closest scale factor.
123float VideoAdapter::FindClosestScale(int width, int height,
124 int target_num_pixels) {
125 return FindScale(kScaleFactors, kUpBias,
126 width, height, target_num_pixels);
127}
128
129// Find the closest view scale factor.
130float VideoAdapter::FindClosestViewScale(int width, int height,
131 int target_num_pixels) {
132 return FindScale(GetViewScaleFactors(), kUpBias,
133 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134}
135
136// Finds the scale factor that, when applied to width and height, produces
137// fewer than num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000138static const float kUpAvoidBias = -1000000000.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000139float VideoAdapter::FindLowerScale(int width, int height,
140 int target_num_pixels) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000141 return FindScale(GetViewScaleFactors(), kUpAvoidBias,
142 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000143}
144
145// There are several frame sizes used by Adapter. This explains them
146// input_format - set once by server to frame size expected from the camera.
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000147// The input frame size is also updated in every call to AdaptFrame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000148// output_format - size that output would like to be. Includes framerate.
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000149// The output frame size is also updated in every call to AdaptFrame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150// output_num_pixels - size that output should be constrained to. Used to
151// compute output_format from in_frame.
152// in_frame - actual camera captured frame size, which is typically the same
153// as input_format. This can also be rotated or cropped for aspect ratio.
154// out_frame - actual frame output by adapter. Should be a direct scale of
155// in_frame maintaining rotation and aspect ratio.
156// OnOutputFormatRequest - server requests you send this resolution based on
157// view requests.
158// OnEncoderResolutionRequest - encoder requests you send this resolution based
159// on bandwidth
160// OnCpuLoadUpdated - cpu monitor requests you send this resolution based on
161// cpu load.
162
163///////////////////////////////////////////////////////////////////////
164// Implementation of VideoAdapter
165VideoAdapter::VideoAdapter()
166 : output_num_pixels_(INT_MAX),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000167 scale_third_(false),
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000168 frames_in_(0),
169 frames_out_(0),
170 frames_scaled_(0),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000171 adaption_changes_(0),
magjed@webrtc.orga73d7462014-11-14 13:25:25 +0000172 previous_width_(0),
173 previous_height_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000174 black_output_(false),
175 is_black_(false),
176 interval_next_frame_(0) {
177}
178
179VideoAdapter::~VideoAdapter() {
180}
181
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182void VideoAdapter::SetInputFormat(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000183 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000184 int64 old_input_interval = input_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000185 input_format_ = format;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 output_format_.interval = rtc::_max(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000188 if (old_input_interval != input_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000189 LOG(LS_INFO) << "VAdapt input interval changed from "
190 << old_input_interval << " to " << input_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000191 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000192}
193
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000194void CoordinatedVideoAdapter::SetInputFormat(const VideoFormat& format) {
195 int previous_width = input_format().width;
196 int previous_height = input_format().height;
197 bool is_resolution_change = previous_width > 0 && format.width > 0 &&
198 (previous_width != format.width ||
199 previous_height != format.height);
200 VideoAdapter::SetInputFormat(format);
201 if (is_resolution_change) {
202 int width, height;
203 // Trigger the adaptation logic again, to potentially reset the adaptation
204 // state for things like view requests that may not longer be capping
205 // output (or may now cap output).
206 AdaptToMinimumFormat(&width, &height);
207 LOG(LS_INFO) << "VAdapt Input Resolution Change: "
208 << "Previous input resolution: "
209 << previous_width << "x" << previous_height
210 << " New input resolution: "
211 << format.width << "x" << format.height
212 << " New output resolution: "
213 << width << "x" << height;
214 }
215}
216
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000217void CoordinatedVideoAdapter::set_cpu_smoothing(bool enable) {
218 LOG(LS_INFO) << "CPU smoothing is now "
219 << (enable ? "enabled" : "disabled");
220 cpu_smoothing_ = enable;
221}
222
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000223void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000224 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000225 int64 old_output_interval = output_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000226 output_format_ = format;
227 output_num_pixels_ = output_format_.width * output_format_.height;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000228 output_format_.interval = rtc::_max(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000229 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000230 if (old_output_interval != output_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000231 LOG(LS_INFO) << "VAdapt output interval changed from "
232 << old_output_interval << " to " << output_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000233 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000234}
235
236const VideoFormat& VideoAdapter::input_format() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000237 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000238 return input_format_;
239}
240
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000241bool VideoAdapter::drops_all_frames() const {
242 return output_num_pixels_ == 0;
243}
244
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000245const VideoFormat& VideoAdapter::output_format() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000246 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000247 return output_format_;
248}
249
250void VideoAdapter::SetBlackOutput(bool black) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000251 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000252 black_output_ = black;
253}
254
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000255bool VideoAdapter::IsBlackOutput() {
256 rtc::CritScope cs(&critical_section_);
257 return black_output_;
258}
259
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000260// Constrain output resolution to this many pixels overall
261void VideoAdapter::SetOutputNumPixels(int num_pixels) {
262 output_num_pixels_ = num_pixels;
263}
264
265int VideoAdapter::GetOutputNumPixels() const {
266 return output_num_pixels_;
267}
268
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000269VideoFormat VideoAdapter::AdaptFrameResolution(int in_width, int in_height) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000270 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000271 ++frames_in_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000273 SetInputFormat(VideoFormat(
274 in_width, in_height, input_format_.interval, input_format_.fourcc));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275
276 // Drop the input frame if necessary.
277 bool should_drop = false;
278 if (!output_num_pixels_) {
279 // Drop all frames as the output format is 0x0.
280 should_drop = true;
281 } else {
282 // Drop some frames based on input fps and output fps.
283 // Normally output fps is less than input fps.
284 // TODO(fbarchard): Consider adjusting interval to reflect the adjusted
285 // interval between frames after dropping some frames.
286 interval_next_frame_ += input_format_.interval;
287 if (output_format_.interval > 0) {
288 if (interval_next_frame_ >= output_format_.interval) {
289 interval_next_frame_ %= output_format_.interval;
290 } else {
291 should_drop = true;
292 }
293 }
294 }
295 if (should_drop) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000296 // Show VAdapt log every 90 frames dropped. (3 seconds)
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000297 if ((frames_in_ - frames_out_) % 90 == 0) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000298 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
299 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000300 LOG(LS_INFO) << "VAdapt Drop Frame: scaled " << frames_scaled_
301 << " / out " << frames_out_
302 << " / in " << frames_in_
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000303 << " Changes: " << adaption_changes_
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000304 << " Input: " << in_width
305 << "x" << in_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000306 << " i" << input_format_.interval
307 << " Output: i" << output_format_.interval;
308 }
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000309
310 return VideoFormat(); // Drop frame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000311 }
312
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000313 const float scale = VideoAdapter::FindClosestViewScale(
314 in_width, in_height, output_num_pixels_);
315 const int output_width = static_cast<int>(in_width * scale + .5f);
316 const int output_height = static_cast<int>(in_height * scale + .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000317
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000318 ++frames_out_;
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000319 if (scale != 1)
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000320 ++frames_scaled_;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000321 // Show VAdapt log every 90 frames output. (3 seconds)
322 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
323 // for LS_VERBOSE and more for LS_INFO.
324 bool show = (frames_out_) % 90 == 0;
325
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000326 // TODO(fbarchard): LOG the previous output resolution and track input
327 // resolution changes as well. Consider dropping the statistics into their
328 // own class which could be queried publically.
329 bool changed = false;
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000330 if (previous_width_ && (previous_width_ != output_width ||
331 previous_height_ != output_height)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000332 show = true;
333 ++adaption_changes_;
334 changed = true;
335 }
336 if (show) {
337 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
338 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000339 LOG(LS_INFO) << "VAdapt Frame: scaled " << frames_scaled_
340 << " / out " << frames_out_
341 << " / in " << frames_in_
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000342 << " Changes: " << adaption_changes_
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000343 << " Input: " << in_width
344 << "x" << in_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000345 << " i" << input_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000346 << " Scale: " << scale
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000347 << " Output: " << output_width
348 << "x" << output_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000349 << " i" << output_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000350 << " Changed: " << (changed ? "true" : "false");
351 }
magjed@webrtc.orgf58b4552014-11-19 18:09:14 +0000352
353 output_format_.width = output_width;
354 output_format_.height = output_height;
355 previous_width_ = output_width;
356 previous_height_ = output_height;
357
358 return output_format_;
359}
360
361// TODO(fbarchard): Add AdaptFrameRate function that only drops frames but
362// not resolution.
363bool VideoAdapter::AdaptFrame(VideoFrame* in_frame, VideoFrame** out_frame) {
364 if (!in_frame || !out_frame)
365 return false;
366
367 const VideoFormat adapted_format =
368 AdaptFrameResolution(static_cast<int>(in_frame->GetWidth()),
369 static_cast<int>(in_frame->GetHeight()));
370
371 rtc::CritScope cs(&critical_section_);
372 if (adapted_format.IsSize0x0()) {
373 *out_frame = NULL;
374 return true;
375 }
376
377 if (!black_output_ &&
378 in_frame->GetWidth() == static_cast<size_t>(adapted_format.width) &&
379 in_frame->GetHeight() == static_cast<size_t>(adapted_format.height)) {
380 // The dimensions are correct and we aren't muting, so use the input frame.
381 *out_frame = in_frame;
382 } else {
383 if (!StretchToOutputFrame(in_frame)) {
384 LOG(LS_VERBOSE) << "VAdapt Stretch Failed.";
385 return false;
386 }
387
388 *out_frame = output_frame_.get();
389 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000390
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000391 return true;
392}
393
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000394void VideoAdapter::set_scale_third(bool enable) {
395 LOG(LS_INFO) << "Video Adapter third scaling is now "
396 << (enable ? "enabled" : "disabled");
397 scale_third_ = enable;
398}
399
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000400// Scale or Blacken the frame. Returns true if successful.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000401bool VideoAdapter::StretchToOutputFrame(const VideoFrame* in_frame) {
402 int output_width = output_format_.width;
403 int output_height = output_format_.height;
404
405 // Create and stretch the output frame if it has not been created yet or its
406 // size is not same as the expected.
407 bool stretched = false;
408 if (!output_frame_ ||
409 output_frame_->GetWidth() != static_cast<size_t>(output_width) ||
410 output_frame_->GetHeight() != static_cast<size_t>(output_height)) {
411 output_frame_.reset(
412 in_frame->Stretch(output_width, output_height, true, true));
413 if (!output_frame_) {
414 LOG(LS_WARNING) << "Adapter failed to stretch frame to "
415 << output_width << "x" << output_height;
416 return false;
417 }
418 stretched = true;
419 is_black_ = false;
420 }
421
422 if (!black_output_) {
423 if (!stretched) {
424 // The output frame does not need to be blacken and has not been stretched
425 // from the input frame yet, stretch the input frame. This is the most
426 // common case.
427 in_frame->StretchToFrame(output_frame_.get(), true, true);
428 }
429 is_black_ = false;
430 } else {
431 if (!is_black_) {
432 output_frame_->SetToBlack();
433 is_black_ = true;
434 }
435 output_frame_->SetElapsedTime(in_frame->GetElapsedTime());
436 output_frame_->SetTimeStamp(in_frame->GetTimeStamp());
437 }
438
439 return true;
440}
441
442///////////////////////////////////////////////////////////////////////
443// Implementation of CoordinatedVideoAdapter
444CoordinatedVideoAdapter::CoordinatedVideoAdapter()
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000445 : cpu_adaptation_(true),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000446 cpu_smoothing_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000447 gd_adaptation_(true),
448 view_adaptation_(true),
449 view_switch_(false),
450 cpu_downgrade_count_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000451 cpu_load_min_samples_(kCpuLoadMinSamples),
452 cpu_load_num_samples_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000453 high_system_threshold_(kHighSystemCpuThreshold),
454 low_system_threshold_(kLowSystemCpuThreshold),
455 process_threshold_(kProcessCpuThreshold),
456 view_desired_num_pixels_(INT_MAX),
457 view_desired_interval_(0),
458 encoder_desired_num_pixels_(INT_MAX),
459 cpu_desired_num_pixels_(INT_MAX),
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000460 adapt_reason_(ADAPTREASON_NONE),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000461 system_load_average_(kCpuLoadInitialAverage) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000462}
463
464// Helper function to UPGRADE or DOWNGRADE a number of pixels
465void CoordinatedVideoAdapter::StepPixelCount(
466 CoordinatedVideoAdapter::AdaptRequest request,
467 int* num_pixels) {
468 switch (request) {
469 case CoordinatedVideoAdapter::DOWNGRADE:
470 *num_pixels /= 2;
471 break;
472
473 case CoordinatedVideoAdapter::UPGRADE:
474 *num_pixels *= 2;
475 break;
476
477 default: // No change in pixel count
478 break;
479 }
480 return;
481}
482
483// Find the adaptation request of the cpu based on the load. Return UPGRADE if
484// the load is low, DOWNGRADE if the load is high, and KEEP otherwise.
485CoordinatedVideoAdapter::AdaptRequest CoordinatedVideoAdapter::FindCpuRequest(
486 int current_cpus, int max_cpus,
487 float process_load, float system_load) {
488 // Downgrade if system is high and plugin is at least more than midrange.
489 if (system_load >= high_system_threshold_ * max_cpus &&
490 process_load >= process_threshold_ * current_cpus) {
491 return CoordinatedVideoAdapter::DOWNGRADE;
492 // Upgrade if system is low.
493 } else if (system_load < low_system_threshold_ * max_cpus) {
494 return CoordinatedVideoAdapter::UPGRADE;
495 }
496 return CoordinatedVideoAdapter::KEEP;
497}
498
499// A remote view request for a new resolution.
500void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000501 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000502 if (!view_adaptation_) {
503 return;
504 }
505 // Set output for initial aspect ratio in mediachannel unittests.
506 int old_num_pixels = GetOutputNumPixels();
507 SetOutputFormat(format);
508 SetOutputNumPixels(old_num_pixels);
509 view_desired_num_pixels_ = format.width * format.height;
510 view_desired_interval_ = format.interval;
511 int new_width, new_height;
512 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
513 LOG(LS_INFO) << "VAdapt View Request: "
514 << format.width << "x" << format.height
515 << " Pixels: " << view_desired_num_pixels_
516 << " Changed: " << (changed ? "true" : "false")
517 << " To: " << new_width << "x" << new_height;
518}
519
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000520void CoordinatedVideoAdapter::set_cpu_load_min_samples(
521 int cpu_load_min_samples) {
522 if (cpu_load_min_samples_ != cpu_load_min_samples) {
523 LOG(LS_INFO) << "VAdapt Change Cpu Adapt Min Samples from: "
524 << cpu_load_min_samples_ << " to "
525 << cpu_load_min_samples;
526 cpu_load_min_samples_ = cpu_load_min_samples;
527 }
528}
529
530void CoordinatedVideoAdapter::set_high_system_threshold(
531 float high_system_threshold) {
532 ASSERT(high_system_threshold <= 1.0f);
533 ASSERT(high_system_threshold >= 0.0f);
534 if (high_system_threshold_ != high_system_threshold) {
535 LOG(LS_INFO) << "VAdapt Change High System Threshold from: "
536 << high_system_threshold_ << " to " << high_system_threshold;
537 high_system_threshold_ = high_system_threshold;
538 }
539}
540
541void CoordinatedVideoAdapter::set_low_system_threshold(
542 float low_system_threshold) {
543 ASSERT(low_system_threshold <= 1.0f);
544 ASSERT(low_system_threshold >= 0.0f);
545 if (low_system_threshold_ != low_system_threshold) {
546 LOG(LS_INFO) << "VAdapt Change Low System Threshold from: "
547 << low_system_threshold_ << " to " << low_system_threshold;
548 low_system_threshold_ = low_system_threshold;
549 }
550}
551
552void CoordinatedVideoAdapter::set_process_threshold(float process_threshold) {
553 ASSERT(process_threshold <= 1.0f);
554 ASSERT(process_threshold >= 0.0f);
555 if (process_threshold_ != process_threshold) {
556 LOG(LS_INFO) << "VAdapt Change High Process Threshold from: "
557 << process_threshold_ << " to " << process_threshold;
558 process_threshold_ = process_threshold;
559 }
560}
561
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000562// A Bandwidth GD request for new resolution
563void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
564 int width, int height, AdaptRequest request) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000565 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000566 if (!gd_adaptation_) {
567 return;
568 }
569 int old_encoder_desired_num_pixels = encoder_desired_num_pixels_;
570 if (KEEP != request) {
571 int new_encoder_desired_num_pixels = width * height;
572 int old_num_pixels = GetOutputNumPixels();
573 if (new_encoder_desired_num_pixels != old_num_pixels) {
574 LOG(LS_VERBOSE) << "VAdapt GD resolution stale. Ignored";
575 } else {
576 // Update the encoder desired format based on the request.
577 encoder_desired_num_pixels_ = new_encoder_desired_num_pixels;
578 StepPixelCount(request, &encoder_desired_num_pixels_);
579 }
580 }
581 int new_width, new_height;
582 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
583
584 // Ignore up or keep if no change.
585 if (DOWNGRADE != request && view_switch_ && !changed) {
586 encoder_desired_num_pixels_ = old_encoder_desired_num_pixels;
587 LOG(LS_VERBOSE) << "VAdapt ignoring GD request.";
588 }
589
590 LOG(LS_INFO) << "VAdapt GD Request: "
591 << (DOWNGRADE == request ? "down" :
592 (UPGRADE == request ? "up" : "keep"))
593 << " From: " << width << "x" << height
594 << " Pixels: " << encoder_desired_num_pixels_
595 << " Changed: " << (changed ? "true" : "false")
596 << " To: " << new_width << "x" << new_height;
597}
598
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000599// A Bandwidth GD request for new resolution
600void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000601 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000602 if (!cpu_adaptation_) {
603 return;
604 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605 // Update how many times we have downgraded due to the cpu load.
606 switch (request) {
607 case DOWNGRADE:
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000608 // Ignore downgrades if we have downgraded the maximum times.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000609 if (cpu_downgrade_count_ < kMaxCpuDowngrades) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000610 ++cpu_downgrade_count_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000611 } else {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000612 LOG(LS_VERBOSE) << "VAdapt CPU load high but do not downgrade "
613 "because maximum downgrades reached";
614 SignalCpuAdaptationUnable();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000615 }
616 break;
617 case UPGRADE:
618 if (cpu_downgrade_count_ > 0) {
619 bool is_min = IsMinimumFormat(cpu_desired_num_pixels_);
620 if (is_min) {
621 --cpu_downgrade_count_;
622 } else {
623 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
624 "because cpu is not limiting resolution";
625 }
626 } else {
627 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
628 "because minimum downgrades reached";
629 }
630 break;
631 case KEEP:
632 default:
633 break;
634 }
635 if (KEEP != request) {
636 // TODO(fbarchard): compute stepping up/down from OutputNumPixels but
637 // clamp to inputpixels / 4 (2 steps)
638 cpu_desired_num_pixels_ = cpu_downgrade_count_ == 0 ? INT_MAX :
639 static_cast<int>(input_format().width * input_format().height >>
640 cpu_downgrade_count_);
641 }
642 int new_width, new_height;
643 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
644 LOG(LS_INFO) << "VAdapt CPU Request: "
645 << (DOWNGRADE == request ? "down" :
646 (UPGRADE == request ? "up" : "keep"))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000647 << " Steps: " << cpu_downgrade_count_
648 << " Changed: " << (changed ? "true" : "false")
649 << " To: " << new_width << "x" << new_height;
650}
651
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000652// A CPU request for new resolution
653// TODO(fbarchard): Move outside adapter.
654void CoordinatedVideoAdapter::OnCpuLoadUpdated(
655 int current_cpus, int max_cpus, float process_load, float system_load) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000656 rtc::CritScope cs(&request_critical_section_);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000657 if (!cpu_adaptation_) {
658 return;
659 }
660 // Update the moving average of system load. Even if we aren't smoothing,
661 // we'll still calculate this information, in case smoothing is later enabled.
662 system_load_average_ = kCpuLoadWeightCoefficient * system_load +
663 (1.0f - kCpuLoadWeightCoefficient) * system_load_average_;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000664 ++cpu_load_num_samples_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000665 if (cpu_smoothing_) {
666 system_load = system_load_average_;
667 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000668 AdaptRequest request = FindCpuRequest(current_cpus, max_cpus,
669 process_load, system_load);
670 // Make sure we're not adapting too quickly.
671 if (request != KEEP) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000672 if (cpu_load_num_samples_ < cpu_load_min_samples_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000673 LOG(LS_VERBOSE) << "VAdapt CPU load high/low but do not adapt until "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000674 << (cpu_load_min_samples_ - cpu_load_num_samples_)
675 << " more samples";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000676 request = KEEP;
677 }
678 }
679
680 OnCpuResolutionRequest(request);
681}
682
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000683// Called by cpu adapter on up requests.
684bool CoordinatedVideoAdapter::IsMinimumFormat(int pixels) {
685 // Find closest scale factor that matches input resolution to min_num_pixels
686 // and set that for output resolution. This is not needed for VideoAdapter,
687 // but provides feedback to unittests and users on expected resolution.
688 // Actual resolution is based on input frame.
689 VideoFormat new_output = output_format();
690 VideoFormat input = input_format();
691 if (input_format().IsSize0x0()) {
692 input = new_output;
693 }
694 float scale = 1.0f;
695 if (!input.IsSize0x0()) {
696 scale = FindClosestScale(input.width,
697 input.height,
698 pixels);
699 }
700 new_output.width = static_cast<int>(input.width * scale + .5f);
701 new_output.height = static_cast<int>(input.height * scale + .5f);
702 int new_pixels = new_output.width * new_output.height;
703 int num_pixels = GetOutputNumPixels();
704 return new_pixels <= num_pixels;
705}
706
707// Called by all coordinators when there is a change.
708bool CoordinatedVideoAdapter::AdaptToMinimumFormat(int* new_width,
709 int* new_height) {
710 VideoFormat new_output = output_format();
711 VideoFormat input = input_format();
712 if (input_format().IsSize0x0()) {
713 input = new_output;
714 }
715 int old_num_pixels = GetOutputNumPixels();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000716 int min_num_pixels = INT_MAX;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000717 adapt_reason_ = ADAPTREASON_NONE;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000718
719 // Reduce resolution based on encoder bandwidth (GD).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000720 if (encoder_desired_num_pixels_ &&
721 (encoder_desired_num_pixels_ < min_num_pixels)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000722 adapt_reason_ |= ADAPTREASON_BANDWIDTH;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 min_num_pixels = encoder_desired_num_pixels_;
724 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000725 // Reduce resolution based on CPU.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726 if (cpu_adaptation_ && cpu_desired_num_pixels_ &&
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000727 (cpu_desired_num_pixels_ <= min_num_pixels)) {
728 if (cpu_desired_num_pixels_ < min_num_pixels) {
729 adapt_reason_ = ADAPTREASON_CPU;
730 } else {
731 adapt_reason_ |= ADAPTREASON_CPU;
732 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 min_num_pixels = cpu_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000734 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000735 // Round resolution for GD or CPU to allow 1/2 to map to 9/16.
736 if (!input.IsSize0x0() && min_num_pixels != INT_MAX) {
737 float scale = FindClosestScale(input.width, input.height, min_num_pixels);
738 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
739 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000741 // Reduce resolution based on View Request.
742 if (view_desired_num_pixels_ <= min_num_pixels) {
743 if (view_desired_num_pixels_ < min_num_pixels) {
744 adapt_reason_ = ADAPTREASON_VIEW;
745 } else {
746 adapt_reason_ |= ADAPTREASON_VIEW;
747 }
748 min_num_pixels = view_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000750 // Snap to a scale factor.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000751 float scale = 1.0f;
752 if (!input.IsSize0x0()) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000753 scale = FindLowerScale(input.width, input.height, min_num_pixels);
754 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
755 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756 }
757 if (scale == 1.0f) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000758 adapt_reason_ = ADAPTREASON_NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000759 }
760 *new_width = new_output.width = static_cast<int>(input.width * scale + .5f);
761 *new_height = new_output.height = static_cast<int>(input.height * scale +
762 .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000763 SetOutputNumPixels(min_num_pixels);
764
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765 new_output.interval = view_desired_interval_;
766 SetOutputFormat(new_output);
767 int new_num_pixels = GetOutputNumPixels();
768 bool changed = new_num_pixels != old_num_pixels;
769
770 static const char* kReasons[8] = {
771 "None",
772 "CPU",
773 "BANDWIDTH",
774 "CPU+BANDWIDTH",
775 "VIEW",
776 "CPU+VIEW",
777 "BANDWIDTH+VIEW",
778 "CPU+BANDWIDTH+VIEW",
779 };
780
781 LOG(LS_VERBOSE) << "VAdapt Status View: " << view_desired_num_pixels_
782 << " GD: " << encoder_desired_num_pixels_
783 << " CPU: " << cpu_desired_num_pixels_
784 << " Pixels: " << min_num_pixels
785 << " Input: " << input.width
786 << "x" << input.height
787 << " Scale: " << scale
788 << " Resolution: " << new_output.width
789 << "x" << new_output.height
790 << " Changed: " << (changed ? "true" : "false")
791 << " Reason: " << kReasons[adapt_reason_];
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000792
793 if (changed) {
794 // When any adaptation occurs, historic CPU load levels are no longer
795 // accurate. Clear out our state so we can re-learn at the new normal.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000796 cpu_load_num_samples_ = 0;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000797 system_load_average_ = kCpuLoadInitialAverage;
798 }
799
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000800 return changed;
801}
802
803} // namespace cricket