blob: f0182f4fb18a6ef5a6bef33e6c8f1e58de6d4ed1 [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
wu@webrtc.org967bfff2013-09-19 05:49:50 +000028#include "talk/app/webrtc/videosource.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000029
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.
wu@webrtc.org967bfff2013-09-19 05:49:50 +000075static const cricket::VideoFormatPod kDefaultFormat =
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076 {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
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000279 int default_area = kDefaultFormat.width * kDefaultFormat.height;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000280
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
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000331class FrameInputWrapper : public cricket::VideoRenderer {
332 public:
333 explicit FrameInputWrapper(cricket::VideoCapturer* capturer)
334 : capturer_(capturer) {
335 ASSERT(capturer_ != NULL);
336 }
337
338 virtual ~FrameInputWrapper() {}
339
340 // VideoRenderer implementation.
341 virtual bool SetSize(int width, int height, int reserved) OVERRIDE {
342 return true;
343 }
344
345 virtual bool RenderFrame(const cricket::VideoFrame* frame) OVERRIDE {
346 if (!capturer_->IsRunning()) {
347 return true;
348 }
349
350 // This signal will be made on media engine render thread. The clients
351 // of this signal should have no assumptions on what thread this signal
352 // come from.
353 capturer_->SignalVideoFrame(capturer_, frame);
354 return true;
355 }
356
357 private:
358 cricket::VideoCapturer* capturer_;
359 int width_;
360 int height_;
361
362 DISALLOW_COPY_AND_ASSIGN(FrameInputWrapper);
363};
364
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000365} // anonymous namespace
366
367namespace webrtc {
368
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000369talk_base::scoped_refptr<VideoSource> VideoSource::Create(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370 cricket::ChannelManager* channel_manager,
371 cricket::VideoCapturer* capturer,
372 const webrtc::MediaConstraintsInterface* constraints) {
373 ASSERT(channel_manager != NULL);
374 ASSERT(capturer != NULL);
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000375 talk_base::scoped_refptr<VideoSource> source(
376 new talk_base::RefCountedObject<VideoSource>(channel_manager,
377 capturer));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000378 source->Initialize(constraints);
379 return source;
380}
381
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000382VideoSource::VideoSource(cricket::ChannelManager* channel_manager,
383 cricket::VideoCapturer* capturer)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000384 : channel_manager_(channel_manager),
385 video_capturer_(capturer),
386 state_(kInitializing) {
387 channel_manager_->SignalVideoCaptureStateChange.connect(
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000388 this, &VideoSource::OnStateChange);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000389}
390
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000391VideoSource::~VideoSource() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000392 channel_manager_->StopVideoCapture(video_capturer_.get(), format_);
393 channel_manager_->SignalVideoCaptureStateChange.disconnect(this);
394}
395
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000396void VideoSource::Initialize(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000397 const webrtc::MediaConstraintsInterface* constraints) {
398
399 std::vector<cricket::VideoFormat> formats;
400 if (video_capturer_->GetSupportedFormats() &&
401 video_capturer_->GetSupportedFormats()->size() > 0) {
402 formats = *video_capturer_->GetSupportedFormats();
403 } else if (video_capturer_->IsScreencast()) {
404 // The screen capturer can accept any resolution and we will derive the
405 // format from the constraints if any.
406 // Note that this only affects tab capturing, not desktop capturing,
407 // since desktop capturer does not respect the VideoFormat passed in.
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000408 formats.push_back(cricket::VideoFormat(kDefaultFormat));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000409 } else {
410 // The VideoCapturer implementation doesn't support capability enumeration.
411 // We need to guess what the camera support.
412 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
413 formats.push_back(cricket::VideoFormat(kVideoFormats[i]));
414 }
415 }
416
417 if (constraints) {
418 MediaConstraintsInterface::Constraints mandatory_constraints =
419 constraints->GetMandatory();
420 MediaConstraintsInterface::Constraints optional_constraints;
421 optional_constraints = constraints->GetOptional();
422
423 if (video_capturer_->IsScreencast()) {
424 // Use the maxWidth and maxHeight allowed by constraints for screencast.
425 FromConstraintsForScreencast(mandatory_constraints, &(formats[0]));
426 }
427
428 formats = FilterFormats(mandatory_constraints, optional_constraints,
429 formats);
430 }
431
432 if (formats.size() == 0) {
433 LOG(LS_WARNING) << "Failed to find a suitable video format.";
434 SetState(kEnded);
435 return;
436 }
437
438 cricket::VideoOptions options;
439 if (!ExtractVideoOptions(constraints, &options)) {
440 LOG(LS_WARNING) << "Could not satisfy mandatory options.";
441 SetState(kEnded);
442 return;
443 }
444 options_.SetAll(options);
445
446 format_ = GetBestCaptureFormat(formats);
447 // Start the camera with our best guess.
448 // TODO(perkj): Should we try again with another format it it turns out that
449 // the camera doesn't produce frames with the correct format? Or will
450 // cricket::VideCapturer be able to re-scale / crop to the requested
451 // resolution?
452 if (!channel_manager_->StartVideoCapture(video_capturer_.get(), format_)) {
453 SetState(kEnded);
454 return;
455 }
456 // Initialize hasn't succeeded until a successful state change has occurred.
457}
458
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000459cricket::VideoRenderer* VideoSource::FrameInput() {
460 // Defer creation of frame_input_ until it's needed, e.g. the local video
461 // sources will never need it.
462 if (!frame_input_) {
463 frame_input_.reset(new FrameInputWrapper(video_capturer_.get()));
464 }
465 return frame_input_.get();
466}
467
468void VideoSource::AddSink(cricket::VideoRenderer* output) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000469 channel_manager_->AddVideoRenderer(video_capturer_.get(), output);
470}
471
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000472void VideoSource::RemoveSink(cricket::VideoRenderer* output) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000473 channel_manager_->RemoveVideoRenderer(video_capturer_.get(), output);
474}
475
476// OnStateChange listens to the ChannelManager::SignalVideoCaptureStateChange.
477// This signal is triggered for all video capturers. Not only the one we are
478// interested in.
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000479void VideoSource::OnStateChange(cricket::VideoCapturer* capturer,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000480 cricket::CaptureState capture_state) {
481 if (capturer == video_capturer_.get()) {
482 SetState(GetReadyState(capture_state));
483 }
484}
485
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000486void VideoSource::SetState(SourceState new_state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000487 if (VERIFY(state_ != new_state)) {
488 state_ = new_state;
489 FireOnChanged();
490 }
491}
492
493} // namespace webrtc