PageRenderTime 34ms CodeModel.GetById 35ms RepoModel.GetById 13ms app.codeStats 0ms

/chromium/third_party/libjingle/source/talk/media/devices/win32devicemanager.cc

https://gitlab.com/f3822/qtwebengine-chromium
C++ | 404 lines | 315 code | 48 blank | 41 comment | 60 complexity | 9875afc35211d96e8596953943c7436f MD5 | raw file
  1. /*
  2. * libjingle
  3. * Copyright 2004 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. #include "talk/media/devices/win32devicemanager.h"
  28. #include <atlbase.h>
  29. #include <dbt.h>
  30. #include <strmif.h> // must come before ks.h
  31. #include <ks.h>
  32. #include <ksmedia.h>
  33. #define INITGUID // For PKEY_AudioEndpoint_GUID
  34. #include <mmdeviceapi.h>
  35. #include <mmsystem.h>
  36. #include <functiondiscoverykeys_devpkey.h>
  37. #include <uuids.h>
  38. #include "talk/base/logging.h"
  39. #include "talk/base/stringutils.h"
  40. #include "talk/base/thread.h"
  41. #include "talk/base/win32.h" // ToUtf8
  42. #include "talk/base/win32window.h"
  43. #include "talk/media/base/mediacommon.h"
  44. #ifdef HAVE_LOGITECH_HEADERS
  45. #include "third_party/logitech/files/logitechquickcam.h"
  46. #endif
  47. namespace cricket {
  48. DeviceManagerInterface* DeviceManagerFactory::Create() {
  49. return new Win32DeviceManager();
  50. }
  51. class Win32DeviceWatcher
  52. : public DeviceWatcher,
  53. public talk_base::Win32Window {
  54. public:
  55. explicit Win32DeviceWatcher(Win32DeviceManager* dm);
  56. virtual ~Win32DeviceWatcher();
  57. virtual bool Start();
  58. virtual void Stop();
  59. private:
  60. HDEVNOTIFY Register(REFGUID guid);
  61. void Unregister(HDEVNOTIFY notify);
  62. virtual bool OnMessage(UINT msg, WPARAM wp, LPARAM lp, LRESULT& result);
  63. Win32DeviceManager* manager_;
  64. HDEVNOTIFY audio_notify_;
  65. HDEVNOTIFY video_notify_;
  66. };
  67. static const char* kFilteredAudioDevicesName[] = {
  68. NULL,
  69. };
  70. static const char* const kFilteredVideoDevicesName[] = {
  71. "Asus virtual Camera", // Bad Asus desktop virtual cam
  72. "Bluetooth Video", // Bad Sony viao bluetooth sharing driver
  73. NULL,
  74. };
  75. static const wchar_t kFriendlyName[] = L"FriendlyName";
  76. static const wchar_t kDevicePath[] = L"DevicePath";
  77. static const char kUsbDevicePathPrefix[] = "\\\\?\\usb";
  78. static bool GetDevices(const CLSID& catid, std::vector<Device>* out);
  79. static bool GetCoreAudioDevices(bool input, std::vector<Device>* devs);
  80. static bool GetWaveDevices(bool input, std::vector<Device>* devs);
  81. Win32DeviceManager::Win32DeviceManager()
  82. : need_couninitialize_(false) {
  83. set_watcher(new Win32DeviceWatcher(this));
  84. }
  85. Win32DeviceManager::~Win32DeviceManager() {
  86. if (initialized()) {
  87. Terminate();
  88. }
  89. }
  90. bool Win32DeviceManager::Init() {
  91. if (!initialized()) {
  92. HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
  93. need_couninitialize_ = SUCCEEDED(hr);
  94. if (FAILED(hr)) {
  95. LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
  96. if (hr != RPC_E_CHANGED_MODE) {
  97. return false;
  98. }
  99. }
  100. if (!watcher()->Start()) {
  101. return false;
  102. }
  103. set_initialized(true);
  104. }
  105. return true;
  106. }
  107. void Win32DeviceManager::Terminate() {
  108. if (initialized()) {
  109. watcher()->Stop();
  110. if (need_couninitialize_) {
  111. CoUninitialize();
  112. need_couninitialize_ = false;
  113. }
  114. set_initialized(false);
  115. }
  116. }
  117. bool Win32DeviceManager::GetDefaultVideoCaptureDevice(Device* device) {
  118. bool ret = false;
  119. // If there are multiple capture devices, we want the first USB one.
  120. // This avoids issues with defaulting to virtual cameras or grabber cards.
  121. std::vector<Device> devices;
  122. ret = (GetVideoCaptureDevices(&devices) && !devices.empty());
  123. if (ret) {
  124. *device = devices[0];
  125. for (size_t i = 0; i < devices.size(); ++i) {
  126. if (strnicmp(devices[i].id.c_str(), kUsbDevicePathPrefix,
  127. ARRAY_SIZE(kUsbDevicePathPrefix) - 1) == 0) {
  128. *device = devices[i];
  129. break;
  130. }
  131. }
  132. }
  133. return ret;
  134. }
  135. bool Win32DeviceManager::GetAudioDevices(bool input,
  136. std::vector<Device>* devs) {
  137. devs->clear();
  138. if (talk_base::IsWindowsVistaOrLater()) {
  139. if (!GetCoreAudioDevices(input, devs))
  140. return false;
  141. } else {
  142. if (!GetWaveDevices(input, devs))
  143. return false;
  144. }
  145. return FilterDevices(devs, kFilteredAudioDevicesName);
  146. }
  147. bool Win32DeviceManager::GetVideoCaptureDevices(std::vector<Device>* devices) {
  148. devices->clear();
  149. if (!GetDevices(CLSID_VideoInputDeviceCategory, devices)) {
  150. return false;
  151. }
  152. return FilterDevices(devices, kFilteredVideoDevicesName);
  153. }
  154. bool GetDevices(const CLSID& catid, std::vector<Device>* devices) {
  155. HRESULT hr;
  156. // CComPtr is a scoped pointer that will be auto released when going
  157. // out of scope. CoUninitialize must not be called before the
  158. // release.
  159. CComPtr<ICreateDevEnum> sys_dev_enum;
  160. CComPtr<IEnumMoniker> cam_enum;
  161. if (FAILED(hr = sys_dev_enum.CoCreateInstance(CLSID_SystemDeviceEnum)) ||
  162. FAILED(hr = sys_dev_enum->CreateClassEnumerator(catid, &cam_enum, 0))) {
  163. LOG(LS_ERROR) << "Failed to create device enumerator, hr=" << hr;
  164. return false;
  165. }
  166. // Only enum devices if CreateClassEnumerator returns S_OK. If there are no
  167. // devices available, S_FALSE will be returned, but enumMk will be NULL.
  168. if (hr == S_OK) {
  169. CComPtr<IMoniker> mk;
  170. while (cam_enum->Next(1, &mk, NULL) == S_OK) {
  171. #ifdef HAVE_LOGITECH_HEADERS
  172. // Initialize Logitech device if applicable
  173. MaybeLogitechDeviceReset(mk);
  174. #endif
  175. CComPtr<IPropertyBag> bag;
  176. if (SUCCEEDED(mk->BindToStorage(NULL, NULL,
  177. __uuidof(bag), reinterpret_cast<void**>(&bag)))) {
  178. CComVariant name, path;
  179. std::string name_str, path_str;
  180. if (SUCCEEDED(bag->Read(kFriendlyName, &name, 0)) &&
  181. name.vt == VT_BSTR) {
  182. name_str = talk_base::ToUtf8(name.bstrVal);
  183. // Get the device id if one exists.
  184. if (SUCCEEDED(bag->Read(kDevicePath, &path, 0)) &&
  185. path.vt == VT_BSTR) {
  186. path_str = talk_base::ToUtf8(path.bstrVal);
  187. }
  188. devices->push_back(Device(name_str, path_str));
  189. }
  190. }
  191. mk = NULL;
  192. }
  193. }
  194. return true;
  195. }
  196. HRESULT GetStringProp(IPropertyStore* bag, PROPERTYKEY key, std::string* out) {
  197. out->clear();
  198. PROPVARIANT var;
  199. PropVariantInit(&var);
  200. HRESULT hr = bag->GetValue(key, &var);
  201. if (SUCCEEDED(hr)) {
  202. if (var.pwszVal)
  203. *out = talk_base::ToUtf8(var.pwszVal);
  204. else
  205. hr = E_FAIL;
  206. }
  207. PropVariantClear(&var);
  208. return hr;
  209. }
  210. // Adapted from http://msdn.microsoft.com/en-us/library/dd370812(v=VS.85).aspx
  211. HRESULT CricketDeviceFromImmDevice(IMMDevice* device, Device* out) {
  212. CComPtr<IPropertyStore> props;
  213. HRESULT hr = device->OpenPropertyStore(STGM_READ, &props);
  214. if (FAILED(hr)) {
  215. return hr;
  216. }
  217. // Get the endpoint's name and id.
  218. std::string name, guid;
  219. hr = GetStringProp(props, PKEY_Device_FriendlyName, &name);
  220. if (SUCCEEDED(hr)) {
  221. hr = GetStringProp(props, PKEY_AudioEndpoint_GUID, &guid);
  222. if (SUCCEEDED(hr)) {
  223. out->name = name;
  224. out->id = guid;
  225. }
  226. }
  227. return hr;
  228. }
  229. bool GetCoreAudioDevices(
  230. bool input, std::vector<Device>* devs) {
  231. HRESULT hr = S_OK;
  232. CComPtr<IMMDeviceEnumerator> enumerator;
  233. hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL,
  234. __uuidof(IMMDeviceEnumerator), reinterpret_cast<void**>(&enumerator));
  235. if (SUCCEEDED(hr)) {
  236. CComPtr<IMMDeviceCollection> devices;
  237. hr = enumerator->EnumAudioEndpoints((input ? eCapture : eRender),
  238. DEVICE_STATE_ACTIVE, &devices);
  239. if (SUCCEEDED(hr)) {
  240. unsigned int count;
  241. hr = devices->GetCount(&count);
  242. if (SUCCEEDED(hr)) {
  243. for (unsigned int i = 0; i < count; i++) {
  244. CComPtr<IMMDevice> device;
  245. // Get pointer to endpoint number i.
  246. hr = devices->Item(i, &device);
  247. if (FAILED(hr)) {
  248. break;
  249. }
  250. Device dev;
  251. hr = CricketDeviceFromImmDevice(device, &dev);
  252. if (SUCCEEDED(hr)) {
  253. devs->push_back(dev);
  254. } else {
  255. LOG(LS_WARNING) << "Unable to query IMM Device, skipping. HR="
  256. << hr;
  257. hr = S_FALSE;
  258. }
  259. }
  260. }
  261. }
  262. }
  263. if (FAILED(hr)) {
  264. LOG(LS_WARNING) << "GetCoreAudioDevices failed with hr " << hr;
  265. return false;
  266. }
  267. return true;
  268. }
  269. bool GetWaveDevices(bool input, std::vector<Device>* devs) {
  270. // Note, we don't use the System Device Enumerator interface here since it
  271. // adds lots of pseudo-devices to the list, such as DirectSound and Wave
  272. // variants of the same device.
  273. if (input) {
  274. int num_devs = waveInGetNumDevs();
  275. for (int i = 0; i < num_devs; ++i) {
  276. WAVEINCAPS caps;
  277. if (waveInGetDevCaps(i, &caps, sizeof(caps)) == MMSYSERR_NOERROR &&
  278. caps.wChannels > 0) {
  279. devs->push_back(Device(talk_base::ToUtf8(caps.szPname),
  280. talk_base::ToString(i)));
  281. }
  282. }
  283. } else {
  284. int num_devs = waveOutGetNumDevs();
  285. for (int i = 0; i < num_devs; ++i) {
  286. WAVEOUTCAPS caps;
  287. if (waveOutGetDevCaps(i, &caps, sizeof(caps)) == MMSYSERR_NOERROR &&
  288. caps.wChannels > 0) {
  289. devs->push_back(Device(talk_base::ToUtf8(caps.szPname), i));
  290. }
  291. }
  292. }
  293. return true;
  294. }
  295. Win32DeviceWatcher::Win32DeviceWatcher(Win32DeviceManager* manager)
  296. : DeviceWatcher(manager),
  297. manager_(manager),
  298. audio_notify_(NULL),
  299. video_notify_(NULL) {
  300. }
  301. Win32DeviceWatcher::~Win32DeviceWatcher() {
  302. }
  303. bool Win32DeviceWatcher::Start() {
  304. if (!Create(NULL, _T("libjingle Win32DeviceWatcher Window"),
  305. 0, 0, 0, 0, 0, 0)) {
  306. return false;
  307. }
  308. audio_notify_ = Register(KSCATEGORY_AUDIO);
  309. if (!audio_notify_) {
  310. Stop();
  311. return false;
  312. }
  313. video_notify_ = Register(KSCATEGORY_VIDEO);
  314. if (!video_notify_) {
  315. Stop();
  316. return false;
  317. }
  318. return true;
  319. }
  320. void Win32DeviceWatcher::Stop() {
  321. UnregisterDeviceNotification(video_notify_);
  322. video_notify_ = NULL;
  323. UnregisterDeviceNotification(audio_notify_);
  324. audio_notify_ = NULL;
  325. Destroy();
  326. }
  327. HDEVNOTIFY Win32DeviceWatcher::Register(REFGUID guid) {
  328. DEV_BROADCAST_DEVICEINTERFACE dbdi;
  329. dbdi.dbcc_size = sizeof(dbdi);
  330. dbdi.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
  331. dbdi.dbcc_classguid = guid;
  332. dbdi.dbcc_name[0] = '\0';
  333. return RegisterDeviceNotification(handle(), &dbdi,
  334. DEVICE_NOTIFY_WINDOW_HANDLE);
  335. }
  336. void Win32DeviceWatcher::Unregister(HDEVNOTIFY handle) {
  337. UnregisterDeviceNotification(handle);
  338. }
  339. bool Win32DeviceWatcher::OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam,
  340. LRESULT& result) {
  341. if (uMsg == WM_DEVICECHANGE) {
  342. if (wParam == DBT_DEVICEARRIVAL ||
  343. wParam == DBT_DEVICEREMOVECOMPLETE) {
  344. DEV_BROADCAST_DEVICEINTERFACE* dbdi =
  345. reinterpret_cast<DEV_BROADCAST_DEVICEINTERFACE*>(lParam);
  346. if (dbdi->dbcc_classguid == KSCATEGORY_AUDIO ||
  347. dbdi->dbcc_classguid == KSCATEGORY_VIDEO) {
  348. manager_->SignalDevicesChange();
  349. }
  350. }
  351. result = 0;
  352. return true;
  353. }
  354. return false;
  355. }
  356. }; // namespace cricket