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

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

Powered by Google App Engine
This is Rietveld 408576698