1 /*****************************************************************************
2 * mmdevice.c : Windows Multimedia Device API audio output plugin for VLC
3 *****************************************************************************
4 * Copyright (C) 2012 RĂ©mi Denis-Courmont
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19 *****************************************************************************/
26 #define _WIN32_WINNT 0x600 /* Windows Vista */
33 #include <audiopolicy.h>
34 #include <mmdeviceapi.h>
36 DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd,
37 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14);
39 #include <vlc_common.h>
40 #include <vlc_plugin.h>
42 #include <vlc_charset.h>
45 DEFINE_GUID (GUID_VLC_AUD_OUT, 0x4533f59d, 0x59ee, 0x00c6,
46 0xad, 0xb2, 0xc6, 0x8b, 0x50, 0x1a, 0x66, 0x55);
48 static int TryEnterMTA(vlc_object_t *obj)
50 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
51 if (unlikely(FAILED(hr)))
53 msg_Err (obj, "cannot initialize COM (error 0x%lx)", hr);
58 #define TryEnterMTA(o) TryEnterMTA(VLC_OBJECT(o))
60 static void EnterMTA(void)
62 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
63 if (unlikely(FAILED(hr)))
67 static void LeaveMTA(void)
75 aout_stream_t *stream; /**< Underlying audio output stream */
77 IMMDeviceEnumerator *it; /**< Device enumerator, NULL when exiting */
78 /*TODO: IMMNotificationClient*/
80 IMMDevice *dev; /**< Selected output device, NULL if none */
81 IAudioSessionManager *manager; /**< Session for the output device */
82 struct IAudioSessionEvents session_events;
83 ISimpleAudioVolume *volume; /**< Volume setter */
86 HANDLE device_changed; /**< Event to reset thread */
87 HANDLE device_ready; /**< Event when thread is reset */
88 vlc_thread_t thread; /**< Thread for audio session control */
91 /* NOTE: The Core Audio API documentation totally fails to specify the thread
92 * safety (or lack thereof) of the interfaces. This code takes the most
93 * restrictive assumption, no thread safety: The background thread (MMThread)
94 * only runs at specified times, namely between the device_ready and
95 * device_changed events (effectively, a thread barrier but only Windows 8
96 * provides thread barriers natively).
98 * The audio output owner (i.e. the audio output core) is responsible for
99 * serializing callbacks. This code only needs to be concerned with
100 * synchronization between the set of audio output callbacks, MMThread()
101 * and (trivially) the device and session notifications. */
103 static int vlc_FromHR(audio_output_t *aout, HRESULT hr)
105 /* Restart on unplug */
106 if (unlikely(hr == AUDCLNT_E_DEVICE_INVALIDATED))
109 aout_ChannelsRestart(VLC_OBJECT(aout), "audio-device", d, d, NULL);
111 return SUCCEEDED(hr) ? 0 : -1;
114 /*** VLC audio output callbacks ***/
115 static int TimeGet(audio_output_t *aout, mtime_t *restrict delay)
117 aout_sys_t *sys = aout->sys;
121 hr = aout_stream_TimeGet(sys->stream, delay);
124 return SUCCEEDED(hr) ? 0 : -1;
127 static void Play(audio_output_t *aout, block_t *block)
129 aout_sys_t *sys = aout->sys;
133 hr = aout_stream_Play(sys->stream, block);
136 vlc_FromHR(aout, hr);
139 static void Pause(audio_output_t *aout, bool paused, mtime_t date)
141 aout_sys_t *sys = aout->sys;
145 hr = aout_stream_Pause(sys->stream, paused);
148 vlc_FromHR(aout, hr);
152 static void Flush(audio_output_t *aout, bool wait)
154 aout_sys_t *sys = aout->sys;
159 { /* Loosy drain emulation */
162 if (SUCCEEDED(aout_stream_TimeGet(sys->stream, &delay)))
163 Sleep((delay / (CLOCK_FREQ / 1000)) + 1);
166 aout_stream_Flush(sys->stream);
172 static int VolumeSet(audio_output_t *aout, float vol)
174 ISimpleAudioVolume *volume = aout->sys->volume;
178 if (TryEnterMTA(aout))
181 HRESULT hr = ISimpleAudioVolume_SetMasterVolume(volume, vol, NULL);
183 msg_Err(aout, "cannot set volume (error 0x%lx)", hr);
186 return FAILED(hr) ? -1 : 0;
189 static int MuteSet(audio_output_t *aout, bool mute)
191 ISimpleAudioVolume *volume = aout->sys->volume;
195 if (TryEnterMTA(aout))
198 HRESULT hr = ISimpleAudioVolume_SetMute(volume, mute ? TRUE : FALSE, NULL);
200 msg_Err(aout, "cannot set volume (error 0x%lx)", hr);
203 return FAILED(hr) ? -1 : 0;
206 /*** Audio session events ***/
207 static inline aout_sys_t *vlc_AudioSessionEvents_sys(IAudioSessionEvents *this)
209 return (void *)(((char *)this) - offsetof(aout_sys_t, session_events));
213 vlc_AudioSessionEvents_QueryInterface(IAudioSessionEvents *this, REFIID riid,
216 if (IsEqualIID(riid, &IID_IUnknown)
217 || IsEqualIID(riid, &IID_IAudioSessionEvents))
220 IUnknown_AddRef(this);
226 return E_NOINTERFACE;
230 static STDMETHODIMP_(ULONG)
231 vlc_AudioSessionEvents_AddRef(IAudioSessionEvents *this)
233 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
234 return InterlockedIncrement(&sys->refs);
237 static STDMETHODIMP_(ULONG)
238 vlc_AudioSessionEvents_Release(IAudioSessionEvents *this)
240 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
241 return InterlockedDecrement(&sys->refs);
245 vlc_AudioSessionEvents_OnDisplayNameChanged(IAudioSessionEvents *this,
246 LPCWSTR wname, LPCGUID ctx)
248 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
249 audio_output_t *aout = sys->aout;
251 msg_Dbg(aout, "display name changed: %ls", wname);
257 vlc_AudioSessionEvents_OnIconPathChanged(IAudioSessionEvents *this,
258 LPCWSTR wpath, LPCGUID ctx)
260 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
261 audio_output_t *aout = sys->aout;
263 msg_Dbg(aout, "icon path changed: %ls", wpath);
269 vlc_AudioSessionEvents_OnSimpleVolumeChanged(IAudioSessionEvents *this,
270 float vol, WINBOOL mute,
273 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
274 audio_output_t *aout = sys->aout;
276 msg_Dbg(aout, "simple volume changed: %f, muting %sabled", vol,
277 mute ? "en" : "dis");
278 aout_VolumeReport(aout, vol);
279 aout_MuteReport(aout, mute == TRUE);
285 vlc_AudioSessionEvents_OnChannelVolumeChanged(IAudioSessionEvents *this,
286 DWORD count, float *vols,
287 DWORD changed, LPCGUID ctx)
289 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
290 audio_output_t *aout = sys->aout;
292 msg_Dbg(aout, "channel volume %lu of %lu changed: %f", changed, count,
299 vlc_AudioSessionEvents_OnGroupingParamChanged(IAudioSessionEvents *this,
300 LPCGUID param, LPCGUID ctx)
303 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
304 audio_output_t *aout = sys->aout;
306 msg_Dbg(aout, "grouping parameter changed");
313 vlc_AudioSessionEvents_OnStateChanged(IAudioSessionEvents *this,
314 AudioSessionState state)
316 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
317 audio_output_t *aout = sys->aout;
319 msg_Dbg(aout, "state changed: %d", state);
324 vlc_AudioSessionEvents_OnSessionDisconnected(IAudioSessionEvents *this,
325 AudioSessionDisconnectReason reason)
327 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
328 audio_output_t *aout = sys->aout;
332 case DisconnectReasonDeviceRemoval:
333 msg_Warn(aout, "session disconnected: %s", "device removed");
335 case DisconnectReasonServerShutdown:
336 msg_Err(aout, "session disconnected: %s", "service stopped");
338 case DisconnectReasonFormatChanged:
339 msg_Warn(aout, "session disconnected: %s", "format changed");
341 case DisconnectReasonSessionLogoff:
342 msg_Err(aout, "session disconnected: %s", "user logged off");
344 case DisconnectReasonSessionDisconnected:
345 msg_Err(aout, "session disconnected: %s", "session disconnected");
347 case DisconnectReasonExclusiveModeOverride:
348 msg_Err(aout, "session disconnected: %s", "stream overriden");
351 msg_Warn(aout, "session disconnected: unknown reason %d", reason);
354 /* NOTE: audio decoder thread should get invalidated device and restart */
358 static const struct IAudioSessionEventsVtbl vlc_AudioSessionEvents =
360 vlc_AudioSessionEvents_QueryInterface,
361 vlc_AudioSessionEvents_AddRef,
362 vlc_AudioSessionEvents_Release,
364 vlc_AudioSessionEvents_OnDisplayNameChanged,
365 vlc_AudioSessionEvents_OnIconPathChanged,
366 vlc_AudioSessionEvents_OnSimpleVolumeChanged,
367 vlc_AudioSessionEvents_OnChannelVolumeChanged,
368 vlc_AudioSessionEvents_OnGroupingParamChanged,
369 vlc_AudioSessionEvents_OnStateChanged,
370 vlc_AudioSessionEvents_OnSessionDisconnected,
374 /*** Initialization / deinitialization **/
375 static wchar_t *var_InheritWide(vlc_object_t *obj, const char *name)
377 char *v8 = var_InheritString(obj, name);
381 wchar_t *v16 = ToWide(v8);
385 #define var_InheritWide(o,n) var_InheritWide(VLC_OBJECT(o),n)
387 static void MMSession(audio_output_t *aout, aout_sys_t *sys)
389 IAudioSessionControl *control;
392 /* Register session control */
393 if (sys->manager != NULL)
395 hr = IAudioSessionManager_GetSimpleAudioVolume(sys->manager,
397 FALSE, &sys->volume);
399 msg_Err(aout, "cannot get simple volume (error 0x%lx)", hr);
401 hr = IAudioSessionManager_GetAudioSessionControl(sys->manager,
402 &GUID_VLC_AUD_OUT, 0,
405 msg_Err(aout, "cannot get session control (error 0x%lx)", hr);
415 wchar_t *ua = var_InheritWide(aout, "user-agent");
416 IAudioSessionControl_SetDisplayName(control, ua, NULL);
419 IAudioSessionControl_RegisterAudioSessionNotification(control,
420 &sys->session_events);
423 if (sys->volume != NULL)
424 { /* Get current values (_after_ changes notification registration) */
428 hr = ISimpleAudioVolume_GetMute(sys->volume, &mute);
430 msg_Err(aout, "cannot get mute (error 0x%lx)", hr);
432 aout_MuteReport(aout, mute != FALSE);
434 hr = ISimpleAudioVolume_GetMasterVolume(sys->volume, &level);
436 msg_Err(aout, "cannot get mute (error 0x%lx)", hr);
438 aout_VolumeReport(aout, level);
441 SetEvent(sys->device_ready);
442 /* Wait until device change or exit */
443 WaitForSingleObject(sys->device_changed, INFINITE);
445 /* Deregister session control */
448 IAudioSessionControl_UnregisterAudioSessionNotification(control,
449 &sys->session_events);
450 IAudioSessionControl_Release(control);
453 if (sys->volume != NULL)
454 ISimpleAudioVolume_Release(sys->volume);
457 /** MMDevice audio output thread.
458 * This thread takes cares of the audio session control. Inconveniently enough,
459 * the audio session control interface must:
460 * - be created and destroyed from the same thread, and
461 * - survive across VLC audio output calls.
462 * The only way to reconcile both requirements is a custom thread.
463 * The thread also ensure that the COM Multi-Thread Apartment is continuously
464 * referenced so that MMDevice objects are not destroyed early.
466 static void *MMThread(void *data)
468 audio_output_t *aout = data;
469 aout_sys_t *sys = aout->sys;
472 while (sys->it != NULL)
473 MMSession(aout, sys);
478 /*** Audio devices ***/
479 static int DevicesEnum(audio_output_t *aout, char ***idp, char ***namep)
481 aout_sys_t *sys = aout->sys;
483 IMMDeviceCollection *devs;
485 hr = IMMDeviceEnumerator_EnumAudioEndpoints(sys->it, eRender,
486 DEVICE_STATE_ACTIVE, &devs);
489 msg_Warn(aout, "cannot enumerate audio endpoints (error 0x%lx)", hr);
494 hr = IMMDeviceCollection_GetCount(devs, &count);
497 msg_Warn(aout, "cannot count audio endpoints (error 0x%lx)", hr);
501 msg_Dbg(aout, "Available Windows Audio devices:");
503 char **ids = xmalloc (count * sizeof (*ids));
504 char **names = xmalloc (count * sizeof (*names));
507 for (UINT i = 0; i < count; i++)
511 hr = IMMDeviceCollection_Item(devs, i, &dev);
515 /* Unique device ID */
517 hr = IMMDevice_GetId(dev, &devid);
520 IMMDevice_Release(dev);
523 ids[n] = FromWide(devid);
525 CoTaskMemFree(devid);
527 /* User-readable device name */
528 IPropertyStore *props;
529 hr = IMMDevice_OpenPropertyStore(dev, STGM_READ, &props);
535 hr = IPropertyStore_GetValue(props, &PKEY_Device_FriendlyName, &v);
537 names[n] = FromWide(v.pwszVal);
538 PropVariantClear(&v);
539 IPropertyStore_Release(props);
541 IMMDevice_Release(dev);
542 if (names[n] == NULL)
543 names[n] = xstrdup(ids[n]);
545 msg_Dbg(aout, "%s (%s)", ids[n], names[n]);
548 IMMDeviceCollection_Release(devs);
556 * Opens the selected audio output device.
558 static HRESULT OpenDevice(audio_output_t *aout, const char *devid)
560 aout_sys_t *sys = aout->sys;
563 assert(sys->dev == NULL);
565 if (devid != NULL) /* Device selected explicitly */
567 msg_Dbg(aout, "using selected device %s", devid);
569 wchar_t *wdevid = ToWide(devid);
570 if (likely(wdevid != NULL))
572 hr = IMMDeviceEnumerator_GetDevice(sys->it, wdevid, &sys->dev);
578 else /* Default device selected by policy */
580 msg_Dbg(aout, "using default device");
581 hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(sys->it, eRender,
582 eConsole, &sys->dev);
584 assert(sys->manager == NULL);
587 msg_Err(aout, "cannot get device (error 0x%lx)", hr);
591 /* Create session manager (for controls even w/o active audio client) */
593 hr = IMMDevice_Activate(sys->dev, &IID_IAudioSessionManager,
594 CLSCTX_ALL, NULL, &pv);
596 msg_Err(aout, "cannot activate session manager (error 0x%lx)", hr);
600 /* Report actual device */
602 hr = IMMDevice_GetId(sys->dev, &wdevid);
605 char *id = FromWide(wdevid);
606 CoTaskMemFree(wdevid);
607 if (likely(id != NULL))
609 aout_DeviceReport(aout, id);
614 SetEvent(sys->device_changed);
615 WaitForSingleObject(sys->device_ready, INFINITE);
620 * Closes the opened audio output device (if any).
622 static void CloseDevice(audio_output_t *aout)
624 aout_sys_t *sys = aout->sys;
626 assert(sys->dev != NULL);
628 if (sys->manager != NULL)
630 IAudioSessionManager_Release(sys->manager);
634 IMMDevice_Release(sys->dev);
638 static int DeviceSelect(audio_output_t *aout, const char *id)
640 aout_sys_t *sys = aout->sys;
643 if (TryEnterMTA(aout))
646 if (sys->dev != NULL)
649 hr = OpenDevice(aout, id);
650 while (hr == AUDCLNT_E_DEVICE_INVALIDATED)
651 hr = OpenDevice(aout, NULL); /* Fallback to default device */
654 if (sys->stream != NULL)
657 /* Request restart of stream with the new device */
658 aout_ChannelsRestart(VLC_OBJECT(aout), "audio-device", d, d, NULL);
660 return FAILED(hr) ? -1 : 0;
664 * Callback for aout_stream_t to create a stream on the device.
665 * This can instantiate an IAudioClient or IDirectSound(8) object.
667 static HRESULT ActivateDevice(void *opaque, REFIID iid, PROPVARIANT *actparms,
670 IMMDevice *dev = opaque;
672 return IMMDevice_Activate(dev, iid, CLSCTX_ALL, actparms, pv);
675 static int Start(audio_output_t *aout, audio_sample_format_t *restrict fmt)
677 aout_sys_t *sys = aout->sys;
680 assert (sys->stream == NULL);
681 /* Open the default device if required (to deal with restarts) */
682 if (sys->dev == NULL && FAILED(DeviceSelect(aout, NULL)))
685 aout_stream_t *s = vlc_object_create(aout, sizeof (*s));
686 if (unlikely(s == NULL))
689 s->owner.device = sys->dev;
690 s->owner.activate = ActivateDevice;
693 hr = aout_stream_Start(s, fmt, &GUID_VLC_AUD_OUT);
697 vlc_object_release(s);
700 return vlc_FromHR(aout, hr);
703 static void Stop(audio_output_t *aout)
705 aout_sys_t *sys = aout->sys;
707 assert (sys->stream != NULL);
710 aout_stream_Stop(sys->stream);
713 vlc_object_release(sys->stream);
717 static int Open(vlc_object_t *obj)
719 audio_output_t *aout = (audio_output_t *)obj;
723 if (!aout->b_force && var_InheritBool(aout, "spdif"))
724 /* Fallback to other plugin until pass-through is implemented */
727 aout_sys_t *sys = malloc(sizeof (*sys));
728 if (unlikely(sys == NULL))
737 sys->session_events.lpVtbl = &vlc_AudioSessionEvents;
740 sys->device_changed = CreateEvent(NULL, FALSE, FALSE, NULL);
741 sys->device_ready = CreateEvent(NULL, FALSE, FALSE, NULL);
742 if (unlikely(sys->device_changed == NULL || sys->device_ready == NULL))
745 /* Initialize MMDevice API */
746 if (TryEnterMTA(aout))
749 hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL,
750 &IID_IMMDeviceEnumerator, &pv);
754 msg_Dbg(aout, "cannot create device enumerator (error 0x%lx)", hr);
759 if (vlc_clone(&sys->thread, MMThread, aout, VLC_THREAD_PRIORITY_LOW))
761 WaitForSingleObject(sys->device_ready, INFINITE);
763 DeviceSelect(aout, NULL); /* Get a device to start with */
764 LeaveMTA(); /* leave MTA after thread has entered MTA */
768 aout->time_get = TimeGet;
772 aout->volume_set = VolumeSet;
773 aout->mute_set = MuteSet;
774 aout->device_enum = DevicesEnum;
775 aout->device_select = DeviceSelect;
781 IMMDeviceEnumerator_Release(sys->it);
784 if (sys->device_ready != NULL)
785 CloseHandle(sys->device_ready);
786 if (sys->device_changed != NULL)
787 CloseHandle(sys->device_changed);
792 static void Close(vlc_object_t *obj)
794 audio_output_t *aout = (audio_output_t *)obj;
795 aout_sys_t *sys = aout->sys;
797 EnterMTA(); /* enter MTA before thread leaves MTA */
798 if (sys->dev != NULL)
801 IMMDeviceEnumerator_Release(sys->it);
804 SetEvent(sys->device_changed);
805 vlc_join(sys->thread, NULL);
808 CloseHandle(sys->device_ready);
809 CloseHandle(sys->device_changed);
814 set_shortname("MMDevice")
815 set_description(N_("Windows Multimedia Device output"))
816 set_capability("audio output", 150)
817 set_category(CAT_AUDIO)
818 set_subcategory(SUBCAT_AUDIO_AOUT)
819 add_shortcut("wasapi")
820 set_callbacks(Open, Close)