blob: d36ad6aa711581b4d63968015df1f6dc63d0d7b4 [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.orgbbd8cad2014-11-14 12:10:46 +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.orgbbd8cad2014-11-14 12:10:46 +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),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172 black_output_(false),
173 is_black_(false),
174 interval_next_frame_(0) {
175}
176
177VideoAdapter::~VideoAdapter() {
178}
179
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180void VideoAdapter::SetInputFormat(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000181 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000182 int64 old_input_interval = input_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000183 input_format_ = format;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000184 output_format_.interval = rtc::_max(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000185 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000186 if (old_input_interval != input_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000187 LOG(LS_INFO) << "VAdapt input interval changed from "
188 << old_input_interval << " to " << input_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000189 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000190}
191
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000192void CoordinatedVideoAdapter::SetInputFormat(const VideoFormat& format) {
193 int previous_width = input_format().width;
194 int previous_height = input_format().height;
195 bool is_resolution_change = previous_width > 0 && format.width > 0 &&
196 (previous_width != format.width ||
197 previous_height != format.height);
198 VideoAdapter::SetInputFormat(format);
199 if (is_resolution_change) {
200 int width, height;
201 // Trigger the adaptation logic again, to potentially reset the adaptation
202 // state for things like view requests that may not longer be capping
203 // output (or may now cap output).
204 AdaptToMinimumFormat(&width, &height);
205 LOG(LS_INFO) << "VAdapt Input Resolution Change: "
206 << "Previous input resolution: "
207 << previous_width << "x" << previous_height
208 << " New input resolution: "
209 << format.width << "x" << format.height
210 << " New output resolution: "
211 << width << "x" << height;
212 }
213}
214
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000215void CoordinatedVideoAdapter::set_cpu_smoothing(bool enable) {
216 LOG(LS_INFO) << "CPU smoothing is now "
217 << (enable ? "enabled" : "disabled");
218 cpu_smoothing_ = enable;
219}
220
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000221void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000222 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000223 int64 old_output_interval = output_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224 output_format_ = format;
225 output_num_pixels_ = output_format_.width * output_format_.height;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000226 output_format_.interval = rtc::_max(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000227 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000228 if (old_output_interval != output_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000229 LOG(LS_INFO) << "VAdapt output interval changed from "
230 << old_output_interval << " to " << output_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000231 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000232}
233
234const VideoFormat& VideoAdapter::input_format() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000235 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000236 return input_format_;
237}
238
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000239bool VideoAdapter::drops_all_frames() const {
240 return output_num_pixels_ == 0;
241}
242
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243const VideoFormat& VideoAdapter::output_format() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000244 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000245 return output_format_;
246}
247
248void VideoAdapter::SetBlackOutput(bool black) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000249 rtc::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000250 black_output_ = black;
251}
252
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000253bool VideoAdapter::IsBlackOutput() {
254 rtc::CritScope cs(&critical_section_);
255 return black_output_;
256}
257
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258// Constrain output resolution to this many pixels overall
259void VideoAdapter::SetOutputNumPixels(int num_pixels) {
260 output_num_pixels_ = num_pixels;
261}
262
263int VideoAdapter::GetOutputNumPixels() const {
264 return output_num_pixels_;
265}
266
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000267VideoFormat VideoAdapter::AdaptFrameResolution(int in_width, int in_height) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000268 rtc::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000269 ++frames_in_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000271 SetInputFormat(VideoFormat(
272 in_width, in_height, input_format_.interval, input_format_.fourcc));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000273
274 // Drop the input frame if necessary.
275 bool should_drop = false;
276 if (!output_num_pixels_) {
277 // Drop all frames as the output format is 0x0.
278 should_drop = true;
279 } else {
280 // Drop some frames based on input fps and output fps.
281 // Normally output fps is less than input fps.
282 // TODO(fbarchard): Consider adjusting interval to reflect the adjusted
283 // interval between frames after dropping some frames.
284 interval_next_frame_ += input_format_.interval;
285 if (output_format_.interval > 0) {
286 if (interval_next_frame_ >= output_format_.interval) {
287 interval_next_frame_ %= output_format_.interval;
288 } else {
289 should_drop = true;
290 }
291 }
292 }
293 if (should_drop) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000294 // Show VAdapt log every 90 frames dropped. (3 seconds)
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000295 if ((frames_in_ - frames_out_) % 90 == 0) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000296 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
297 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000298 LOG(LS_INFO) << "VAdapt Drop Frame: scaled " << frames_scaled_
299 << " / out " << frames_out_
300 << " / in " << frames_in_
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000301 << " Changes: " << adaption_changes_
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000302 << " Input: " << in_width
303 << "x" << in_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000304 << " i" << input_format_.interval
305 << " Output: i" << output_format_.interval;
306 }
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000307
308 return VideoFormat(); // Drop frame.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000309 }
310
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000311 const float scale = VideoAdapter::FindClosestViewScale(
312 in_width, in_height, output_num_pixels_);
313 const int output_width = static_cast<int>(in_width * scale + .5f);
314 const int output_height = static_cast<int>(in_height * scale + .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000315
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000316 ++frames_out_;
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000317 if (scale != 1)
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000318 ++frames_scaled_;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000319 // Show VAdapt log every 90 frames output. (3 seconds)
320 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
321 // for LS_VERBOSE and more for LS_INFO.
322 bool show = (frames_out_) % 90 == 0;
323
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000324 // TODO(fbarchard): LOG the previous output resolution and track input
325 // resolution changes as well. Consider dropping the statistics into their
326 // own class which could be queried publically.
327 bool changed = false;
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000328 if (output_format_.width && (output_format_.width != output_width ||
329 output_format_.height != output_height)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000330 show = true;
331 ++adaption_changes_;
332 changed = true;
333 }
334 if (show) {
335 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
336 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000337 LOG(LS_INFO) << "VAdapt Frame: scaled " << frames_scaled_
338 << " / out " << frames_out_
339 << " / in " << frames_in_
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000340 << " Changes: " << adaption_changes_
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000341 << " Input: " << in_width
342 << "x" << in_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000343 << " i" << input_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000344 << " Scale: " << scale
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000345 << " Output: " << output_width
346 << "x" << output_height
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000347 << " i" << output_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000348 << " Changed: " << (changed ? "true" : "false");
349 }
magjed@webrtc.orgbbd8cad2014-11-14 12:10:46 +0000350
351 output_format_.width = output_width;
352 output_format_.height = output_height;
353
354 return output_format_;
355}
356
357// TODO(fbarchard): Add AdaptFrameRate function that only drops frames but
358// not resolution.
359bool VideoAdapter::AdaptFrame(VideoFrame* in_frame, VideoFrame** out_frame) {
360 if (!in_frame || !out_frame)
361 return false;
362
363 const VideoFormat adapted_format =
364 AdaptFrameResolution(static_cast<int>(in_frame->GetWidth()),
365 static_cast<int>(in_frame->GetHeight()));
366
367 rtc::CritScope cs(&critical_section_);
368 if (adapted_format.IsSize0x0()) {
369 *out_frame = NULL;
370 return true;
371 }
372
373 if (!black_output_ &&
374 in_frame->GetWidth() == static_cast<size_t>(adapted_format.width) &&
375 in_frame->GetHeight() == static_cast<size_t>(adapted_format.height)) {
376 // The dimensions are correct and we aren't muting, so use the input frame.
377 *out_frame = in_frame;
378 } else {
379 if (!StretchToOutputFrame(in_frame)) {
380 LOG(LS_VERBOSE) << "VAdapt Stretch Failed.";
381 return false;
382 }
383
384 *out_frame = output_frame_.get();
385 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000386
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000387 return true;
388}
389
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000390void VideoAdapter::set_scale_third(bool enable) {
391 LOG(LS_INFO) << "Video Adapter third scaling is now "
392 << (enable ? "enabled" : "disabled");
393 scale_third_ = enable;
394}
395
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000396// Scale or Blacken the frame. Returns true if successful.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000397bool VideoAdapter::StretchToOutputFrame(const VideoFrame* in_frame) {
398 int output_width = output_format_.width;
399 int output_height = output_format_.height;
400
401 // Create and stretch the output frame if it has not been created yet or its
402 // size is not same as the expected.
403 bool stretched = false;
404 if (!output_frame_ ||
405 output_frame_->GetWidth() != static_cast<size_t>(output_width) ||
406 output_frame_->GetHeight() != static_cast<size_t>(output_height)) {
407 output_frame_.reset(
408 in_frame->Stretch(output_width, output_height, true, true));
409 if (!output_frame_) {
410 LOG(LS_WARNING) << "Adapter failed to stretch frame to "
411 << output_width << "x" << output_height;
412 return false;
413 }
414 stretched = true;
415 is_black_ = false;
416 }
417
418 if (!black_output_) {
419 if (!stretched) {
420 // The output frame does not need to be blacken and has not been stretched
421 // from the input frame yet, stretch the input frame. This is the most
422 // common case.
423 in_frame->StretchToFrame(output_frame_.get(), true, true);
424 }
425 is_black_ = false;
426 } else {
427 if (!is_black_) {
428 output_frame_->SetToBlack();
429 is_black_ = true;
430 }
431 output_frame_->SetElapsedTime(in_frame->GetElapsedTime());
432 output_frame_->SetTimeStamp(in_frame->GetTimeStamp());
433 }
434
435 return true;
436}
437
438///////////////////////////////////////////////////////////////////////
439// Implementation of CoordinatedVideoAdapter
440CoordinatedVideoAdapter::CoordinatedVideoAdapter()
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000441 : cpu_adaptation_(true),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000442 cpu_smoothing_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000443 gd_adaptation_(true),
444 view_adaptation_(true),
445 view_switch_(false),
446 cpu_downgrade_count_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000447 cpu_load_min_samples_(kCpuLoadMinSamples),
448 cpu_load_num_samples_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000449 high_system_threshold_(kHighSystemCpuThreshold),
450 low_system_threshold_(kLowSystemCpuThreshold),
451 process_threshold_(kProcessCpuThreshold),
452 view_desired_num_pixels_(INT_MAX),
453 view_desired_interval_(0),
454 encoder_desired_num_pixels_(INT_MAX),
455 cpu_desired_num_pixels_(INT_MAX),
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000456 adapt_reason_(ADAPTREASON_NONE),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000457 system_load_average_(kCpuLoadInitialAverage) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000458}
459
460// Helper function to UPGRADE or DOWNGRADE a number of pixels
461void CoordinatedVideoAdapter::StepPixelCount(
462 CoordinatedVideoAdapter::AdaptRequest request,
463 int* num_pixels) {
464 switch (request) {
465 case CoordinatedVideoAdapter::DOWNGRADE:
466 *num_pixels /= 2;
467 break;
468
469 case CoordinatedVideoAdapter::UPGRADE:
470 *num_pixels *= 2;
471 break;
472
473 default: // No change in pixel count
474 break;
475 }
476 return;
477}
478
479// Find the adaptation request of the cpu based on the load. Return UPGRADE if
480// the load is low, DOWNGRADE if the load is high, and KEEP otherwise.
481CoordinatedVideoAdapter::AdaptRequest CoordinatedVideoAdapter::FindCpuRequest(
482 int current_cpus, int max_cpus,
483 float process_load, float system_load) {
484 // Downgrade if system is high and plugin is at least more than midrange.
485 if (system_load >= high_system_threshold_ * max_cpus &&
486 process_load >= process_threshold_ * current_cpus) {
487 return CoordinatedVideoAdapter::DOWNGRADE;
488 // Upgrade if system is low.
489 } else if (system_load < low_system_threshold_ * max_cpus) {
490 return CoordinatedVideoAdapter::UPGRADE;
491 }
492 return CoordinatedVideoAdapter::KEEP;
493}
494
495// A remote view request for a new resolution.
496void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000497 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000498 if (!view_adaptation_) {
499 return;
500 }
501 // Set output for initial aspect ratio in mediachannel unittests.
502 int old_num_pixels = GetOutputNumPixels();
503 SetOutputFormat(format);
504 SetOutputNumPixels(old_num_pixels);
505 view_desired_num_pixels_ = format.width * format.height;
506 view_desired_interval_ = format.interval;
507 int new_width, new_height;
508 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
509 LOG(LS_INFO) << "VAdapt View Request: "
510 << format.width << "x" << format.height
511 << " Pixels: " << view_desired_num_pixels_
512 << " Changed: " << (changed ? "true" : "false")
513 << " To: " << new_width << "x" << new_height;
514}
515
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000516void CoordinatedVideoAdapter::set_cpu_load_min_samples(
517 int cpu_load_min_samples) {
518 if (cpu_load_min_samples_ != cpu_load_min_samples) {
519 LOG(LS_INFO) << "VAdapt Change Cpu Adapt Min Samples from: "
520 << cpu_load_min_samples_ << " to "
521 << cpu_load_min_samples;
522 cpu_load_min_samples_ = cpu_load_min_samples;
523 }
524}
525
526void CoordinatedVideoAdapter::set_high_system_threshold(
527 float high_system_threshold) {
528 ASSERT(high_system_threshold <= 1.0f);
529 ASSERT(high_system_threshold >= 0.0f);
530 if (high_system_threshold_ != high_system_threshold) {
531 LOG(LS_INFO) << "VAdapt Change High System Threshold from: "
532 << high_system_threshold_ << " to " << high_system_threshold;
533 high_system_threshold_ = high_system_threshold;
534 }
535}
536
537void CoordinatedVideoAdapter::set_low_system_threshold(
538 float low_system_threshold) {
539 ASSERT(low_system_threshold <= 1.0f);
540 ASSERT(low_system_threshold >= 0.0f);
541 if (low_system_threshold_ != low_system_threshold) {
542 LOG(LS_INFO) << "VAdapt Change Low System Threshold from: "
543 << low_system_threshold_ << " to " << low_system_threshold;
544 low_system_threshold_ = low_system_threshold;
545 }
546}
547
548void CoordinatedVideoAdapter::set_process_threshold(float process_threshold) {
549 ASSERT(process_threshold <= 1.0f);
550 ASSERT(process_threshold >= 0.0f);
551 if (process_threshold_ != process_threshold) {
552 LOG(LS_INFO) << "VAdapt Change High Process Threshold from: "
553 << process_threshold_ << " to " << process_threshold;
554 process_threshold_ = process_threshold;
555 }
556}
557
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000558// A Bandwidth GD request for new resolution
559void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
560 int width, int height, AdaptRequest request) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000561 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000562 if (!gd_adaptation_) {
563 return;
564 }
565 int old_encoder_desired_num_pixels = encoder_desired_num_pixels_;
566 if (KEEP != request) {
567 int new_encoder_desired_num_pixels = width * height;
568 int old_num_pixels = GetOutputNumPixels();
569 if (new_encoder_desired_num_pixels != old_num_pixels) {
570 LOG(LS_VERBOSE) << "VAdapt GD resolution stale. Ignored";
571 } else {
572 // Update the encoder desired format based on the request.
573 encoder_desired_num_pixels_ = new_encoder_desired_num_pixels;
574 StepPixelCount(request, &encoder_desired_num_pixels_);
575 }
576 }
577 int new_width, new_height;
578 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
579
580 // Ignore up or keep if no change.
581 if (DOWNGRADE != request && view_switch_ && !changed) {
582 encoder_desired_num_pixels_ = old_encoder_desired_num_pixels;
583 LOG(LS_VERBOSE) << "VAdapt ignoring GD request.";
584 }
585
586 LOG(LS_INFO) << "VAdapt GD Request: "
587 << (DOWNGRADE == request ? "down" :
588 (UPGRADE == request ? "up" : "keep"))
589 << " From: " << width << "x" << height
590 << " Pixels: " << encoder_desired_num_pixels_
591 << " Changed: " << (changed ? "true" : "false")
592 << " To: " << new_width << "x" << new_height;
593}
594
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000595// A Bandwidth GD request for new resolution
596void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000597 rtc::CritScope cs(&request_critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598 if (!cpu_adaptation_) {
599 return;
600 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000601 // Update how many times we have downgraded due to the cpu load.
602 switch (request) {
603 case DOWNGRADE:
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000604 // Ignore downgrades if we have downgraded the maximum times.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605 if (cpu_downgrade_count_ < kMaxCpuDowngrades) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000606 ++cpu_downgrade_count_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000607 } else {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000608 LOG(LS_VERBOSE) << "VAdapt CPU load high but do not downgrade "
609 "because maximum downgrades reached";
610 SignalCpuAdaptationUnable();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000611 }
612 break;
613 case UPGRADE:
614 if (cpu_downgrade_count_ > 0) {
615 bool is_min = IsMinimumFormat(cpu_desired_num_pixels_);
616 if (is_min) {
617 --cpu_downgrade_count_;
618 } else {
619 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
620 "because cpu is not limiting resolution";
621 }
622 } else {
623 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
624 "because minimum downgrades reached";
625 }
626 break;
627 case KEEP:
628 default:
629 break;
630 }
631 if (KEEP != request) {
632 // TODO(fbarchard): compute stepping up/down from OutputNumPixels but
633 // clamp to inputpixels / 4 (2 steps)
634 cpu_desired_num_pixels_ = cpu_downgrade_count_ == 0 ? INT_MAX :
635 static_cast<int>(input_format().width * input_format().height >>
636 cpu_downgrade_count_);
637 }
638 int new_width, new_height;
639 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
640 LOG(LS_INFO) << "VAdapt CPU Request: "
641 << (DOWNGRADE == request ? "down" :
642 (UPGRADE == request ? "up" : "keep"))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000643 << " Steps: " << cpu_downgrade_count_
644 << " Changed: " << (changed ? "true" : "false")
645 << " To: " << new_width << "x" << new_height;
646}
647
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000648// A CPU request for new resolution
649// TODO(fbarchard): Move outside adapter.
650void CoordinatedVideoAdapter::OnCpuLoadUpdated(
651 int current_cpus, int max_cpus, float process_load, float system_load) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000652 rtc::CritScope cs(&request_critical_section_);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000653 if (!cpu_adaptation_) {
654 return;
655 }
656 // Update the moving average of system load. Even if we aren't smoothing,
657 // we'll still calculate this information, in case smoothing is later enabled.
658 system_load_average_ = kCpuLoadWeightCoefficient * system_load +
659 (1.0f - kCpuLoadWeightCoefficient) * system_load_average_;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000660 ++cpu_load_num_samples_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000661 if (cpu_smoothing_) {
662 system_load = system_load_average_;
663 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000664 AdaptRequest request = FindCpuRequest(current_cpus, max_cpus,
665 process_load, system_load);
666 // Make sure we're not adapting too quickly.
667 if (request != KEEP) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000668 if (cpu_load_num_samples_ < cpu_load_min_samples_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000669 LOG(LS_VERBOSE) << "VAdapt CPU load high/low but do not adapt until "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000670 << (cpu_load_min_samples_ - cpu_load_num_samples_)
671 << " more samples";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000672 request = KEEP;
673 }
674 }
675
676 OnCpuResolutionRequest(request);
677}
678
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000679// Called by cpu adapter on up requests.
680bool CoordinatedVideoAdapter::IsMinimumFormat(int pixels) {
681 // Find closest scale factor that matches input resolution to min_num_pixels
682 // and set that for output resolution. This is not needed for VideoAdapter,
683 // but provides feedback to unittests and users on expected resolution.
684 // Actual resolution is based on input frame.
685 VideoFormat new_output = output_format();
686 VideoFormat input = input_format();
687 if (input_format().IsSize0x0()) {
688 input = new_output;
689 }
690 float scale = 1.0f;
691 if (!input.IsSize0x0()) {
692 scale = FindClosestScale(input.width,
693 input.height,
694 pixels);
695 }
696 new_output.width = static_cast<int>(input.width * scale + .5f);
697 new_output.height = static_cast<int>(input.height * scale + .5f);
698 int new_pixels = new_output.width * new_output.height;
699 int num_pixels = GetOutputNumPixels();
700 return new_pixels <= num_pixels;
701}
702
703// Called by all coordinators when there is a change.
704bool CoordinatedVideoAdapter::AdaptToMinimumFormat(int* new_width,
705 int* new_height) {
706 VideoFormat new_output = output_format();
707 VideoFormat input = input_format();
708 if (input_format().IsSize0x0()) {
709 input = new_output;
710 }
711 int old_num_pixels = GetOutputNumPixels();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000712 int min_num_pixels = INT_MAX;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000713 adapt_reason_ = ADAPTREASON_NONE;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000714
715 // Reduce resolution based on encoder bandwidth (GD).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716 if (encoder_desired_num_pixels_ &&
717 (encoder_desired_num_pixels_ < min_num_pixels)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000718 adapt_reason_ |= ADAPTREASON_BANDWIDTH;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000719 min_num_pixels = encoder_desired_num_pixels_;
720 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000721 // Reduce resolution based on CPU.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 if (cpu_adaptation_ && cpu_desired_num_pixels_ &&
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000723 (cpu_desired_num_pixels_ <= min_num_pixels)) {
724 if (cpu_desired_num_pixels_ < min_num_pixels) {
725 adapt_reason_ = ADAPTREASON_CPU;
726 } else {
727 adapt_reason_ |= ADAPTREASON_CPU;
728 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729 min_num_pixels = cpu_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000731 // Round resolution for GD or CPU to allow 1/2 to map to 9/16.
732 if (!input.IsSize0x0() && min_num_pixels != INT_MAX) {
733 float scale = FindClosestScale(input.width, input.height, min_num_pixels);
734 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
735 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000737 // Reduce resolution based on View Request.
738 if (view_desired_num_pixels_ <= min_num_pixels) {
739 if (view_desired_num_pixels_ < min_num_pixels) {
740 adapt_reason_ = ADAPTREASON_VIEW;
741 } else {
742 adapt_reason_ |= ADAPTREASON_VIEW;
743 }
744 min_num_pixels = view_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000746 // Snap to a scale factor.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747 float scale = 1.0f;
748 if (!input.IsSize0x0()) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000749 scale = FindLowerScale(input.width, input.height, min_num_pixels);
750 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
751 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752 }
753 if (scale == 1.0f) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000754 adapt_reason_ = ADAPTREASON_NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000755 }
756 *new_width = new_output.width = static_cast<int>(input.width * scale + .5f);
757 *new_height = new_output.height = static_cast<int>(input.height * scale +
758 .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000759 SetOutputNumPixels(min_num_pixels);
760
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000761 new_output.interval = view_desired_interval_;
762 SetOutputFormat(new_output);
763 int new_num_pixels = GetOutputNumPixels();
764 bool changed = new_num_pixels != old_num_pixels;
765
766 static const char* kReasons[8] = {
767 "None",
768 "CPU",
769 "BANDWIDTH",
770 "CPU+BANDWIDTH",
771 "VIEW",
772 "CPU+VIEW",
773 "BANDWIDTH+VIEW",
774 "CPU+BANDWIDTH+VIEW",
775 };
776
777 LOG(LS_VERBOSE) << "VAdapt Status View: " << view_desired_num_pixels_
778 << " GD: " << encoder_desired_num_pixels_
779 << " CPU: " << cpu_desired_num_pixels_
780 << " Pixels: " << min_num_pixels
781 << " Input: " << input.width
782 << "x" << input.height
783 << " Scale: " << scale
784 << " Resolution: " << new_output.width
785 << "x" << new_output.height
786 << " Changed: " << (changed ? "true" : "false")
787 << " Reason: " << kReasons[adapt_reason_];
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000788
789 if (changed) {
790 // When any adaptation occurs, historic CPU load levels are no longer
791 // accurate. Clear out our state so we can re-learn at the new normal.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000792 cpu_load_num_samples_ = 0;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000793 system_load_average_ = kCpuLoadInitialAverage;
794 }
795
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796 return changed;
797}
798
799} // namespace cricket