blob: bcaeb89ea4ff0c4b10f7868b90849967beadc576 [file] [log] [blame]
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00001/*
2 * libjingle
3 * Copyright 2011 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 */
henrike@webrtc.org28e20752013-07-10 00:45:36 +000027
28#include "talk/media/webrtc/webrtcvideocapturer.h"
29
30#ifdef HAVE_CONFIG_H
31#include <config.h>
32#endif
33
34#ifdef HAVE_WEBRTC_VIDEO
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000035#include "talk/media/webrtc/webrtcvideoframe.h"
36#include "talk/media/webrtc/webrtcvideoframefactory.h"
tommi@webrtc.orge07710c2015-02-19 17:43:25 +000037#include "webrtc/base/bind.h"
38#include "webrtc/base/checks.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000039#include "webrtc/base/criticalsection.h"
40#include "webrtc/base/logging.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000041#include "webrtc/base/safe_conversions.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000042#include "webrtc/base/thread.h"
43#include "webrtc/base/timeutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000044
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000045#include "webrtc/base/win32.h" // Need this to #include the impl files.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000046#include "webrtc/modules/video_capture/include/video_capture_factory.h"
Guo-wei Shieh64c1e8c2015-04-01 15:33:06 -070047#include "webrtc/system_wrappers/interface/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000048
49namespace cricket {
50
51struct kVideoFourCCEntry {
52 uint32 fourcc;
53 webrtc::RawVideoType webrtc_type;
54};
55
56// This indicates our format preferences and defines a mapping between
57// webrtc::RawVideoType (from video_capture_defines.h) to our FOURCCs.
58static kVideoFourCCEntry kSupportedFourCCs[] = {
59 { FOURCC_I420, webrtc::kVideoI420 }, // 12 bpp, no conversion.
60 { FOURCC_YV12, webrtc::kVideoYV12 }, // 12 bpp, no conversion.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000061 { FOURCC_YUY2, webrtc::kVideoYUY2 }, // 16 bpp, fast conversion.
62 { FOURCC_UYVY, webrtc::kVideoUYVY }, // 16 bpp, fast conversion.
buildbot@webrtc.orgfa5fcd62014-07-21 21:55:43 +000063 { FOURCC_NV12, webrtc::kVideoNV12 }, // 12 bpp, fast conversion.
64 { FOURCC_NV21, webrtc::kVideoNV21 }, // 12 bpp, fast conversion.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065 { FOURCC_MJPG, webrtc::kVideoMJPEG }, // compressed, slow conversion.
66 { FOURCC_ARGB, webrtc::kVideoARGB }, // 32 bpp, slow conversion.
67 { FOURCC_24BG, webrtc::kVideoRGB24 }, // 24 bpp, slow conversion.
68};
69
70class WebRtcVcmFactory : public WebRtcVcmFactoryInterface {
71 public:
72 virtual webrtc::VideoCaptureModule* Create(int id, const char* device) {
73 return webrtc::VideoCaptureFactory::Create(id, device);
74 }
75 virtual webrtc::VideoCaptureModule::DeviceInfo* CreateDeviceInfo(int id) {
76 return webrtc::VideoCaptureFactory::CreateDeviceInfo(id);
77 }
78 virtual void DestroyDeviceInfo(webrtc::VideoCaptureModule::DeviceInfo* info) {
79 delete info;
80 }
81};
82
83static bool CapabilityToFormat(const webrtc::VideoCaptureCapability& cap,
84 VideoFormat* format) {
85 uint32 fourcc = 0;
86 for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {
87 if (kSupportedFourCCs[i].webrtc_type == cap.rawType) {
88 fourcc = kSupportedFourCCs[i].fourcc;
89 break;
90 }
91 }
92 if (fourcc == 0) {
93 return false;
94 }
95
96 format->fourcc = fourcc;
97 format->width = cap.width;
98 format->height = cap.height;
99 format->interval = VideoFormat::FpsToInterval(cap.maxFPS);
100 return true;
101}
102
103static bool FormatToCapability(const VideoFormat& format,
104 webrtc::VideoCaptureCapability* cap) {
105 webrtc::RawVideoType webrtc_type = webrtc::kVideoUnknown;
106 for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {
107 if (kSupportedFourCCs[i].fourcc == format.fourcc) {
108 webrtc_type = kSupportedFourCCs[i].webrtc_type;
109 break;
110 }
111 }
112 if (webrtc_type == webrtc::kVideoUnknown) {
113 return false;
114 }
115
116 cap->width = format.width;
117 cap->height = format.height;
118 cap->maxFPS = VideoFormat::IntervalToFps(format.interval);
119 cap->expectedCaptureDelay = 0;
120 cap->rawType = webrtc_type;
121 cap->codecType = webrtc::kVideoCodecUnknown;
122 cap->interlaced = false;
123 return true;
124}
125
126///////////////////////////////////////////////////////////////////////////
127// Implementation of class WebRtcVideoCapturer
128///////////////////////////////////////////////////////////////////////////
129
130WebRtcVideoCapturer::WebRtcVideoCapturer()
131 : factory_(new WebRtcVcmFactory),
132 module_(NULL),
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000133 captured_frames_(0),
134 start_thread_(nullptr) {
buildbot@webrtc.org4f0d4012014-08-07 04:47:36 +0000135 set_frame_factory(new WebRtcVideoFrameFactory());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136}
137
138WebRtcVideoCapturer::WebRtcVideoCapturer(WebRtcVcmFactoryInterface* factory)
139 : factory_(factory),
140 module_(NULL),
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000141 captured_frames_(0),
142 start_thread_(nullptr) {
buildbot@webrtc.org4f0d4012014-08-07 04:47:36 +0000143 set_frame_factory(new WebRtcVideoFrameFactory());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000144}
145
146WebRtcVideoCapturer::~WebRtcVideoCapturer() {
147 if (module_) {
148 module_->Release();
149 }
150}
151
152bool WebRtcVideoCapturer::Init(const Device& device) {
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000153 DCHECK(!start_thread_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000154 if (module_) {
155 LOG(LS_ERROR) << "The capturer is already initialized";
156 return false;
157 }
158
159 webrtc::VideoCaptureModule::DeviceInfo* info = factory_->CreateDeviceInfo(0);
160 if (!info) {
161 return false;
162 }
163
164 // Find the desired camera, by name.
165 // In the future, comparing IDs will be more robust.
166 // TODO(juberti): Figure what's needed to allow this.
167 int num_cams = info->NumberOfDevices();
168 char vcm_id[256] = "";
169 bool found = false;
170 for (int index = 0; index < num_cams; ++index) {
171 char vcm_name[256];
172 if (info->GetDeviceName(index, vcm_name, ARRAY_SIZE(vcm_name),
173 vcm_id, ARRAY_SIZE(vcm_id)) != -1) {
174 if (device.name == reinterpret_cast<char*>(vcm_name)) {
175 found = true;
176 break;
177 }
178 }
179 }
180 if (!found) {
181 LOG(LS_WARNING) << "Failed to find capturer for id: " << device.id;
182 factory_->DestroyDeviceInfo(info);
183 return false;
184 }
185
186 // Enumerate the supported formats.
187 // TODO(juberti): Find out why this starts/stops the camera...
188 std::vector<VideoFormat> supported;
189 int32_t num_caps = info->NumberOfCapabilities(vcm_id);
190 for (int32_t i = 0; i < num_caps; ++i) {
191 webrtc::VideoCaptureCapability cap;
192 if (info->GetCapability(vcm_id, i, cap) != -1) {
193 VideoFormat format;
194 if (CapabilityToFormat(cap, &format)) {
195 supported.push_back(format);
196 } else {
197 LOG(LS_WARNING) << "Ignoring unsupported WebRTC capture format "
198 << cap.rawType;
199 }
200 }
201 }
202 factory_->DestroyDeviceInfo(info);
henrike@webrtc.orgd3d6bce2014-03-10 20:41:22 +0000203// TODO(fischman): Remove the following check
204// when capabilities for iOS are implemented
205// https://code.google.com/p/webrtc/issues/detail?id=2968
206#if !defined(IOS)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000207 if (supported.empty()) {
208 LOG(LS_ERROR) << "Failed to find usable formats for id: " << device.id;
209 return false;
210 }
henrike@webrtc.orgd3d6bce2014-03-10 20:41:22 +0000211#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000212 module_ = factory_->Create(0, vcm_id);
213 if (!module_) {
214 LOG(LS_ERROR) << "Failed to create capturer for id: " << device.id;
215 return false;
216 }
217
218 // It is safe to change member attributes now.
219 module_->AddRef();
220 SetId(device.id);
221 SetSupportedFormats(supported);
guoweis@webrtc.org1226e922015-02-11 18:37:54 +0000222
223 // Ensure these 2 have the same value.
224 SetApplyRotation(module_->GetApplyRotation());
225
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000226 return true;
227}
228
229bool WebRtcVideoCapturer::Init(webrtc::VideoCaptureModule* module) {
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000230 DCHECK(!start_thread_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231 if (module_) {
232 LOG(LS_ERROR) << "The capturer is already initialized";
233 return false;
234 }
235 if (!module) {
236 LOG(LS_ERROR) << "Invalid VCM supplied";
237 return false;
238 }
239 // TODO(juberti): Set id and formats.
240 (module_ = module)->AddRef();
241 return true;
242}
243
244bool WebRtcVideoCapturer::GetBestCaptureFormat(const VideoFormat& desired,
245 VideoFormat* best_format) {
246 if (!best_format) {
247 return false;
248 }
249
250 if (!VideoCapturer::GetBestCaptureFormat(desired, best_format)) {
251 // We maybe using a manually injected VCM which doesn't support enum.
252 // Use the desired format as the best format.
253 best_format->width = desired.width;
254 best_format->height = desired.height;
255 best_format->fourcc = FOURCC_I420;
256 best_format->interval = desired.interval;
257 LOG(LS_INFO) << "Failed to find best capture format,"
258 << " fall back to the requested format "
259 << best_format->ToString();
260 }
261 return true;
262}
guoweis@webrtc.org1226e922015-02-11 18:37:54 +0000263bool WebRtcVideoCapturer::SetApplyRotation(bool enable) {
Guo-wei Shieh64c1e8c2015-04-01 15:33:06 -0700264 // Can't take lock here as this will cause deadlock with
265 // OnIncomingCapturedFrame. In fact, the whole method, including methods it
266 // calls, can't take lock.
guoweis@webrtc.org1226e922015-02-11 18:37:54 +0000267 assert(module_);
268
Guo-wei Shieh64c1e8c2015-04-01 15:33:06 -0700269 const std::string group_name =
270 webrtc::field_trial::FindFullName("WebRTC-CVO");
271
272 if (group_name == "Disabled") {
273 return true;
274 }
275
guoweis@webrtc.org1226e922015-02-11 18:37:54 +0000276 if (!VideoCapturer::SetApplyRotation(enable)) {
277 return false;
278 }
279 return module_->SetApplyRotation(enable);
280}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000281
282CaptureState WebRtcVideoCapturer::Start(const VideoFormat& capture_format) {
283 if (!module_) {
284 LOG(LS_ERROR) << "The capturer has not been initialized";
285 return CS_NO_DEVICE;
286 }
287
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000288 rtc::CritScope cs(&critical_section_stopping_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000289 if (IsRunning()) {
290 LOG(LS_ERROR) << "The capturer is already running";
291 return CS_FAILED;
292 }
293
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000294 DCHECK(!start_thread_);
295
296 start_thread_ = rtc::Thread::Current();
297
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000298 SetCaptureFormat(&capture_format);
299
300 webrtc::VideoCaptureCapability cap;
301 if (!FormatToCapability(capture_format, &cap)) {
302 LOG(LS_ERROR) << "Invalid capture format specified";
303 return CS_FAILED;
304 }
305
306 std::string camera_id(GetId());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000307 uint32 start = rtc::Time();
mallinath@webrtc.org7433a082014-01-29 00:56:02 +0000308 module_->RegisterCaptureDataCallback(*this);
309 if (module_->StartCapture(cap) != 0) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000310 LOG(LS_ERROR) << "Camera '" << camera_id << "' failed to start";
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000311 start_thread_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000312 return CS_FAILED;
313 }
314
315 LOG(LS_INFO) << "Camera '" << camera_id << "' started with format "
316 << capture_format.ToString() << ", elapsed time "
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000317 << rtc::TimeSince(start) << " ms";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000318
319 captured_frames_ = 0;
320 SetCaptureState(CS_RUNNING);
321 return CS_STARTING;
322}
323
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000324// Critical section blocks Stop from shutting down during callbacks from capture
325// thread to OnIncomingCapturedFrame. Note that the crit is try-locked in
326// OnFrameCaptured, as the lock ordering between this and the system component
327// controlling the camera is reversed: system frame -> OnIncomingCapturedFrame;
328// Stop -> system stop camera).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000329void WebRtcVideoCapturer::Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000330 rtc::CritScope cs(&critical_section_stopping_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000331 if (IsRunning()) {
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000332 DCHECK(start_thread_);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000333 rtc::Thread::Current()->Clear(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000334 module_->StopCapture();
335 module_->DeRegisterCaptureDataCallback();
336
337 // TODO(juberti): Determine if the VCM exposes any drop stats we can use.
338 double drop_ratio = 0.0;
339 std::string camera_id(GetId());
340 LOG(LS_INFO) << "Camera '" << camera_id << "' stopped after capturing "
341 << captured_frames_ << " frames and dropping "
342 << drop_ratio << "%";
343 }
344 SetCaptureFormat(NULL);
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000345 start_thread_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000346}
347
348bool WebRtcVideoCapturer::IsRunning() {
349 return (module_ != NULL && module_->CaptureStarted());
350}
351
352bool WebRtcVideoCapturer::GetPreferredFourccs(
353 std::vector<uint32>* fourccs) {
354 if (!fourccs) {
355 return false;
356 }
357
358 fourccs->clear();
359 for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {
360 fourccs->push_back(kSupportedFourCCs[i].fourcc);
361 }
362 return true;
363}
364
perkj@webrtc.orgaf612d52015-03-18 09:51:05 +0000365void WebRtcVideoCapturer::OnIncomingCapturedFrame(
366 const int32_t id,
367 const webrtc::I420VideoFrame& sample) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000368 // This would be a normal CritScope, except that it's possible that:
369 // (1) whatever system component producing this frame has taken a lock, and
370 // (2) Stop() probably calls back into that system component, which may take
371 // the same lock. Due to the reversed order, we have to try-lock in order to
372 // avoid a potential deadlock. Besides, if we can't enter because we're
373 // stopping, we may as well drop the frame.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000374 rtc::TryCritScope cs(&critical_section_stopping_);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000375 if (!cs.locked() || !IsRunning()) {
376 // Capturer has been stopped or is in the process of stopping.
377 return;
378 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000379
380 ++captured_frames_;
381 // Log the size and pixel aspect ratio of the first captured frame.
382 if (1 == captured_frames_) {
383 LOG(LS_INFO) << "Captured frame size "
magjed@webrtc.org2056ee32015-03-16 13:46:52 +0000384 << sample.width() << "x" << sample.height()
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000385 << ". Expected format " << GetCaptureFormat()->ToString();
386 }
387
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000388 if (start_thread_->IsCurrent()) {
magjed@webrtc.org2056ee32015-03-16 13:46:52 +0000389 SignalFrameCapturedOnStartThread(&sample);
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000390 } else {
391 // This currently happens on with at least VideoCaptureModuleV4L2 and
392 // possibly other implementations of WebRTC's VideoCaptureModule.
393 // In order to maintain the threading contract with the upper layers and
394 // consistency with other capturers such as in Chrome, we need to do a
395 // thread hop.
396 start_thread_->Invoke<void>(
397 rtc::Bind(&WebRtcVideoCapturer::SignalFrameCapturedOnStartThread,
magjed@webrtc.org2056ee32015-03-16 13:46:52 +0000398 this, &sample));
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000399 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000400}
401
402void WebRtcVideoCapturer::OnCaptureDelayChanged(const int32_t id,
403 const int32_t delay) {
404 LOG(LS_INFO) << "Capture delay changed to " << delay << " ms";
405}
406
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000407void WebRtcVideoCapturer::SignalFrameCapturedOnStartThread(
perkj@webrtc.orgaf612d52015-03-18 09:51:05 +0000408 const webrtc::I420VideoFrame* frame) {
tommi@webrtc.orge07710c2015-02-19 17:43:25 +0000409 DCHECK(start_thread_->IsCurrent());
410 // Signal down stream components on captured frame.
411 // The CapturedFrame class doesn't support planes. We have to ExtractBuffer
412 // to one block for it.
413 size_t length =
414 webrtc::CalcBufferSize(webrtc::kI420, frame->width(), frame->height());
415 capture_buffer_.resize(length);
416 // TODO(magjed): Refactor the WebRtcCapturedFrame to avoid memory copy or
417 // take over ownership of the buffer held by |frame| if that's possible.
418 webrtc::ExtractBuffer(*frame, length, &capture_buffer_[0]);
419 WebRtcCapturedFrame webrtc_frame(*frame, &capture_buffer_[0], length);
420 SignalFrameCaptured(this, &webrtc_frame);
421}
422
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000423// WebRtcCapturedFrame
424WebRtcCapturedFrame::WebRtcCapturedFrame(const webrtc::I420VideoFrame& sample,
425 void* buffer,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000426 size_t length) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000427 width = sample.width();
428 height = sample.height();
429 fourcc = FOURCC_I420;
430 // TODO(hellner): Support pixel aspect ratio (for OSX).
431 pixel_width = 1;
432 pixel_height = 1;
433 // Convert units from VideoFrame RenderTimeMs to CapturedFrame (nanoseconds).
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000434 elapsed_time = sample.render_time_ms() * rtc::kNumNanosecsPerMillisec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000435 time_stamp = elapsed_time;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000436 data_size = rtc::checked_cast<uint32>(length);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000437 data = buffer;
guoweis@webrtc.org1226e922015-02-11 18:37:54 +0000438 rotation = sample.rotation();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000439}
440
441} // namespace cricket
442
443#endif // HAVE_WEBRTC_VIDEO