blob: 9b344daec5e9aecf172a43867e10f9d7b0c8aee4 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2012, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/localvideosource.h"
29
30#include <vector>
31
32#include "talk/app/webrtc/mediaconstraintsinterface.h"
33#include "talk/session/media/channelmanager.h"
34
35using cricket::CaptureState;
36using webrtc::MediaConstraintsInterface;
37using webrtc::MediaSourceInterface;
38
39namespace webrtc {
40
41// Constraint keys. Specified by draft-alvestrand-constraints-resolution-00b
42// They are declared as static members in mediastreaminterface.h
43const char MediaConstraintsInterface::kMinAspectRatio[] = "minAspectRatio";
44const char MediaConstraintsInterface::kMaxAspectRatio[] = "maxAspectRatio";
45const char MediaConstraintsInterface::kMaxWidth[] = "maxWidth";
46const char MediaConstraintsInterface::kMinWidth[] = "minWidth";
47const char MediaConstraintsInterface::kMaxHeight[] = "maxHeight";
48const char MediaConstraintsInterface::kMinHeight[] = "minHeight";
49const char MediaConstraintsInterface::kMaxFrameRate[] = "maxFrameRate";
50const char MediaConstraintsInterface::kMinFrameRate[] = "minFrameRate";
51
52// Google-specific keys
53const char MediaConstraintsInterface::kNoiseReduction[] = "googNoiseReduction";
54const char MediaConstraintsInterface::kLeakyBucket[] = "googLeakyBucket";
55const char MediaConstraintsInterface::kTemporalLayeredScreencast[] =
56 "googTemporalLayeredScreencast";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000057// TODO(ronghuawu): Remove once cpu overuse detection is stable.
58const char MediaConstraintsInterface::kCpuOveruseDetection[] =
59 "googCpuOveruseDetection";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060
61} // namespace webrtc
62
63namespace {
64
65const double kRoundingTruncation = 0.0005;
66
67enum {
68 MSG_VIDEOCAPTURESTATECONNECT,
69 MSG_VIDEOCAPTURESTATEDISCONNECT,
70 MSG_VIDEOCAPTURESTATECHANGE,
71};
72
73// Default resolution. If no constraint is specified, this is the resolution we
74// will use.
75static const cricket::VideoFormatPod kDefaultResolution =
76 {640, 480, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY};
77
78// List of formats used if the camera doesn't support capability enumeration.
79static const cricket::VideoFormatPod kVideoFormats[] = {
80 {1920, 1080, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
81 {1280, 720, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
82 {960, 720, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
83 {640, 360, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
84 {640, 480, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
85 {320, 240, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY},
86 {320, 180, FPS_TO_INTERVAL(30), cricket::FOURCC_ANY}
87};
88
89MediaSourceInterface::SourceState
90GetReadyState(cricket::CaptureState state) {
91 switch (state) {
92 case cricket::CS_STARTING:
93 return MediaSourceInterface::kInitializing;
94 case cricket::CS_RUNNING:
95 return MediaSourceInterface::kLive;
96 case cricket::CS_FAILED:
97 case cricket::CS_NO_DEVICE:
98 case cricket::CS_STOPPED:
99 return MediaSourceInterface::kEnded;
100 case cricket::CS_PAUSED:
101 return MediaSourceInterface::kMuted;
102 default:
103 ASSERT(false && "GetReadyState unknown state");
104 }
105 return MediaSourceInterface::kEnded;
106}
107
108void SetUpperLimit(int new_limit, int* original_limit) {
109 if (*original_limit < 0 || new_limit < *original_limit)
110 *original_limit = new_limit;
111}
112
113// Updates |format_upper_limit| from |constraint|.
114// If constraint.maxFoo is smaller than format_upper_limit.foo,
115// set format_upper_limit.foo to constraint.maxFoo.
116void SetUpperLimitFromConstraint(
117 const MediaConstraintsInterface::Constraint& constraint,
118 cricket::VideoFormat* format_upper_limit) {
119 if (constraint.key == MediaConstraintsInterface::kMaxWidth) {
120 int value = talk_base::FromString<int>(constraint.value);
121 SetUpperLimit(value, &(format_upper_limit->width));
122 } else if (constraint.key == MediaConstraintsInterface::kMaxHeight) {
123 int value = talk_base::FromString<int>(constraint.value);
124 SetUpperLimit(value, &(format_upper_limit->height));
125 }
126}
127
128// Fills |format_out| with the max width and height allowed by |constraints|.
129void FromConstraintsForScreencast(
130 const MediaConstraintsInterface::Constraints& constraints,
131 cricket::VideoFormat* format_out) {
132 typedef MediaConstraintsInterface::Constraints::const_iterator
133 ConstraintsIterator;
134
135 cricket::VideoFormat upper_limit(-1, -1, 0, 0);
136 for (ConstraintsIterator constraints_it = constraints.begin();
137 constraints_it != constraints.end(); ++constraints_it)
138 SetUpperLimitFromConstraint(*constraints_it, &upper_limit);
139
140 if (upper_limit.width >= 0)
141 format_out->width = upper_limit.width;
142 if (upper_limit.height >= 0)
143 format_out->height = upper_limit.height;
144}
145
146// Returns true if |constraint| is fulfilled. |format_out| can differ from
147// |format_in| if the format is changed by the constraint. Ie - the frame rate
148// can be changed by setting maxFrameRate.
149bool NewFormatWithConstraints(
150 const MediaConstraintsInterface::Constraint& constraint,
151 const cricket::VideoFormat& format_in,
152 bool mandatory,
153 cricket::VideoFormat* format_out) {
154 ASSERT(format_out != NULL);
155 *format_out = format_in;
156
157 if (constraint.key == MediaConstraintsInterface::kMinWidth) {
158 int value = talk_base::FromString<int>(constraint.value);
159 return (value <= format_in.width);
160 } else if (constraint.key == MediaConstraintsInterface::kMaxWidth) {
161 int value = talk_base::FromString<int>(constraint.value);
162 return (value >= format_in.width);
163 } else if (constraint.key == MediaConstraintsInterface::kMinHeight) {
164 int value = talk_base::FromString<int>(constraint.value);
165 return (value <= format_in.height);
166 } else if (constraint.key == MediaConstraintsInterface::kMaxHeight) {
167 int value = talk_base::FromString<int>(constraint.value);
168 return (value >= format_in.height);
169 } else if (constraint.key == MediaConstraintsInterface::kMinFrameRate) {
170 int value = talk_base::FromString<int>(constraint.value);
171 return (value <= cricket::VideoFormat::IntervalToFps(format_in.interval));
172 } else if (constraint.key == MediaConstraintsInterface::kMaxFrameRate) {
173 int value = talk_base::FromString<int>(constraint.value);
174 if (value == 0) {
175 if (mandatory) {
176 // TODO(ronghuawu): Convert the constraint value to float when sub-1fps
177 // is supported by the capturer.
178 return false;
179 } else {
180 value = 1;
181 }
182 }
183 if (value <= cricket::VideoFormat::IntervalToFps(format_in.interval)) {
184 format_out->interval = cricket::VideoFormat::FpsToInterval(value);
185 return true;
186 } else {
187 return false;
188 }
189 } else if (constraint.key == MediaConstraintsInterface::kMinAspectRatio) {
190 double value = talk_base::FromString<double>(constraint.value);
191 // The aspect ratio in |constraint.value| has been converted to a string and
192 // back to a double, so it may have a rounding error.
193 // E.g if the value 1/3 is converted to a string, the string will not have
194 // infinite length.
195 // We add a margin of 0.0005 which is high enough to detect the same aspect
196 // ratio but small enough to avoid matching wrong aspect ratios.
197 double ratio = static_cast<double>(format_in.width) / format_in.height;
198 return (value <= ratio + kRoundingTruncation);
199 } else if (constraint.key == MediaConstraintsInterface::kMaxAspectRatio) {
200 double value = talk_base::FromString<double>(constraint.value);
201 double ratio = static_cast<double>(format_in.width) / format_in.height;
202 // Subtract 0.0005 to avoid rounding problems. Same as above.
203 const double kRoundingTruncation = 0.0005;
204 return (value >= ratio - kRoundingTruncation);
205 } else if (constraint.key == MediaConstraintsInterface::kNoiseReduction ||
206 constraint.key == MediaConstraintsInterface::kLeakyBucket ||
207 constraint.key ==
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000208 MediaConstraintsInterface::kTemporalLayeredScreencast ||
209 constraint.key ==
210 MediaConstraintsInterface::kCpuOveruseDetection) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000211 // These are actually options, not constraints, so they can be satisfied
212 // regardless of the format.
213 return true;
214 }
215 LOG(LS_WARNING) << "Found unknown MediaStream constraint. Name:"
216 << constraint.key << " Value:" << constraint.value;
217 return false;
218}
219
220// Removes cricket::VideoFormats from |formats| that don't meet |constraint|.
221void FilterFormatsByConstraint(
222 const MediaConstraintsInterface::Constraint& constraint,
223 bool mandatory,
224 std::vector<cricket::VideoFormat>* formats) {
225 std::vector<cricket::VideoFormat>::iterator format_it =
226 formats->begin();
227 while (format_it != formats->end()) {
228 // Modify the format_it to fulfill the constraint if possible.
229 // Delete it otherwise.
230 if (!NewFormatWithConstraints(constraint, (*format_it),
231 mandatory, &(*format_it))) {
232 format_it = formats->erase(format_it);
233 } else {
234 ++format_it;
235 }
236 }
237}
238
239// Returns a vector of cricket::VideoFormat that best match |constraints|.
240std::vector<cricket::VideoFormat> FilterFormats(
241 const MediaConstraintsInterface::Constraints& mandatory,
242 const MediaConstraintsInterface::Constraints& optional,
243 const std::vector<cricket::VideoFormat>& supported_formats) {
244 typedef MediaConstraintsInterface::Constraints::const_iterator
245 ConstraintsIterator;
246 std::vector<cricket::VideoFormat> candidates = supported_formats;
247
248 for (ConstraintsIterator constraints_it = mandatory.begin();
249 constraints_it != mandatory.end(); ++constraints_it)
250 FilterFormatsByConstraint(*constraints_it, true, &candidates);
251
252 if (candidates.size() == 0)
253 return candidates;
254
255 // Ok - all mandatory checked and we still have a candidate.
256 // Let's try filtering using the optional constraints.
257 for (ConstraintsIterator constraints_it = optional.begin();
258 constraints_it != optional.end(); ++constraints_it) {
259 std::vector<cricket::VideoFormat> current_candidates = candidates;
260 FilterFormatsByConstraint(*constraints_it, false, &current_candidates);
261 if (current_candidates.size() > 0) {
262 candidates = current_candidates;
263 }
264 }
265
266 // We have done as good as we can to filter the supported resolutions.
267 return candidates;
268}
269
270// Find the format that best matches the default video size.
271// Constraints are optional and since the performance of a video call
272// might be bad due to bitrate limitations, CPU, and camera performance,
273// it is better to select a resolution that is as close as possible to our
274// default and still meets the contraints.
275const cricket::VideoFormat& GetBestCaptureFormat(
276 const std::vector<cricket::VideoFormat>& formats) {
277 ASSERT(formats.size() > 0);
278
279 int default_area = kDefaultResolution.width * kDefaultResolution.height;
280
281 std::vector<cricket::VideoFormat>::const_iterator it = formats.begin();
282 std::vector<cricket::VideoFormat>::const_iterator best_it = formats.begin();
283 int best_diff = abs(default_area - it->width* it->height);
284 for (; it != formats.end(); ++it) {
285 int diff = abs(default_area - it->width* it->height);
286 if (diff < best_diff) {
287 best_diff = diff;
288 best_it = it;
289 }
290 }
291 return *best_it;
292}
293
294// Set |option| to the highest-priority value of |key| in the constraints.
295// Return false if the key is mandatory, and the value is invalid.
296bool ExtractOption(const MediaConstraintsInterface* all_constraints,
297 const std::string& key, cricket::Settable<bool>* option) {
298 size_t mandatory = 0;
299 bool value;
300 if (FindConstraint(all_constraints, key, &value, &mandatory)) {
301 option->Set(value);
302 return true;
303 }
304
305 return mandatory == 0;
306}
307
308// Search |all_constraints| for known video options. Apply all options that are
309// found with valid values, and return false if any mandatory video option was
310// found with an invalid value.
311bool ExtractVideoOptions(const MediaConstraintsInterface* all_constraints,
312 cricket::VideoOptions* options) {
313 bool all_valid = true;
314
315 all_valid &= ExtractOption(all_constraints,
316 MediaConstraintsInterface::kNoiseReduction,
317 &(options->video_noise_reduction));
318 all_valid &= ExtractOption(all_constraints,
319 MediaConstraintsInterface::kLeakyBucket,
320 &(options->video_leaky_bucket));
321 all_valid &= ExtractOption(all_constraints,
322 MediaConstraintsInterface::kTemporalLayeredScreencast,
323 &(options->video_temporal_layer_screencast));
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000324 all_valid &= ExtractOption(all_constraints,
325 MediaConstraintsInterface::kCpuOveruseDetection,
326 &(options->cpu_overuse_detection));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000327
328 return all_valid;
329}
330
331} // anonymous namespace
332
333namespace webrtc {
334
335talk_base::scoped_refptr<LocalVideoSource> LocalVideoSource::Create(
336 cricket::ChannelManager* channel_manager,
337 cricket::VideoCapturer* capturer,
338 const webrtc::MediaConstraintsInterface* constraints) {
339 ASSERT(channel_manager != NULL);
340 ASSERT(capturer != NULL);
341 talk_base::scoped_refptr<LocalVideoSource> source(
342 new talk_base::RefCountedObject<LocalVideoSource>(channel_manager,
343 capturer));
344 source->Initialize(constraints);
345 return source;
346}
347
348LocalVideoSource::LocalVideoSource(cricket::ChannelManager* channel_manager,
349 cricket::VideoCapturer* capturer)
350 : channel_manager_(channel_manager),
351 video_capturer_(capturer),
352 state_(kInitializing) {
353 channel_manager_->SignalVideoCaptureStateChange.connect(
354 this, &LocalVideoSource::OnStateChange);
355}
356
357LocalVideoSource::~LocalVideoSource() {
358 channel_manager_->StopVideoCapture(video_capturer_.get(), format_);
359 channel_manager_->SignalVideoCaptureStateChange.disconnect(this);
360}
361
362void LocalVideoSource::Initialize(
363 const webrtc::MediaConstraintsInterface* constraints) {
364
365 std::vector<cricket::VideoFormat> formats;
366 if (video_capturer_->GetSupportedFormats() &&
367 video_capturer_->GetSupportedFormats()->size() > 0) {
368 formats = *video_capturer_->GetSupportedFormats();
369 } else if (video_capturer_->IsScreencast()) {
370 // The screen capturer can accept any resolution and we will derive the
371 // format from the constraints if any.
372 // Note that this only affects tab capturing, not desktop capturing,
373 // since desktop capturer does not respect the VideoFormat passed in.
374 formats.push_back(cricket::VideoFormat(kDefaultResolution));
375 } else {
376 // The VideoCapturer implementation doesn't support capability enumeration.
377 // We need to guess what the camera support.
378 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
379 formats.push_back(cricket::VideoFormat(kVideoFormats[i]));
380 }
381 }
382
383 if (constraints) {
384 MediaConstraintsInterface::Constraints mandatory_constraints =
385 constraints->GetMandatory();
386 MediaConstraintsInterface::Constraints optional_constraints;
387 optional_constraints = constraints->GetOptional();
388
389 if (video_capturer_->IsScreencast()) {
390 // Use the maxWidth and maxHeight allowed by constraints for screencast.
391 FromConstraintsForScreencast(mandatory_constraints, &(formats[0]));
392 }
393
394 formats = FilterFormats(mandatory_constraints, optional_constraints,
395 formats);
396 }
397
398 if (formats.size() == 0) {
399 LOG(LS_WARNING) << "Failed to find a suitable video format.";
400 SetState(kEnded);
401 return;
402 }
403
404 cricket::VideoOptions options;
405 if (!ExtractVideoOptions(constraints, &options)) {
406 LOG(LS_WARNING) << "Could not satisfy mandatory options.";
407 SetState(kEnded);
408 return;
409 }
410 options_.SetAll(options);
411
412 format_ = GetBestCaptureFormat(formats);
413 // Start the camera with our best guess.
414 // TODO(perkj): Should we try again with another format it it turns out that
415 // the camera doesn't produce frames with the correct format? Or will
416 // cricket::VideCapturer be able to re-scale / crop to the requested
417 // resolution?
418 if (!channel_manager_->StartVideoCapture(video_capturer_.get(), format_)) {
419 SetState(kEnded);
420 return;
421 }
422 // Initialize hasn't succeeded until a successful state change has occurred.
423}
424
425void LocalVideoSource::AddSink(cricket::VideoRenderer* output) {
426 channel_manager_->AddVideoRenderer(video_capturer_.get(), output);
427}
428
429void LocalVideoSource::RemoveSink(cricket::VideoRenderer* output) {
430 channel_manager_->RemoveVideoRenderer(video_capturer_.get(), output);
431}
432
433// OnStateChange listens to the ChannelManager::SignalVideoCaptureStateChange.
434// This signal is triggered for all video capturers. Not only the one we are
435// interested in.
436void LocalVideoSource::OnStateChange(cricket::VideoCapturer* capturer,
437 cricket::CaptureState capture_state) {
438 if (capturer == video_capturer_.get()) {
439 SetState(GetReadyState(capture_state));
440 }
441}
442
443void LocalVideoSource::SetState(SourceState new_state) {
444 if (VERIFY(state_ != new_state)) {
445 state_ = new_state;
446 FireOnChanged();
447 }
448}
449
450} // namespace webrtc