blob: f1979951cd5d9c1c59af5fdcfea907f8d7a40968 [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.org28e20752013-07-10 00:45:36 +000030#include "talk/base/logging.h"
31#include "talk/base/timeutils.h"
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000032#include "talk/media/base/constants.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000033#include "talk/media/base/videoframe.h"
34
35namespace cricket {
36
37// TODO(fbarchard): Make downgrades settable
38static const int kMaxCpuDowngrades = 2; // Downgrade at most 2 times for CPU.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +000039// The number of cpu samples to require before adapting. This value depends on
40// the cpu monitor sampling frequency being 2000ms.
41static const int kCpuLoadMinSamples = 3;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000042// The amount of weight to give to each new cpu load sample. The lower the
43// value, the slower we'll adapt to changing cpu conditions.
44static const float kCpuLoadWeightCoefficient = 0.4f;
45// The seed value for the cpu load moving average.
46static const float kCpuLoadInitialAverage = 0.5f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047
henrike@webrtc.org28e20752013-07-10 00:45:36 +000048// Desktop needs 1/8 scale for HD (1280 x 720) to QQVGA (160 x 90)
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000049static const float kScaleFactors[] = {
50 1.f / 1.f, // Full size.
51 3.f / 4.f, // 3/4 scale.
52 1.f / 2.f, // 1/2 scale.
53 3.f / 8.f, // 3/8 scale.
54 1.f / 4.f, // 1/4 scale.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055 3.f / 16.f, // 3/16 scale.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000056 1.f / 8.f, // 1/8 scale.
57 0.f // End of table.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000060// TODO(fbarchard): Use this table (optionally) for CPU and GD as well.
61static const float kViewScaleFactors[] = {
62 1.f / 1.f, // Full size.
63 3.f / 4.f, // 3/4 scale.
64 2.f / 3.f, // 2/3 scale. // Allow 1080p to 720p.
65 1.f / 2.f, // 1/2 scale.
66 3.f / 8.f, // 3/8 scale.
67 1.f / 3.f, // 1/3 scale. // Allow 1080p to 360p.
68 1.f / 4.f, // 1/4 scale.
69 3.f / 16.f, // 3/16 scale.
70 1.f / 8.f, // 1/8 scale.
71 0.f // End of table.
72};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000074const float* VideoAdapter::GetViewScaleFactors() const {
75 return scale_third_ ? kViewScaleFactors : kScaleFactors;
76}
77
78// For resolutions that would scale down a little instead of up a little,
79// bias toward scaling up a little. This will tend to choose 3/4 scale instead
80// of 2/3 scale, when the 2/3 is not an exact match.
81static const float kUpBias = -0.9f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082// Find the scale factor that, when applied to width and height, is closest
83// to num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000084float VideoAdapter::FindScale(const float* scale_factors,
85 const float upbias,
86 int width, int height,
87 int target_num_pixels) {
88 const float kMinNumPixels = 160 * 90;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089 if (!target_num_pixels) {
90 return 0.f;
91 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000092 float best_distance = static_cast<float>(INT_MAX);
93 float best_scale = 1.f; // Default to unscaled if nothing matches.
94 float pixels = static_cast<float>(width * height);
95 for (int i = 0; ; ++i) {
96 float scale = scale_factors[i];
97 float test_num_pixels = pixels * scale * scale;
98 // Do not consider scale factors that produce too small images.
99 // Scale factor of 0 at end of table will also exit here.
100 if (test_num_pixels < kMinNumPixels) {
101 break;
102 }
103 float diff = target_num_pixels - test_num_pixels;
104 // If resolution is higher than desired, bias the difference based on
105 // preference for slightly larger for nearest, or avoid completely if
106 // looking for lower resolutions only.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 if (diff < 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000108 diff = diff * kUpBias;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 }
110 if (diff < best_distance) {
111 best_distance = diff;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000112 best_scale = scale;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000113 if (best_distance == 0) { // Found exact match.
114 break;
115 }
116 }
117 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000118 return best_scale;
119}
120
121// Find the closest scale factor.
122float VideoAdapter::FindClosestScale(int width, int height,
123 int target_num_pixels) {
124 return FindScale(kScaleFactors, kUpBias,
125 width, height, target_num_pixels);
126}
127
128// Find the closest view scale factor.
129float VideoAdapter::FindClosestViewScale(int width, int height,
130 int target_num_pixels) {
131 return FindScale(GetViewScaleFactors(), kUpBias,
132 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133}
134
135// Finds the scale factor that, when applied to width and height, produces
136// fewer than num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000137static const float kUpAvoidBias = -1000000000.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000138float VideoAdapter::FindLowerScale(int width, int height,
139 int target_num_pixels) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000140 return FindScale(GetViewScaleFactors(), kUpAvoidBias,
141 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000142}
143
144// There are several frame sizes used by Adapter. This explains them
145// input_format - set once by server to frame size expected from the camera.
146// output_format - size that output would like to be. Includes framerate.
147// output_num_pixels - size that output should be constrained to. Used to
148// compute output_format from in_frame.
149// in_frame - actual camera captured frame size, which is typically the same
150// as input_format. This can also be rotated or cropped for aspect ratio.
151// out_frame - actual frame output by adapter. Should be a direct scale of
152// in_frame maintaining rotation and aspect ratio.
153// OnOutputFormatRequest - server requests you send this resolution based on
154// view requests.
155// OnEncoderResolutionRequest - encoder requests you send this resolution based
156// on bandwidth
157// OnCpuLoadUpdated - cpu monitor requests you send this resolution based on
158// cpu load.
159
160///////////////////////////////////////////////////////////////////////
161// Implementation of VideoAdapter
162VideoAdapter::VideoAdapter()
163 : output_num_pixels_(INT_MAX),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000164 scale_third_(false),
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000165 frames_in_(0),
166 frames_out_(0),
167 frames_scaled_(0),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000168 adaption_changes_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000169 previous_width_(0),
170 previous_height_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000171 black_output_(false),
172 is_black_(false),
173 interval_next_frame_(0) {
174}
175
176VideoAdapter::~VideoAdapter() {
177}
178
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000179void VideoAdapter::SetInputFormat(const VideoFormat& format) {
180 talk_base::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000181 int64 old_input_interval = input_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182 input_format_ = format;
183 output_format_.interval = talk_base::_max(
184 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000185 if (old_input_interval != input_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000186 LOG(LS_INFO) << "VAdapt input interval changed from "
187 << old_input_interval << " to " << input_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000188 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000189}
190
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000191void CoordinatedVideoAdapter::SetInputFormat(const VideoFormat& format) {
192 int previous_width = input_format().width;
193 int previous_height = input_format().height;
194 bool is_resolution_change = previous_width > 0 && format.width > 0 &&
195 (previous_width != format.width ||
196 previous_height != format.height);
197 VideoAdapter::SetInputFormat(format);
198 if (is_resolution_change) {
199 int width, height;
200 // Trigger the adaptation logic again, to potentially reset the adaptation
201 // state for things like view requests that may not longer be capping
202 // output (or may now cap output).
203 AdaptToMinimumFormat(&width, &height);
204 LOG(LS_INFO) << "VAdapt Input Resolution Change: "
205 << "Previous input resolution: "
206 << previous_width << "x" << previous_height
207 << " New input resolution: "
208 << format.width << "x" << format.height
209 << " New output resolution: "
210 << width << "x" << height;
211 }
212}
213
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000214void CoordinatedVideoAdapter::set_cpu_smoothing(bool enable) {
215 LOG(LS_INFO) << "CPU smoothing is now "
216 << (enable ? "enabled" : "disabled");
217 cpu_smoothing_ = enable;
218}
219
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000220void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
221 talk_base::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000222 int64 old_output_interval = output_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000223 output_format_ = format;
224 output_num_pixels_ = output_format_.width * output_format_.height;
225 output_format_.interval = talk_base::_max(
226 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000227 if (old_output_interval != output_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000228 LOG(LS_INFO) << "VAdapt output interval changed from "
229 << old_output_interval << " to " << output_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000230 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231}
232
233const VideoFormat& VideoAdapter::input_format() {
234 talk_base::CritScope cs(&critical_section_);
235 return input_format_;
236}
237
238const VideoFormat& VideoAdapter::output_format() {
239 talk_base::CritScope cs(&critical_section_);
240 return output_format_;
241}
242
243void VideoAdapter::SetBlackOutput(bool black) {
244 talk_base::CritScope cs(&critical_section_);
245 black_output_ = black;
246}
247
248// Constrain output resolution to this many pixels overall
249void VideoAdapter::SetOutputNumPixels(int num_pixels) {
250 output_num_pixels_ = num_pixels;
251}
252
253int VideoAdapter::GetOutputNumPixels() const {
254 return output_num_pixels_;
255}
256
257// TODO(fbarchard): Add AdaptFrameRate function that only drops frames but
258// not resolution.
259bool VideoAdapter::AdaptFrame(const VideoFrame* in_frame,
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000260 VideoFrame** out_frame) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000261 talk_base::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000262 if (!in_frame || !out_frame) {
263 return false;
264 }
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000265 ++frames_in_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266
267 // Update input to actual frame dimensions.
mallinath@webrtc.orgab5a0912013-09-07 00:12:57 +0000268 VideoFormat format(static_cast<int>(in_frame->GetWidth()),
269 static_cast<int>(in_frame->GetHeight()),
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000270 input_format_.interval, input_format_.fourcc);
271 SetInputFormat(format);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272
273 // Drop the input frame if necessary.
274 bool should_drop = false;
275 if (!output_num_pixels_) {
276 // Drop all frames as the output format is 0x0.
277 should_drop = true;
278 } else {
279 // Drop some frames based on input fps and output fps.
280 // Normally output fps is less than input fps.
281 // TODO(fbarchard): Consider adjusting interval to reflect the adjusted
282 // interval between frames after dropping some frames.
283 interval_next_frame_ += input_format_.interval;
284 if (output_format_.interval > 0) {
285 if (interval_next_frame_ >= output_format_.interval) {
286 interval_next_frame_ %= output_format_.interval;
287 } else {
288 should_drop = true;
289 }
290 }
291 }
292 if (should_drop) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000293 // Show VAdapt log every 90 frames dropped. (3 seconds)
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000294 if ((frames_in_ - frames_out_) % 90 == 0) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000295 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
296 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000297 LOG(LS_INFO) << "VAdapt Drop Frame: scaled " << frames_scaled_
298 << " / out " << frames_out_
299 << " / in " << frames_in_
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000300 << " Changes: " << adaption_changes_
301 << " Input: " << in_frame->GetWidth()
302 << "x" << in_frame->GetHeight()
303 << " i" << input_format_.interval
304 << " Output: i" << output_format_.interval;
305 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000306 *out_frame = NULL;
307 return true;
308 }
309
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000310 float scale = 1.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000311 if (output_num_pixels_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000312 scale = VideoAdapter::FindClosestViewScale(
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000313 static_cast<int>(in_frame->GetWidth()),
314 static_cast<int>(in_frame->GetHeight()),
315 output_num_pixels_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000316 output_format_.width = static_cast<int>(in_frame->GetWidth() * scale + .5f);
317 output_format_.height = static_cast<int>(in_frame->GetHeight() * scale +
318 .5f);
319 }
320
321 if (!StretchToOutputFrame(in_frame)) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000322 LOG(LS_VERBOSE) << "VAdapt Stretch Failed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000323 return false;
324 }
325
326 *out_frame = output_frame_.get();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000327
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000328 ++frames_out_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000329 if (in_frame->GetWidth() != (*out_frame)->GetWidth() ||
330 in_frame->GetHeight() != (*out_frame)->GetHeight()) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000331 ++frames_scaled_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000332 }
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000333 // Show VAdapt log every 90 frames output. (3 seconds)
334 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
335 // for LS_VERBOSE and more for LS_INFO.
336 bool show = (frames_out_) % 90 == 0;
337
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000338 // TODO(fbarchard): LOG the previous output resolution and track input
339 // resolution changes as well. Consider dropping the statistics into their
340 // own class which could be queried publically.
341 bool changed = false;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000342 if (previous_width_ && (previous_width_ != (*out_frame)->GetWidth() ||
343 previous_height_ != (*out_frame)->GetHeight())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000344 show = true;
345 ++adaption_changes_;
346 changed = true;
347 }
348 if (show) {
349 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
350 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000351 LOG(LS_INFO) << "VAdapt Frame: scaled " << frames_scaled_
352 << " / out " << frames_out_
353 << " / in " << frames_in_
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000354 << " Changes: " << adaption_changes_
355 << " Input: " << in_frame->GetWidth()
356 << "x" << in_frame->GetHeight()
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000357 << " i" << input_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000358 << " Scale: " << scale
359 << " Output: " << (*out_frame)->GetWidth()
360 << "x" << (*out_frame)->GetHeight()
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000361 << " i" << output_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000362 << " Changed: " << (changed ? "true" : "false");
363 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000364 previous_width_ = (*out_frame)->GetWidth();
365 previous_height_ = (*out_frame)->GetHeight();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000366
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000367 return true;
368}
369
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000370void VideoAdapter::set_scale_third(bool enable) {
371 LOG(LS_INFO) << "Video Adapter third scaling is now "
372 << (enable ? "enabled" : "disabled");
373 scale_third_ = enable;
374}
375
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000376// Scale or Blacken the frame. Returns true if successful.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000377bool VideoAdapter::StretchToOutputFrame(const VideoFrame* in_frame) {
378 int output_width = output_format_.width;
379 int output_height = output_format_.height;
380
381 // Create and stretch the output frame if it has not been created yet or its
382 // size is not same as the expected.
383 bool stretched = false;
384 if (!output_frame_ ||
385 output_frame_->GetWidth() != static_cast<size_t>(output_width) ||
386 output_frame_->GetHeight() != static_cast<size_t>(output_height)) {
387 output_frame_.reset(
388 in_frame->Stretch(output_width, output_height, true, true));
389 if (!output_frame_) {
390 LOG(LS_WARNING) << "Adapter failed to stretch frame to "
391 << output_width << "x" << output_height;
392 return false;
393 }
394 stretched = true;
395 is_black_ = false;
396 }
397
398 if (!black_output_) {
399 if (!stretched) {
400 // The output frame does not need to be blacken and has not been stretched
401 // from the input frame yet, stretch the input frame. This is the most
402 // common case.
403 in_frame->StretchToFrame(output_frame_.get(), true, true);
404 }
405 is_black_ = false;
406 } else {
407 if (!is_black_) {
408 output_frame_->SetToBlack();
409 is_black_ = true;
410 }
411 output_frame_->SetElapsedTime(in_frame->GetElapsedTime());
412 output_frame_->SetTimeStamp(in_frame->GetTimeStamp());
413 }
414
415 return true;
416}
417
418///////////////////////////////////////////////////////////////////////
419// Implementation of CoordinatedVideoAdapter
420CoordinatedVideoAdapter::CoordinatedVideoAdapter()
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000421 : cpu_adaptation_(true),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000422 cpu_smoothing_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000423 gd_adaptation_(true),
424 view_adaptation_(true),
425 view_switch_(false),
426 cpu_downgrade_count_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000427 cpu_load_min_samples_(kCpuLoadMinSamples),
428 cpu_load_num_samples_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000429 high_system_threshold_(kHighSystemCpuThreshold),
430 low_system_threshold_(kLowSystemCpuThreshold),
431 process_threshold_(kProcessCpuThreshold),
432 view_desired_num_pixels_(INT_MAX),
433 view_desired_interval_(0),
434 encoder_desired_num_pixels_(INT_MAX),
435 cpu_desired_num_pixels_(INT_MAX),
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000436 adapt_reason_(ADAPTREASON_NONE),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000437 system_load_average_(kCpuLoadInitialAverage) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000438}
439
440// Helper function to UPGRADE or DOWNGRADE a number of pixels
441void CoordinatedVideoAdapter::StepPixelCount(
442 CoordinatedVideoAdapter::AdaptRequest request,
443 int* num_pixels) {
444 switch (request) {
445 case CoordinatedVideoAdapter::DOWNGRADE:
446 *num_pixels /= 2;
447 break;
448
449 case CoordinatedVideoAdapter::UPGRADE:
450 *num_pixels *= 2;
451 break;
452
453 default: // No change in pixel count
454 break;
455 }
456 return;
457}
458
459// Find the adaptation request of the cpu based on the load. Return UPGRADE if
460// the load is low, DOWNGRADE if the load is high, and KEEP otherwise.
461CoordinatedVideoAdapter::AdaptRequest CoordinatedVideoAdapter::FindCpuRequest(
462 int current_cpus, int max_cpus,
463 float process_load, float system_load) {
464 // Downgrade if system is high and plugin is at least more than midrange.
465 if (system_load >= high_system_threshold_ * max_cpus &&
466 process_load >= process_threshold_ * current_cpus) {
467 return CoordinatedVideoAdapter::DOWNGRADE;
468 // Upgrade if system is low.
469 } else if (system_load < low_system_threshold_ * max_cpus) {
470 return CoordinatedVideoAdapter::UPGRADE;
471 }
472 return CoordinatedVideoAdapter::KEEP;
473}
474
475// A remote view request for a new resolution.
476void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
477 talk_base::CritScope cs(&request_critical_section_);
478 if (!view_adaptation_) {
479 return;
480 }
481 // Set output for initial aspect ratio in mediachannel unittests.
482 int old_num_pixels = GetOutputNumPixels();
483 SetOutputFormat(format);
484 SetOutputNumPixels(old_num_pixels);
485 view_desired_num_pixels_ = format.width * format.height;
486 view_desired_interval_ = format.interval;
487 int new_width, new_height;
488 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
489 LOG(LS_INFO) << "VAdapt View Request: "
490 << format.width << "x" << format.height
491 << " Pixels: " << view_desired_num_pixels_
492 << " Changed: " << (changed ? "true" : "false")
493 << " To: " << new_width << "x" << new_height;
494}
495
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000496void CoordinatedVideoAdapter::set_cpu_load_min_samples(
497 int cpu_load_min_samples) {
498 if (cpu_load_min_samples_ != cpu_load_min_samples) {
499 LOG(LS_INFO) << "VAdapt Change Cpu Adapt Min Samples from: "
500 << cpu_load_min_samples_ << " to "
501 << cpu_load_min_samples;
502 cpu_load_min_samples_ = cpu_load_min_samples;
503 }
504}
505
506void CoordinatedVideoAdapter::set_high_system_threshold(
507 float high_system_threshold) {
508 ASSERT(high_system_threshold <= 1.0f);
509 ASSERT(high_system_threshold >= 0.0f);
510 if (high_system_threshold_ != high_system_threshold) {
511 LOG(LS_INFO) << "VAdapt Change High System Threshold from: "
512 << high_system_threshold_ << " to " << high_system_threshold;
513 high_system_threshold_ = high_system_threshold;
514 }
515}
516
517void CoordinatedVideoAdapter::set_low_system_threshold(
518 float low_system_threshold) {
519 ASSERT(low_system_threshold <= 1.0f);
520 ASSERT(low_system_threshold >= 0.0f);
521 if (low_system_threshold_ != low_system_threshold) {
522 LOG(LS_INFO) << "VAdapt Change Low System Threshold from: "
523 << low_system_threshold_ << " to " << low_system_threshold;
524 low_system_threshold_ = low_system_threshold;
525 }
526}
527
528void CoordinatedVideoAdapter::set_process_threshold(float process_threshold) {
529 ASSERT(process_threshold <= 1.0f);
530 ASSERT(process_threshold >= 0.0f);
531 if (process_threshold_ != process_threshold) {
532 LOG(LS_INFO) << "VAdapt Change High Process Threshold from: "
533 << process_threshold_ << " to " << process_threshold;
534 process_threshold_ = process_threshold;
535 }
536}
537
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000538// A Bandwidth GD request for new resolution
539void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
540 int width, int height, AdaptRequest request) {
541 talk_base::CritScope cs(&request_critical_section_);
542 if (!gd_adaptation_) {
543 return;
544 }
545 int old_encoder_desired_num_pixels = encoder_desired_num_pixels_;
546 if (KEEP != request) {
547 int new_encoder_desired_num_pixels = width * height;
548 int old_num_pixels = GetOutputNumPixels();
549 if (new_encoder_desired_num_pixels != old_num_pixels) {
550 LOG(LS_VERBOSE) << "VAdapt GD resolution stale. Ignored";
551 } else {
552 // Update the encoder desired format based on the request.
553 encoder_desired_num_pixels_ = new_encoder_desired_num_pixels;
554 StepPixelCount(request, &encoder_desired_num_pixels_);
555 }
556 }
557 int new_width, new_height;
558 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
559
560 // Ignore up or keep if no change.
561 if (DOWNGRADE != request && view_switch_ && !changed) {
562 encoder_desired_num_pixels_ = old_encoder_desired_num_pixels;
563 LOG(LS_VERBOSE) << "VAdapt ignoring GD request.";
564 }
565
566 LOG(LS_INFO) << "VAdapt GD Request: "
567 << (DOWNGRADE == request ? "down" :
568 (UPGRADE == request ? "up" : "keep"))
569 << " From: " << width << "x" << height
570 << " Pixels: " << encoder_desired_num_pixels_
571 << " Changed: " << (changed ? "true" : "false")
572 << " To: " << new_width << "x" << new_height;
573}
574
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000575// A Bandwidth GD request for new resolution
576void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000577 talk_base::CritScope cs(&request_critical_section_);
578 if (!cpu_adaptation_) {
579 return;
580 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000581 // Update how many times we have downgraded due to the cpu load.
582 switch (request) {
583 case DOWNGRADE:
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000584 // Ignore downgrades if we have downgraded the maximum times.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585 if (cpu_downgrade_count_ < kMaxCpuDowngrades) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000586 ++cpu_downgrade_count_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587 } else {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000588 LOG(LS_VERBOSE) << "VAdapt CPU load high but do not downgrade "
589 "because maximum downgrades reached";
590 SignalCpuAdaptationUnable();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000591 }
592 break;
593 case UPGRADE:
594 if (cpu_downgrade_count_ > 0) {
595 bool is_min = IsMinimumFormat(cpu_desired_num_pixels_);
596 if (is_min) {
597 --cpu_downgrade_count_;
598 } else {
599 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
600 "because cpu is not limiting resolution";
601 }
602 } else {
603 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
604 "because minimum downgrades reached";
605 }
606 break;
607 case KEEP:
608 default:
609 break;
610 }
611 if (KEEP != request) {
612 // TODO(fbarchard): compute stepping up/down from OutputNumPixels but
613 // clamp to inputpixels / 4 (2 steps)
614 cpu_desired_num_pixels_ = cpu_downgrade_count_ == 0 ? INT_MAX :
615 static_cast<int>(input_format().width * input_format().height >>
616 cpu_downgrade_count_);
617 }
618 int new_width, new_height;
619 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
620 LOG(LS_INFO) << "VAdapt CPU Request: "
621 << (DOWNGRADE == request ? "down" :
622 (UPGRADE == request ? "up" : "keep"))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000623 << " Steps: " << cpu_downgrade_count_
624 << " Changed: " << (changed ? "true" : "false")
625 << " To: " << new_width << "x" << new_height;
626}
627
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000628// A CPU request for new resolution
629// TODO(fbarchard): Move outside adapter.
630void CoordinatedVideoAdapter::OnCpuLoadUpdated(
631 int current_cpus, int max_cpus, float process_load, float system_load) {
632 talk_base::CritScope cs(&request_critical_section_);
633 if (!cpu_adaptation_) {
634 return;
635 }
636 // Update the moving average of system load. Even if we aren't smoothing,
637 // we'll still calculate this information, in case smoothing is later enabled.
638 system_load_average_ = kCpuLoadWeightCoefficient * system_load +
639 (1.0f - kCpuLoadWeightCoefficient) * system_load_average_;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000640 ++cpu_load_num_samples_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000641 if (cpu_smoothing_) {
642 system_load = system_load_average_;
643 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000644 AdaptRequest request = FindCpuRequest(current_cpus, max_cpus,
645 process_load, system_load);
646 // Make sure we're not adapting too quickly.
647 if (request != KEEP) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000648 if (cpu_load_num_samples_ < cpu_load_min_samples_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000649 LOG(LS_VERBOSE) << "VAdapt CPU load high/low but do not adapt until "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000650 << (cpu_load_min_samples_ - cpu_load_num_samples_)
651 << " more samples";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000652 request = KEEP;
653 }
654 }
655
656 OnCpuResolutionRequest(request);
657}
658
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000659// Called by cpu adapter on up requests.
660bool CoordinatedVideoAdapter::IsMinimumFormat(int pixels) {
661 // Find closest scale factor that matches input resolution to min_num_pixels
662 // and set that for output resolution. This is not needed for VideoAdapter,
663 // but provides feedback to unittests and users on expected resolution.
664 // Actual resolution is based on input frame.
665 VideoFormat new_output = output_format();
666 VideoFormat input = input_format();
667 if (input_format().IsSize0x0()) {
668 input = new_output;
669 }
670 float scale = 1.0f;
671 if (!input.IsSize0x0()) {
672 scale = FindClosestScale(input.width,
673 input.height,
674 pixels);
675 }
676 new_output.width = static_cast<int>(input.width * scale + .5f);
677 new_output.height = static_cast<int>(input.height * scale + .5f);
678 int new_pixels = new_output.width * new_output.height;
679 int num_pixels = GetOutputNumPixels();
680 return new_pixels <= num_pixels;
681}
682
683// Called by all coordinators when there is a change.
684bool CoordinatedVideoAdapter::AdaptToMinimumFormat(int* new_width,
685 int* new_height) {
686 VideoFormat new_output = output_format();
687 VideoFormat input = input_format();
688 if (input_format().IsSize0x0()) {
689 input = new_output;
690 }
691 int old_num_pixels = GetOutputNumPixels();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000692 int min_num_pixels = INT_MAX;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000693 adapt_reason_ = ADAPTREASON_NONE;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000694
695 // Reduce resolution based on encoder bandwidth (GD).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696 if (encoder_desired_num_pixels_ &&
697 (encoder_desired_num_pixels_ < min_num_pixels)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000698 adapt_reason_ |= ADAPTREASON_BANDWIDTH;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699 min_num_pixels = encoder_desired_num_pixels_;
700 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000701 // Reduce resolution based on CPU.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702 if (cpu_adaptation_ && cpu_desired_num_pixels_ &&
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000703 (cpu_desired_num_pixels_ <= min_num_pixels)) {
704 if (cpu_desired_num_pixels_ < min_num_pixels) {
705 adapt_reason_ = ADAPTREASON_CPU;
706 } else {
707 adapt_reason_ |= ADAPTREASON_CPU;
708 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000709 min_num_pixels = cpu_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000711 // Round resolution for GD or CPU to allow 1/2 to map to 9/16.
712 if (!input.IsSize0x0() && min_num_pixels != INT_MAX) {
713 float scale = FindClosestScale(input.width, input.height, min_num_pixels);
714 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
715 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000717 // Reduce resolution based on View Request.
718 if (view_desired_num_pixels_ <= min_num_pixels) {
719 if (view_desired_num_pixels_ < min_num_pixels) {
720 adapt_reason_ = ADAPTREASON_VIEW;
721 } else {
722 adapt_reason_ |= ADAPTREASON_VIEW;
723 }
724 min_num_pixels = view_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000726 // Snap to a scale factor.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727 float scale = 1.0f;
728 if (!input.IsSize0x0()) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000729 scale = FindLowerScale(input.width, input.height, min_num_pixels);
730 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
731 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732 }
733 if (scale == 1.0f) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000734 adapt_reason_ = ADAPTREASON_NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735 }
736 *new_width = new_output.width = static_cast<int>(input.width * scale + .5f);
737 *new_height = new_output.height = static_cast<int>(input.height * scale +
738 .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000739 SetOutputNumPixels(min_num_pixels);
740
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741 new_output.interval = view_desired_interval_;
742 SetOutputFormat(new_output);
743 int new_num_pixels = GetOutputNumPixels();
744 bool changed = new_num_pixels != old_num_pixels;
745
746 static const char* kReasons[8] = {
747 "None",
748 "CPU",
749 "BANDWIDTH",
750 "CPU+BANDWIDTH",
751 "VIEW",
752 "CPU+VIEW",
753 "BANDWIDTH+VIEW",
754 "CPU+BANDWIDTH+VIEW",
755 };
756
757 LOG(LS_VERBOSE) << "VAdapt Status View: " << view_desired_num_pixels_
758 << " GD: " << encoder_desired_num_pixels_
759 << " CPU: " << cpu_desired_num_pixels_
760 << " Pixels: " << min_num_pixels
761 << " Input: " << input.width
762 << "x" << input.height
763 << " Scale: " << scale
764 << " Resolution: " << new_output.width
765 << "x" << new_output.height
766 << " Changed: " << (changed ? "true" : "false")
767 << " Reason: " << kReasons[adapt_reason_];
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000768
769 if (changed) {
770 // When any adaptation occurs, historic CPU load levels are no longer
771 // accurate. Clear out our state so we can re-learn at the new normal.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000772 cpu_load_num_samples_ = 0;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000773 system_load_average_ = kCpuLoadInitialAverage;
774 }
775
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000776 return changed;
777}
778
779} // namespace cricket