blob: bbfb3348bec126fb7c561aa715d08ddd455d23e4 [file] [log] [blame]
perkj11e18052016-03-07 22:03:23 +01001/*
perkj11e18052016-03-07 22:03:23 +01002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/videocapturertracksource.h"
perkj11e18052016-03-07 22:03:23 +010012
perkja3ede6c2016-03-08 01:27:48 +010013#include <cstdlib>
14#include <string>
Steve Anton36b29d12017-10-30 09:57:42 -070015#include <utility>
perkja3ede6c2016-03-08 01:27:48 +010016#include <vector>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/mediaconstraintsinterface.h"
19#include "rtc_base/arraysize.h"
20#include "rtc_base/checks.h"
perkja3ede6c2016-03-08 01:27:48 +010021
22using cricket::CaptureState;
23using webrtc::MediaConstraintsInterface;
24using webrtc::MediaSourceInterface;
25
26namespace {
27
28const double kRoundingTruncation = 0.0005;
29
30// Default resolution. If no constraint is specified, this is the resolution we
31// will use.
32static const cricket::VideoFormatPod kDefaultFormat = {
33 640, 480, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY};
34
35// List of formats used if the camera doesn't support capability enumeration.
36static const cricket::VideoFormatPod kVideoFormats[] = {
37 {1920, 1080, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
38 {1280, 720, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
39 {960, 720, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
40 {640, 360, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
41 {640, 480, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
42 {320, 240, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
43 {320, 180, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY}};
44
45MediaSourceInterface::SourceState GetReadyState(cricket::CaptureState state) {
46 switch (state) {
47 case cricket::CS_STARTING:
48 return MediaSourceInterface::kInitializing;
49 case cricket::CS_RUNNING:
50 return MediaSourceInterface::kLive;
51 case cricket::CS_FAILED:
52 case cricket::CS_STOPPED:
53 return MediaSourceInterface::kEnded;
perkja3ede6c2016-03-08 01:27:48 +010054 default:
nisseede5da42017-01-12 05:15:36 -080055 RTC_NOTREACHED() << "GetReadyState unknown state";
perkja3ede6c2016-03-08 01:27:48 +010056 }
57 return MediaSourceInterface::kEnded;
58}
59
60void SetUpperLimit(int new_limit, int* original_limit) {
61 if (*original_limit < 0 || new_limit < *original_limit)
62 *original_limit = new_limit;
63}
64
65// Updates |format_upper_limit| from |constraint|.
66// If constraint.maxFoo is smaller than format_upper_limit.foo,
67// set format_upper_limit.foo to constraint.maxFoo.
68void SetUpperLimitFromConstraint(
69 const MediaConstraintsInterface::Constraint& constraint,
70 cricket::VideoFormat* format_upper_limit) {
71 if (constraint.key == MediaConstraintsInterface::kMaxWidth) {
72 int value = rtc::FromString<int>(constraint.value);
73 SetUpperLimit(value, &(format_upper_limit->width));
74 } else if (constraint.key == MediaConstraintsInterface::kMaxHeight) {
75 int value = rtc::FromString<int>(constraint.value);
76 SetUpperLimit(value, &(format_upper_limit->height));
77 }
78}
79
80// Fills |format_out| with the max width and height allowed by |constraints|.
81void FromConstraintsForScreencast(
82 const MediaConstraintsInterface::Constraints& constraints,
83 cricket::VideoFormat* format_out) {
84 typedef MediaConstraintsInterface::Constraints::const_iterator
85 ConstraintsIterator;
86
87 cricket::VideoFormat upper_limit(-1, -1, 0, 0);
88 for (ConstraintsIterator constraints_it = constraints.begin();
89 constraints_it != constraints.end(); ++constraints_it)
90 SetUpperLimitFromConstraint(*constraints_it, &upper_limit);
91
92 if (upper_limit.width >= 0)
93 format_out->width = upper_limit.width;
94 if (upper_limit.height >= 0)
95 format_out->height = upper_limit.height;
96}
97
98// Returns true if |constraint| is fulfilled. |format_out| can differ from
99// |format_in| if the format is changed by the constraint. Ie - the frame rate
100// can be changed by setting maxFrameRate.
101bool NewFormatWithConstraints(
102 const MediaConstraintsInterface::Constraint& constraint,
103 const cricket::VideoFormat& format_in,
104 bool mandatory,
105 cricket::VideoFormat* format_out) {
nisseede5da42017-01-12 05:15:36 -0800106 RTC_DCHECK(format_out != NULL);
perkja3ede6c2016-03-08 01:27:48 +0100107 *format_out = format_in;
108
109 if (constraint.key == MediaConstraintsInterface::kMinWidth) {
110 int value = rtc::FromString<int>(constraint.value);
111 return (value <= format_in.width);
112 } else if (constraint.key == MediaConstraintsInterface::kMaxWidth) {
113 int value = rtc::FromString<int>(constraint.value);
114 return (value >= format_in.width);
115 } else if (constraint.key == MediaConstraintsInterface::kMinHeight) {
116 int value = rtc::FromString<int>(constraint.value);
117 return (value <= format_in.height);
118 } else if (constraint.key == MediaConstraintsInterface::kMaxHeight) {
119 int value = rtc::FromString<int>(constraint.value);
120 return (value >= format_in.height);
121 } else if (constraint.key == MediaConstraintsInterface::kMinFrameRate) {
122 int value = rtc::FromString<int>(constraint.value);
123 return (value <= cricket::VideoFormat::IntervalToFps(format_in.interval));
124 } else if (constraint.key == MediaConstraintsInterface::kMaxFrameRate) {
125 int value = rtc::FromString<int>(constraint.value);
126 if (value == 0) {
127 if (mandatory) {
128 // TODO(ronghuawu): Convert the constraint value to float when sub-1fps
129 // is supported by the capturer.
130 return false;
131 } else {
132 value = 1;
133 }
134 }
135 if (value <= cricket::VideoFormat::IntervalToFps(format_in.interval))
136 format_out->interval = cricket::VideoFormat::FpsToInterval(value);
137 return true;
138 } else if (constraint.key == MediaConstraintsInterface::kMinAspectRatio) {
139 double value = rtc::FromString<double>(constraint.value);
140 // The aspect ratio in |constraint.value| has been converted to a string and
141 // back to a double, so it may have a rounding error.
142 // E.g if the value 1/3 is converted to a string, the string will not have
143 // infinite length.
144 // We add a margin of 0.0005 which is high enough to detect the same aspect
145 // ratio but small enough to avoid matching wrong aspect ratios.
146 double ratio = static_cast<double>(format_in.width) / format_in.height;
147 return (value <= ratio + kRoundingTruncation);
148 } else if (constraint.key == MediaConstraintsInterface::kMaxAspectRatio) {
149 double value = rtc::FromString<double>(constraint.value);
150 double ratio = static_cast<double>(format_in.width) / format_in.height;
151 // Subtract 0.0005 to avoid rounding problems. Same as above.
152 const double kRoundingTruncation = 0.0005;
153 return (value >= ratio - kRoundingTruncation);
154 } else if (constraint.key == MediaConstraintsInterface::kNoiseReduction) {
155 // These are actually options, not constraints, so they can be satisfied
156 // regardless of the format.
157 return true;
158 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100159 RTC_LOG(LS_WARNING) << "Found unknown MediaStream constraint. Name:"
160 << constraint.key << " Value:" << constraint.value;
perkja3ede6c2016-03-08 01:27:48 +0100161 return false;
162}
163
164// Removes cricket::VideoFormats from |formats| that don't meet |constraint|.
165void FilterFormatsByConstraint(
166 const MediaConstraintsInterface::Constraint& constraint,
167 bool mandatory,
168 std::vector<cricket::VideoFormat>* formats) {
169 std::vector<cricket::VideoFormat>::iterator format_it = formats->begin();
170 while (format_it != formats->end()) {
171 // Modify the format_it to fulfill the constraint if possible.
172 // Delete it otherwise.
173 if (!NewFormatWithConstraints(constraint, (*format_it), mandatory,
174 &(*format_it))) {
175 format_it = formats->erase(format_it);
176 } else {
177 ++format_it;
178 }
179 }
180}
181
182// Returns a vector of cricket::VideoFormat that best match |constraints|.
183std::vector<cricket::VideoFormat> FilterFormats(
184 const MediaConstraintsInterface::Constraints& mandatory,
185 const MediaConstraintsInterface::Constraints& optional,
186 const std::vector<cricket::VideoFormat>& supported_formats) {
187 typedef MediaConstraintsInterface::Constraints::const_iterator
188 ConstraintsIterator;
189 std::vector<cricket::VideoFormat> candidates = supported_formats;
190
191 for (ConstraintsIterator constraints_it = mandatory.begin();
192 constraints_it != mandatory.end(); ++constraints_it)
193 FilterFormatsByConstraint(*constraints_it, true, &candidates);
194
195 if (candidates.size() == 0)
196 return candidates;
197
198 // Ok - all mandatory checked and we still have a candidate.
199 // Let's try filtering using the optional constraints.
200 for (ConstraintsIterator constraints_it = optional.begin();
201 constraints_it != optional.end(); ++constraints_it) {
202 std::vector<cricket::VideoFormat> current_candidates = candidates;
203 FilterFormatsByConstraint(*constraints_it, false, &current_candidates);
204 if (current_candidates.size() > 0) {
205 candidates = current_candidates;
206 }
207 }
208
209 // We have done as good as we can to filter the supported resolutions.
210 return candidates;
211}
212
213// Find the format that best matches the default video size.
214// Constraints are optional and since the performance of a video call
215// might be bad due to bitrate limitations, CPU, and camera performance,
216// it is better to select a resolution that is as close as possible to our
217// default and still meets the contraints.
218const cricket::VideoFormat& GetBestCaptureFormat(
219 const std::vector<cricket::VideoFormat>& formats) {
nisseede5da42017-01-12 05:15:36 -0800220 RTC_DCHECK(formats.size() > 0);
perkja3ede6c2016-03-08 01:27:48 +0100221
222 int default_area = kDefaultFormat.width * kDefaultFormat.height;
223
224 std::vector<cricket::VideoFormat>::const_iterator it = formats.begin();
225 std::vector<cricket::VideoFormat>::const_iterator best_it = formats.begin();
226 int best_diff_area = std::abs(default_area - it->width * it->height);
227 int64_t best_diff_interval = kDefaultFormat.interval;
228 for (; it != formats.end(); ++it) {
229 int diff_area = std::abs(default_area - it->width * it->height);
230 int64_t diff_interval = std::abs(kDefaultFormat.interval - it->interval);
231 if (diff_area < best_diff_area ||
232 (diff_area == best_diff_area && diff_interval < best_diff_interval)) {
233 best_diff_area = diff_area;
234 best_diff_interval = diff_interval;
235 best_it = it;
236 }
237 }
238 return *best_it;
239}
240
241// Set |option| to the highest-priority value of |key| in the constraints.
242// Return false if the key is mandatory, and the value is invalid.
243bool ExtractOption(const MediaConstraintsInterface* all_constraints,
244 const std::string& key,
Perc0d31e92016-03-31 17:23:39 +0200245 rtc::Optional<bool>* option) {
perkja3ede6c2016-03-08 01:27:48 +0100246 size_t mandatory = 0;
Perc0d31e92016-03-31 17:23:39 +0200247 bool value;
248 if (FindConstraint(all_constraints, key, &value, &mandatory)) {
Oskar Sundbom36f8f3e2017-11-16 10:54:27 +0100249 *option = value;
perkja3ede6c2016-03-08 01:27:48 +0100250 return true;
251 }
252
253 return mandatory == 0;
254}
255
perkja3ede6c2016-03-08 01:27:48 +0100256} // anonymous namespace
257
258namespace webrtc {
259
260rtc::scoped_refptr<VideoTrackSourceInterface> VideoCapturerTrackSource::Create(
261 rtc::Thread* worker_thread,
deadbeef112b2e92017-02-10 20:13:37 -0800262 std::unique_ptr<cricket::VideoCapturer> capturer,
perkja3ede6c2016-03-08 01:27:48 +0100263 const webrtc::MediaConstraintsInterface* constraints,
264 bool remote) {
265 RTC_DCHECK(worker_thread != NULL);
steweg4b371272017-04-09 09:09:06 -0700266 RTC_DCHECK(capturer != nullptr);
perkja3ede6c2016-03-08 01:27:48 +0100267 rtc::scoped_refptr<VideoCapturerTrackSource> source(
deadbeef112b2e92017-02-10 20:13:37 -0800268 new rtc::RefCountedObject<VideoCapturerTrackSource>(
269 worker_thread, std::move(capturer), remote));
perkja3ede6c2016-03-08 01:27:48 +0100270 source->Initialize(constraints);
271 return source;
272}
273
274rtc::scoped_refptr<VideoTrackSourceInterface> VideoCapturerTrackSource::Create(
275 rtc::Thread* worker_thread,
deadbeef112b2e92017-02-10 20:13:37 -0800276 std::unique_ptr<cricket::VideoCapturer> capturer,
perkja3ede6c2016-03-08 01:27:48 +0100277 bool remote) {
278 RTC_DCHECK(worker_thread != NULL);
steweg4b371272017-04-09 09:09:06 -0700279 RTC_DCHECK(capturer != nullptr);
perkja3ede6c2016-03-08 01:27:48 +0100280 rtc::scoped_refptr<VideoCapturerTrackSource> source(
deadbeef112b2e92017-02-10 20:13:37 -0800281 new rtc::RefCountedObject<VideoCapturerTrackSource>(
282 worker_thread, std::move(capturer), remote));
perkja3ede6c2016-03-08 01:27:48 +0100283 source->Initialize(nullptr);
284 return source;
285}
286
287VideoCapturerTrackSource::VideoCapturerTrackSource(
288 rtc::Thread* worker_thread,
deadbeef112b2e92017-02-10 20:13:37 -0800289 std::unique_ptr<cricket::VideoCapturer> capturer,
perkja3ede6c2016-03-08 01:27:48 +0100290 bool remote)
deadbeef112b2e92017-02-10 20:13:37 -0800291 : VideoTrackSource(capturer.get(), remote),
perkj0d3eef22016-03-09 02:39:17 +0100292 signaling_thread_(rtc::Thread::Current()),
nisse5b68ab52016-04-07 07:45:54 -0700293 worker_thread_(worker_thread),
deadbeef112b2e92017-02-10 20:13:37 -0800294 video_capturer_(std::move(capturer)),
Perc0d31e92016-03-31 17:23:39 +0200295 started_(false) {
perkja3ede6c2016-03-08 01:27:48 +0100296 video_capturer_->SignalStateChange.connect(
297 this, &VideoCapturerTrackSource::OnStateChange);
298}
299
300VideoCapturerTrackSource::~VideoCapturerTrackSource() {
301 video_capturer_->SignalStateChange.disconnect(this);
302 Stop();
303}
304
305void VideoCapturerTrackSource::Initialize(
306 const webrtc::MediaConstraintsInterface* constraints) {
307 std::vector<cricket::VideoFormat> formats =
308 *video_capturer_->GetSupportedFormats();
309 if (formats.empty()) {
310 if (video_capturer_->IsScreencast()) {
311 // The screen capturer can accept any resolution and we will derive the
312 // format from the constraints if any.
313 // Note that this only affects tab capturing, not desktop capturing,
314 // since the desktop capturer does not respect the VideoFormat passed in.
315 formats.push_back(cricket::VideoFormat(kDefaultFormat));
316 } else {
317 // The VideoCapturer implementation doesn't support capability
318 // enumeration. We need to guess what the camera supports.
kjellander3e33bfe2016-06-20 07:04:09 -0700319 for (uint32_t i = 0; i < arraysize(kVideoFormats); ++i) {
perkja3ede6c2016-03-08 01:27:48 +0100320 formats.push_back(cricket::VideoFormat(kVideoFormats[i]));
321 }
322 }
323 }
324
325 if (constraints) {
326 MediaConstraintsInterface::Constraints mandatory_constraints =
327 constraints->GetMandatory();
328 MediaConstraintsInterface::Constraints optional_constraints;
329 optional_constraints = constraints->GetOptional();
330
331 if (video_capturer_->IsScreencast()) {
332 // Use the maxWidth and maxHeight allowed by constraints for screencast.
333 FromConstraintsForScreencast(mandatory_constraints, &(formats[0]));
334 }
335
336 formats =
337 FilterFormats(mandatory_constraints, optional_constraints, formats);
338 }
339
340 if (formats.size() == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100341 RTC_LOG(LS_WARNING) << "Failed to find a suitable video format.";
perkja3ede6c2016-03-08 01:27:48 +0100342 SetState(kEnded);
343 return;
344 }
345
perkj0d3eef22016-03-09 02:39:17 +0100346 if (!ExtractOption(constraints, MediaConstraintsInterface::kNoiseReduction,
347 &needs_denoising_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100348 RTC_LOG(LS_WARNING) << "Invalid mandatory value for"
349 << MediaConstraintsInterface::kNoiseReduction;
perkja3ede6c2016-03-08 01:27:48 +0100350 SetState(kEnded);
351 return;
352 }
perkja3ede6c2016-03-08 01:27:48 +0100353
354 format_ = GetBestCaptureFormat(formats);
355 // Start the camera with our best guess.
nisse5b68ab52016-04-07 07:45:54 -0700356 if (!worker_thread_->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700357 RTC_FROM_HERE, rtc::Bind(&cricket::VideoCapturer::StartCapturing,
358 video_capturer_.get(), format_))) {
perkja3ede6c2016-03-08 01:27:48 +0100359 SetState(kEnded);
360 return;
361 }
362 started_ = true;
363 // Initialize hasn't succeeded until a successful state change has occurred.
364}
365
nissefcc640f2016-04-01 01:10:42 -0700366bool VideoCapturerTrackSource::GetStats(Stats* stats) {
367 return video_capturer_->GetInputSize(&stats->input_width,
368 &stats->input_height);
369}
370
perkja3ede6c2016-03-08 01:27:48 +0100371void VideoCapturerTrackSource::Stop() {
372 if (!started_) {
373 return;
374 }
375 started_ = false;
nisse5b68ab52016-04-07 07:45:54 -0700376 worker_thread_->Invoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700377 RTC_FROM_HERE,
perkja3ede6c2016-03-08 01:27:48 +0100378 rtc::Bind(&cricket::VideoCapturer::Stop, video_capturer_.get()));
379}
380
perkja3ede6c2016-03-08 01:27:48 +0100381// OnStateChange listens to the cricket::VideoCapturer::SignalStateChange.
382void VideoCapturerTrackSource::OnStateChange(
383 cricket::VideoCapturer* capturer,
384 cricket::CaptureState capture_state) {
385 if (rtc::Thread::Current() != signaling_thread_) {
deadbeeff15fb452017-02-25 13:37:59 -0800386 // Use rtc::Unretained, because we don't want this to capture a reference
387 // to ourselves. If our destructor is called while this task is executing,
388 // that's fine; our AsyncInvoker destructor will wait for it to finish if
389 // it isn't simply canceled.
perkja3ede6c2016-03-08 01:27:48 +0100390 invoker_.AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700391 RTC_FROM_HERE, signaling_thread_,
deadbeeff15fb452017-02-25 13:37:59 -0800392 rtc::Bind(&VideoCapturerTrackSource::OnStateChange,
393 rtc::Unretained(this), capturer, capture_state));
perkja3ede6c2016-03-08 01:27:48 +0100394 return;
395 }
396
397 if (capturer == video_capturer_.get()) {
398 SetState(GetReadyState(capture_state));
399 }
400}
401
perkja3ede6c2016-03-08 01:27:48 +0100402} // namespace webrtc