blob: e292c7a065ce2dcb828d101df67a0188be5e7f3e [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
11#include "webrtc/api/videocapturertracksource.h"
12
perkja3ede6c2016-03-08 01:27:48 +010013#include <cstdlib>
14#include <string>
15#include <vector>
16
17#include "webrtc/api/mediaconstraintsinterface.h"
18#include "webrtc/base/arraysize.h"
19
20using cricket::CaptureState;
21using webrtc::MediaConstraintsInterface;
22using webrtc::MediaSourceInterface;
23
24namespace {
25
26const double kRoundingTruncation = 0.0005;
27
28// Default resolution. If no constraint is specified, this is the resolution we
29// will use.
30static const cricket::VideoFormatPod kDefaultFormat = {
31 640, 480, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY};
32
33// List of formats used if the camera doesn't support capability enumeration.
34static const cricket::VideoFormatPod kVideoFormats[] = {
35 {1920, 1080, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
36 {1280, 720, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
37 {960, 720, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
38 {640, 360, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
39 {640, 480, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
40 {320, 240, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
41 {320, 180, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY}};
42
43MediaSourceInterface::SourceState GetReadyState(cricket::CaptureState state) {
44 switch (state) {
45 case cricket::CS_STARTING:
46 return MediaSourceInterface::kInitializing;
47 case cricket::CS_RUNNING:
48 return MediaSourceInterface::kLive;
49 case cricket::CS_FAILED:
50 case cricket::CS_STOPPED:
51 return MediaSourceInterface::kEnded;
52 case cricket::CS_PAUSED:
53 return MediaSourceInterface::kMuted;
54 default:
55 ASSERT(false && "GetReadyState unknown state");
56 }
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) {
106 ASSERT(format_out != NULL);
107 *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 }
159 LOG(LS_WARNING) << "Found unknown MediaStream constraint. Name:"
160 << constraint.key << " Value:" << constraint.value;
161 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) {
220 ASSERT(formats.size() > 0);
221
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,
perkj0d3eef22016-03-09 02:39:17 +0100245 bool* option) {
perkja3ede6c2016-03-08 01:27:48 +0100246 size_t mandatory = 0;
perkj0d3eef22016-03-09 02:39:17 +0100247 *option = false;
248 if (FindConstraint(all_constraints, key, option, &mandatory)) {
perkja3ede6c2016-03-08 01:27:48 +0100249 return true;
250 }
251
252 return mandatory == 0;
253}
254
perkja3ede6c2016-03-08 01:27:48 +0100255} // anonymous namespace
256
257namespace webrtc {
258
259rtc::scoped_refptr<VideoTrackSourceInterface> VideoCapturerTrackSource::Create(
260 rtc::Thread* worker_thread,
261 cricket::VideoCapturer* capturer,
262 const webrtc::MediaConstraintsInterface* constraints,
263 bool remote) {
264 RTC_DCHECK(worker_thread != NULL);
265 RTC_DCHECK(capturer != NULL);
266 rtc::scoped_refptr<VideoCapturerTrackSource> source(
267 new rtc::RefCountedObject<VideoCapturerTrackSource>(worker_thread,
268 capturer, remote));
269 source->Initialize(constraints);
270 return source;
271}
272
273rtc::scoped_refptr<VideoTrackSourceInterface> VideoCapturerTrackSource::Create(
274 rtc::Thread* worker_thread,
275 cricket::VideoCapturer* capturer,
276 bool remote) {
277 RTC_DCHECK(worker_thread != NULL);
278 RTC_DCHECK(capturer != NULL);
279 rtc::scoped_refptr<VideoCapturerTrackSource> source(
280 new rtc::RefCountedObject<VideoCapturerTrackSource>(worker_thread,
281 capturer, remote));
282 source->Initialize(nullptr);
283 return source;
284}
285
286VideoCapturerTrackSource::VideoCapturerTrackSource(
287 rtc::Thread* worker_thread,
288 cricket::VideoCapturer* capturer,
289 bool remote)
perkj0d3eef22016-03-09 02:39:17 +0100290 : VideoTrackSource(capturer, worker_thread, remote),
291 signaling_thread_(rtc::Thread::Current()),
perkja3ede6c2016-03-08 01:27:48 +0100292 video_capturer_(capturer),
293 started_(false),
perkj0d3eef22016-03-09 02:39:17 +0100294 needs_denoising_(false) {
perkja3ede6c2016-03-08 01:27:48 +0100295 video_capturer_->SignalStateChange.connect(
296 this, &VideoCapturerTrackSource::OnStateChange);
297}
298
299VideoCapturerTrackSource::~VideoCapturerTrackSource() {
300 video_capturer_->SignalStateChange.disconnect(this);
301 Stop();
302}
303
304void VideoCapturerTrackSource::Initialize(
305 const webrtc::MediaConstraintsInterface* constraints) {
306 std::vector<cricket::VideoFormat> formats =
307 *video_capturer_->GetSupportedFormats();
308 if (formats.empty()) {
309 if (video_capturer_->IsScreencast()) {
310 // The screen capturer can accept any resolution and we will derive the
311 // format from the constraints if any.
312 // Note that this only affects tab capturing, not desktop capturing,
313 // since the desktop capturer does not respect the VideoFormat passed in.
314 formats.push_back(cricket::VideoFormat(kDefaultFormat));
315 } else {
316 // The VideoCapturer implementation doesn't support capability
317 // enumeration. We need to guess what the camera supports.
318 for (int i = 0; i < arraysize(kVideoFormats); ++i) {
319 formats.push_back(cricket::VideoFormat(kVideoFormats[i]));
320 }
321 }
322 }
323
324 if (constraints) {
325 MediaConstraintsInterface::Constraints mandatory_constraints =
326 constraints->GetMandatory();
327 MediaConstraintsInterface::Constraints optional_constraints;
328 optional_constraints = constraints->GetOptional();
329
330 if (video_capturer_->IsScreencast()) {
331 // Use the maxWidth and maxHeight allowed by constraints for screencast.
332 FromConstraintsForScreencast(mandatory_constraints, &(formats[0]));
333 }
334
335 formats =
336 FilterFormats(mandatory_constraints, optional_constraints, formats);
337 }
338
339 if (formats.size() == 0) {
340 LOG(LS_WARNING) << "Failed to find a suitable video format.";
341 SetState(kEnded);
342 return;
343 }
344
perkj0d3eef22016-03-09 02:39:17 +0100345 if (!ExtractOption(constraints, MediaConstraintsInterface::kNoiseReduction,
346 &needs_denoising_)) {
347 LOG(LS_WARNING) << "Invalid mandatory value for"
348 << MediaConstraintsInterface::kNoiseReduction;
perkja3ede6c2016-03-08 01:27:48 +0100349 SetState(kEnded);
350 return;
351 }
perkja3ede6c2016-03-08 01:27:48 +0100352
353 format_ = GetBestCaptureFormat(formats);
354 // Start the camera with our best guess.
perkj0d3eef22016-03-09 02:39:17 +0100355 if (!worker_thread()->Invoke<bool>(
perkja3ede6c2016-03-08 01:27:48 +0100356 rtc::Bind(&cricket::VideoCapturer::StartCapturing,
357 video_capturer_.get(), format_))) {
358 SetState(kEnded);
359 return;
360 }
361 started_ = true;
362 // Initialize hasn't succeeded until a successful state change has occurred.
363}
364
365void VideoCapturerTrackSource::Stop() {
366 if (!started_) {
367 return;
368 }
369 started_ = false;
perkj0d3eef22016-03-09 02:39:17 +0100370 worker_thread()->Invoke<void>(
perkja3ede6c2016-03-08 01:27:48 +0100371 rtc::Bind(&cricket::VideoCapturer::Stop, video_capturer_.get()));
372}
373
374void VideoCapturerTrackSource::Restart() {
375 if (started_) {
376 return;
377 }
perkj0d3eef22016-03-09 02:39:17 +0100378 if (!worker_thread()->Invoke<bool>(
perkja3ede6c2016-03-08 01:27:48 +0100379 rtc::Bind(&cricket::VideoCapturer::StartCapturing,
380 video_capturer_.get(), format_))) {
381 SetState(kEnded);
382 return;
383 }
384 started_ = true;
385}
386
perkja3ede6c2016-03-08 01:27:48 +0100387// OnStateChange listens to the cricket::VideoCapturer::SignalStateChange.
388void VideoCapturerTrackSource::OnStateChange(
389 cricket::VideoCapturer* capturer,
390 cricket::CaptureState capture_state) {
391 if (rtc::Thread::Current() != signaling_thread_) {
392 invoker_.AsyncInvoke<void>(
393 signaling_thread_, rtc::Bind(&VideoCapturerTrackSource::OnStateChange,
394 this, capturer, capture_state));
395 return;
396 }
397
398 if (capturer == video_capturer_.get()) {
399 SetState(GetReadyState(capture_state));
400 }
401}
402
perkja3ede6c2016-03-08 01:27:48 +0100403} // namespace webrtc