Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(116)

Side by Side Diff: media/video/capture/win/video_capture_device_mf_win.cc

Issue 11419200: Video capture implementation using the Media Foundation API. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: ready for review Created 8 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "media/video/capture/win/video_capture_device_mf_win.h"
6
7 #include <mferror.h>
8
9 #include "base/lazy_instance.h"
10 #include "base/memory/ref_counted.h"
11 #include "base/synchronization/waitable_event.h"
12 #include "base/sys_string_conversions.h"
13 #include "base/win/scoped_co_mem.h"
14 #include "media/video/capture/win/capability_list_win.h"
15
16 using base::win::ScopedCoMem;
17 using base::win::ScopedComPtr;
18
19 namespace {
20
21 using media::CapabilityList;
darin (slow to review) 2012/11/29 00:28:05 nit: i recommend putting the anonymous namespace w
tommi (sloooow) - chröme 2012/11/29 11:02:58 Done.
22 using media::VideoCaptureCapability;
23 using media::VideoCaptureCapabilityWin;
24
25 class MFInitializerSingleton {
26 public:
27 MFInitializerSingleton() { MFStartup(MF_VERSION, MFSTARTUP_LITE); }
28 ~MFInitializerSingleton() { MFShutdown(); }
29 };
30
31 static base::LazyInstance<MFInitializerSingleton> g_mf_initialize =
32 LAZY_INSTANCE_INITIALIZER;
33
34 void EnsureMFInit() {
35 g_mf_initialize.Get();
36 }
37
38 bool PrepareVideoCaptureAttributes(IMFAttributes** attributes, int count) {
39 EnsureMFInit();
40
41 if (FAILED(MFCreateAttributes(attributes, count)))
42 return false;
43
44 return SUCCEEDED((*attributes)->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
45 MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID));
46 }
47
48 bool EnumerateVideoDevices(IMFActivate*** devices,
49 UINT32* count) {
50 ScopedComPtr<IMFAttributes> attributes;
51 if (!PrepareVideoCaptureAttributes(attributes.Receive(), 1))
52 return false;
53
54 return SUCCEEDED(MFEnumDeviceSources(attributes, devices, count));
55 }
56
57 bool CreateVideoCaptureDevice(const char* sym_link, IMFMediaSource** source) {
58 ScopedComPtr<IMFAttributes> attributes;
59 if (!PrepareVideoCaptureAttributes(attributes.Receive(), 2))
60 return false;
61
62 attributes->SetString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,
63 base::SysUTF8ToWide(sym_link).c_str());
64
65 return SUCCEEDED(MFCreateDeviceSource(attributes, source));
66 }
67
68 bool FormatFromGuid(const GUID& guid, VideoCaptureCapability::Format* format) {
69 struct {
70 const GUID& guid;
71 const VideoCaptureCapability::Format format;
72 } static const kFormatMap[] = {
73 { MFVideoFormat_I420, VideoCaptureCapability::kI420 },
74 { MFVideoFormat_YUY2, VideoCaptureCapability::kYUY2 },
75 { MFVideoFormat_UYVY, VideoCaptureCapability::kUYVY },
76 { MFVideoFormat_RGB24, VideoCaptureCapability::kRGB24 },
77 { MFVideoFormat_ARGB32, VideoCaptureCapability::kARGB },
78 { MFVideoFormat_MJPG, VideoCaptureCapability::kMJPEG },
79 { MFVideoFormat_YV12, VideoCaptureCapability::kYV12 },
80 };
81
82 for (int i = 0; i < arraysize(kFormatMap); ++i) {
83 if (kFormatMap[i].guid == guid) {
84 *format = kFormatMap[i].format;
85 return true;
86 }
87 }
88
89 return false;
90 }
91
92 bool GetFrameSize(IMFMediaType* type, int* width, int* height) {
93 UINT32 width32, height32;
94 if (FAILED(MFGetAttributeSize(type, MF_MT_FRAME_SIZE, &width32, &height32)))
95 return false;
96 *width = width32;
97 *height = height32;
98 return true;
99 }
100
101 bool GetFrameRate(IMFMediaType* type, int* frame_rate) {
102 UINT32 numerator, denominator;
103 if (FAILED(MFGetAttributeRatio(type, MF_MT_FRAME_RATE, &numerator,
104 &denominator))) {
105 return false;
106 }
107 *frame_rate = numerator / denominator;
108 return true;
109 }
110
111 bool FillCapabilitiesFromType(IMFMediaType* type,
112 VideoCaptureCapability* capability) {
113 GUID type_guid;
114 if (FAILED(type->GetGUID(MF_MT_SUBTYPE, &type_guid)) ||
115 !FormatFromGuid(type_guid, &capability->color) ||
116 !GetFrameSize(type, &capability->width, &capability->height) ||
117 !GetFrameRate(type, &capability->frame_rate)) {
118 return false;
119 }
120
121 capability->expected_capture_delay = 0; // Currently not used.
122 capability->interlaced = false; // Currently not used.
123
124 return true;
125 }
126
127 HRESULT FillCapabilities(IMFSourceReader* source,
128 CapabilityList* capabilities) {
129 DWORD stream_index = 0;
130 ScopedComPtr<IMFMediaType> type;
131 HRESULT hr;
132 while (SUCCEEDED(hr = source->GetNativeMediaType(
133 MF_SOURCE_READER_FIRST_VIDEO_STREAM, stream_index, type.Receive()))) {
134 VideoCaptureCapabilityWin capability(stream_index++);
135 if (FillCapabilitiesFromType(type, &capability))
136 capabilities->Add(capability);
137 type.Release();
138 }
139
140 if (SUCCEEDED(hr) && capabilities->empty())
141 hr = HRESULT_FROM_WIN32(ERROR_EMPTY);
142
143 return (hr == MF_E_NO_MORE_TYPES) ? S_OK : hr;
144 }
145
146 } // namespace
147
148 namespace media {
149
150 class MFReaderCallback
151 : public base::RefCountedThreadSafe<MFReaderCallback>,
152 public IMFSourceReaderCallback {
153 public:
154 MFReaderCallback(VideoCaptureDeviceMFWin* observer)
155 : observer_(observer), wait_event_(NULL) {
156 }
157
158 void SetSignalOnFlush(base::WaitableEvent* event) {
159 wait_event_ = event;
160 }
161
162 STDMETHOD(QueryInterface)(REFIID riid, void** object) {
163 if (riid != IID_IUnknown && riid != IID_IMFSourceReaderCallback)
164 return E_NOINTERFACE;
165 *object = static_cast<IMFSourceReaderCallback*>(this);
166 AddRef();
167 return S_OK;
168 }
169
170 STDMETHOD_(ULONG, AddRef)() {
171 base::RefCountedThreadSafe<MFReaderCallback>::AddRef();
172 return 1U;
173 }
174
175 STDMETHOD_(ULONG, Release)() {
176 base::RefCountedThreadSafe<MFReaderCallback>::Release();
177 return 1U;
178 }
179
180 STDMETHOD(OnReadSample)(HRESULT status, DWORD stream_index,
181 DWORD stream_flags, LONGLONG time_stamp, IMFSample* sample) {
182 base::Time stamp(base::Time::Now());
183 if (!sample) {
184 observer_->OnIncomingCapturedFrame(NULL, 0, stamp);
185 return S_OK;
186 }
187
188 DWORD count = 0;
189 sample->GetBufferCount(&count);
190
191 for (DWORD i = 0; i < count; ++i) {
192 ScopedComPtr<IMFMediaBuffer> buffer;
193 sample->GetBufferByIndex(i, buffer.Receive());
194 if (buffer) {
195 DWORD length = 0, max_length = 0;
196 BYTE* data = NULL;
197 buffer->Lock(&data, &max_length, &length);
198 observer_->OnIncomingCapturedFrame(data, length, stamp);
darin (slow to review) 2012/11/29 00:28:05 is it possible for the observer_ to destroy |this|
tommi (sloooow) - chröme 2012/11/29 11:02:58 This particular OnIncomingCapturedFrame is basical
199 buffer->Unlock();
200 }
201 }
202 return S_OK;
203 }
204
205 STDMETHOD(OnFlush)(DWORD stream_index) {
206 if (wait_event_) {
207 wait_event_->Signal();
208 wait_event_ = NULL;
209 }
210 return S_OK;
211 }
212
213 STDMETHOD(OnEvent)(DWORD stream_index, IMFMediaEvent* event) {
214 NOTIMPLEMENTED();
215 return S_OK;
216 }
217
218 private:
219 friend class base::RefCountedThreadSafe<MFReaderCallback>;
220 ~MFReaderCallback() {}
221
222 VideoCaptureDeviceMFWin* observer_;
223 base::WaitableEvent* wait_event_;
224 };
225
226 // static
227 void VideoCaptureDeviceMFWin::GetDeviceNames(Names* device_names) {
228 ScopedCoMem<IMFActivate*> devices;
229 UINT32 count;
230 if (!EnumerateVideoDevices(&devices, &count))
231 return;
232
233 HRESULT hr;
234 for (UINT32 i = 0; i < count; ++i) {
235 UINT32 name_size, id_size;
236 ScopedCoMem<wchar_t> name, id;
237 if (SUCCEEDED(hr = devices[i]->GetAllocatedString(
238 MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &name, &name_size)) &&
239 SUCCEEDED(hr = devices[i]->GetAllocatedString(
240 MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, &id,
241 &id_size))) {
242 std::wstring name_w(name, name_size), id_w(id, id_size);
243 Name device;
244 device.device_name = base::SysWideToUTF8(name_w);
245 device.unique_id = base::SysWideToUTF8(id_w);
246 device_names->push_back(device);
247 } else {
248 DLOG(WARNING) << "GetAllocatedString failed: " << std::hex << hr;
249 }
250 devices[i]->Release();
251 }
252 }
253
254 VideoCaptureDeviceMFWin::VideoCaptureDeviceMFWin(const Name& device_name)
255 : name_(device_name), observer_(NULL), capture_(0) {
256 DetachFromThread();
257 }
258
259 VideoCaptureDeviceMFWin::~VideoCaptureDeviceMFWin() {
260 DCHECK(CalledOnValidThread());
261 }
262
263 bool VideoCaptureDeviceMFWin::Init() {
264 DCHECK(CalledOnValidThread());
265 DCHECK(!reader_);
266
267 ScopedComPtr<IMFMediaSource> source;
268 if (!CreateVideoCaptureDevice(name_.unique_id.c_str(), source.Receive()))
269 return false;
270
271 ScopedComPtr<IMFAttributes> attributes;
272 MFCreateAttributes(attributes.Receive(), 1);
273 DCHECK(attributes);
274
275 callback_ = new MFReaderCallback(this);
276 attributes->SetUnknown(MF_SOURCE_READER_ASYNC_CALLBACK, callback_.get());
277
278 return SUCCEEDED(MFCreateSourceReaderFromMediaSource(source, attributes,
279 reader_.Receive()));
280 }
281
282 void VideoCaptureDeviceMFWin::Allocate(
283 int width,
284 int height,
285 int frame_rate,
286 VideoCaptureDevice::EventHandler* observer) {
287 DCHECK(CalledOnValidThread());
288
289 base::AutoLock lock(lock_);
290
291 if (observer_) {
292 DCHECK_EQ(observer, observer_);
293 return;
294 }
295
296 observer_ = observer;
297 DCHECK_EQ(capture_, false);
298
299 CapabilityList capabilities;
300 HRESULT hr = S_OK;
301 if (!reader_ || FAILED(hr = FillCapabilities(reader_, &capabilities))) {
302 OnError(hr);
303 return;
304 }
305
306 const VideoCaptureCapabilityWin& found_capability =
307 capabilities.GetBestMatchedCapability(width, height, frame_rate);
308
309 ScopedComPtr<IMFMediaType> type;
310 if (FAILED(hr = reader_->GetNativeMediaType(
311 MF_SOURCE_READER_FIRST_VIDEO_STREAM, found_capability.stream_index,
312 type.Receive())) ||
313 FAILED(hr = reader_->SetCurrentMediaType(
314 MF_SOURCE_READER_FIRST_VIDEO_STREAM, NULL, type))) {
315 OnError(hr);
316 return;
317 }
318
319 observer_->OnFrameInfo(found_capability);
320 }
321
322 void VideoCaptureDeviceMFWin::Start() {
323 DCHECK(CalledOnValidThread());
324
325 base::AutoLock lock(lock_);
326 if (!capture_) {
327 capture_ = true;
328 HRESULT hr;
329 if (FAILED(hr = reader_->ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0,
330 NULL, NULL, NULL, NULL))) {
331 OnError(hr);
332 capture_ = false;
333 }
334 }
335 }
336
337 void VideoCaptureDeviceMFWin::Stop() {
338 DCHECK(CalledOnValidThread());
339 base::WaitableEvent flushed(false, false);
340 bool wait = false;
341 {
342 base::AutoLock lock(lock_);
343 if (capture_) {
344 capture_ = false;
345 callback_->SetSignalOnFlush(&flushed);
346 HRESULT hr = reader_->Flush(MF_SOURCE_READER_ALL_STREAMS);
347 wait = SUCCEEDED(hr);
348 if (!wait) {
349 callback_->SetSignalOnFlush(NULL);
350 OnError(hr);
351 }
352 }
353 }
354
355 if (wait)
356 flushed.Wait();
357 }
358
359 void VideoCaptureDeviceMFWin::DeAllocate() {
360 DCHECK(CalledOnValidThread());
361
362 Stop();
363
364 base::AutoLock lock(lock_);
365 observer_ = NULL;
366 }
367
368 const VideoCaptureDevice::Name& VideoCaptureDeviceMFWin::device_name() {
369 DCHECK(CalledOnValidThread());
370 return name_;
371 }
372
373 void VideoCaptureDeviceMFWin::OnIncomingCapturedFrame(
374 const uint8* data,
375 int length,
376 const base::Time& time_stamp) {
377 base::AutoLock lock(lock_);
378 if (data && observer_)
379 observer_->OnIncomingCapturedFrame(data, length, time_stamp);
380
381 if (capture_) {
382 HRESULT hr = reader_->ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0,
383 NULL, NULL, NULL, NULL);
384 if (FAILED(hr)) {
385 // If running the *VideoCap* unit tests on repeat, this can sometimes
386 // fail with HRESULT_FROM_WINHRESULT_FROM_WIN32(ERROR_INVALID_FUNCTION).
387 // It's not clear to me why this is, but it is possible that it has
388 // something to do with this bug:
389 // http://support.microsoft.com/kb/979567
390 OnError(hr);
391 }
392 }
393 }
394
395 void VideoCaptureDeviceMFWin::OnError(HRESULT hr) {
396 DLOG(ERROR) << "VideoCaptureDeviceMFWin: " << std::hex << hr;
397 if (observer_)
398 observer_->OnError();
399 }
400
401 } // namespace media
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698