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))
107 aout_RestartRequest(aout, AOUT_RESTART_OUTPUT);
108 return SUCCEEDED(hr) ? 0 : -1;
111 /*** VLC audio output callbacks ***/
112 static int TimeGet(audio_output_t *aout, mtime_t *restrict delay)
114 aout_sys_t *sys = aout->sys;
118 hr = aout_stream_TimeGet(sys->stream, delay);
121 return SUCCEEDED(hr) ? 0 : -1;
124 static void Play(audio_output_t *aout, block_t *block)
126 aout_sys_t *sys = aout->sys;
130 hr = aout_stream_Play(sys->stream, block);
133 vlc_FromHR(aout, hr);
136 static void Pause(audio_output_t *aout, bool paused, mtime_t date)
138 aout_sys_t *sys = aout->sys;
142 hr = aout_stream_Pause(sys->stream, paused);
145 vlc_FromHR(aout, hr);
149 static void Flush(audio_output_t *aout, bool wait)
151 aout_sys_t *sys = aout->sys;
156 { /* Loosy drain emulation */
159 if (SUCCEEDED(aout_stream_TimeGet(sys->stream, &delay)))
160 Sleep((delay / (CLOCK_FREQ / 1000)) + 1);
163 aout_stream_Flush(sys->stream);
169 static int VolumeSet(audio_output_t *aout, float vol)
171 ISimpleAudioVolume *volume = aout->sys->volume;
175 if (TryEnterMTA(aout))
178 HRESULT hr = ISimpleAudioVolume_SetMasterVolume(volume, vol, NULL);
180 msg_Err(aout, "cannot set volume (error 0x%lx)", hr);
183 return FAILED(hr) ? -1 : 0;
186 static int MuteSet(audio_output_t *aout, bool mute)
188 ISimpleAudioVolume *volume = aout->sys->volume;
192 if (TryEnterMTA(aout))
195 HRESULT hr = ISimpleAudioVolume_SetMute(volume, mute ? TRUE : FALSE, NULL);
197 msg_Err(aout, "cannot set volume (error 0x%lx)", hr);
200 return FAILED(hr) ? -1 : 0;
203 /*** Audio session events ***/
204 static inline aout_sys_t *vlc_AudioSessionEvents_sys(IAudioSessionEvents *this)
206 return (void *)(((char *)this) - offsetof(aout_sys_t, session_events));
210 vlc_AudioSessionEvents_QueryInterface(IAudioSessionEvents *this, REFIID riid,
213 if (IsEqualIID(riid, &IID_IUnknown)
214 || IsEqualIID(riid, &IID_IAudioSessionEvents))
217 IUnknown_AddRef(this);
223 return E_NOINTERFACE;
227 static STDMETHODIMP_(ULONG)
228 vlc_AudioSessionEvents_AddRef(IAudioSessionEvents *this)
230 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
231 return InterlockedIncrement(&sys->refs);
234 static STDMETHODIMP_(ULONG)
235 vlc_AudioSessionEvents_Release(IAudioSessionEvents *this)
237 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
238 return InterlockedDecrement(&sys->refs);
242 vlc_AudioSessionEvents_OnDisplayNameChanged(IAudioSessionEvents *this,
243 LPCWSTR wname, LPCGUID ctx)
245 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
246 audio_output_t *aout = sys->aout;
248 msg_Dbg(aout, "display name changed: %ls", wname);
254 vlc_AudioSessionEvents_OnIconPathChanged(IAudioSessionEvents *this,
255 LPCWSTR wpath, LPCGUID ctx)
257 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
258 audio_output_t *aout = sys->aout;
260 msg_Dbg(aout, "icon path changed: %ls", wpath);
266 vlc_AudioSessionEvents_OnSimpleVolumeChanged(IAudioSessionEvents *this,
267 float vol, WINBOOL mute,
270 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
271 audio_output_t *aout = sys->aout;
273 msg_Dbg(aout, "simple volume changed: %f, muting %sabled", vol,
274 mute ? "en" : "dis");
275 aout_VolumeReport(aout, vol);
276 aout_MuteReport(aout, mute == TRUE);
282 vlc_AudioSessionEvents_OnChannelVolumeChanged(IAudioSessionEvents *this,
283 DWORD count, float *vols,
284 DWORD changed, LPCGUID ctx)
286 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
287 audio_output_t *aout = sys->aout;
289 msg_Dbg(aout, "channel volume %lu of %lu changed: %f", changed, count,
296 vlc_AudioSessionEvents_OnGroupingParamChanged(IAudioSessionEvents *this,
297 LPCGUID param, LPCGUID ctx)
300 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
301 audio_output_t *aout = sys->aout;
303 msg_Dbg(aout, "grouping parameter changed");
310 vlc_AudioSessionEvents_OnStateChanged(IAudioSessionEvents *this,
311 AudioSessionState state)
313 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
314 audio_output_t *aout = sys->aout;
316 msg_Dbg(aout, "state changed: %d", state);
321 vlc_AudioSessionEvents_OnSessionDisconnected(IAudioSessionEvents *this,
322 AudioSessionDisconnectReason reason)
324 aout_sys_t *sys = vlc_AudioSessionEvents_sys(this);
325 audio_output_t *aout = sys->aout;
329 case DisconnectReasonDeviceRemoval:
330 msg_Warn(aout, "session disconnected: %s", "device removed");
332 case DisconnectReasonServerShutdown:
333 msg_Err(aout, "session disconnected: %s", "service stopped");
335 case DisconnectReasonFormatChanged:
336 msg_Warn(aout, "session disconnected: %s", "format changed");
338 case DisconnectReasonSessionLogoff:
339 msg_Err(aout, "session disconnected: %s", "user logged off");
341 case DisconnectReasonSessionDisconnected:
342 msg_Err(aout, "session disconnected: %s", "session disconnected");
344 case DisconnectReasonExclusiveModeOverride:
345 msg_Err(aout, "session disconnected: %s", "stream overriden");
348 msg_Warn(aout, "session disconnected: unknown reason %d", reason);
351 /* NOTE: audio decoder thread should get invalidated device and restart */
355 static const struct IAudioSessionEventsVtbl vlc_AudioSessionEvents =
357 vlc_AudioSessionEvents_QueryInterface,
358 vlc_AudioSessionEvents_AddRef,
359 vlc_AudioSessionEvents_Release,
361 vlc_AudioSessionEvents_OnDisplayNameChanged,
362 vlc_AudioSessionEvents_OnIconPathChanged,
363 vlc_AudioSessionEvents_OnSimpleVolumeChanged,
364 vlc_AudioSessionEvents_OnChannelVolumeChanged,
365 vlc_AudioSessionEvents_OnGroupingParamChanged,
366 vlc_AudioSessionEvents_OnStateChanged,
367 vlc_AudioSessionEvents_OnSessionDisconnected,
371 /*** Initialization / deinitialization **/
372 static wchar_t *var_InheritWide(vlc_object_t *obj, const char *name)
374 char *v8 = var_InheritString(obj, name);
378 wchar_t *v16 = ToWide(v8);
382 #define var_InheritWide(o,n) var_InheritWide(VLC_OBJECT(o),n)
384 static void MMSession(audio_output_t *aout, aout_sys_t *sys)
386 IAudioSessionControl *control;
389 /* Register session control */
390 if (sys->manager != NULL)
392 hr = IAudioSessionManager_GetSimpleAudioVolume(sys->manager,
394 FALSE, &sys->volume);
396 msg_Err(aout, "cannot get simple volume (error 0x%lx)", hr);
398 hr = IAudioSessionManager_GetAudioSessionControl(sys->manager,
399 &GUID_VLC_AUD_OUT, 0,
402 msg_Err(aout, "cannot get session control (error 0x%lx)", hr);
412 wchar_t *ua = var_InheritWide(aout, "user-agent");
413 IAudioSessionControl_SetDisplayName(control, ua, NULL);
416 IAudioSessionControl_RegisterAudioSessionNotification(control,
417 &sys->session_events);
420 if (sys->volume != NULL)
421 { /* Get current values (_after_ changes notification registration) */
425 hr = ISimpleAudioVolume_GetMute(sys->volume, &mute);
427 msg_Err(aout, "cannot get mute (error 0x%lx)", hr);
429 aout_MuteReport(aout, mute != FALSE);
431 hr = ISimpleAudioVolume_GetMasterVolume(sys->volume, &level);
433 msg_Err(aout, "cannot get mute (error 0x%lx)", hr);
435 aout_VolumeReport(aout, level);
438 SetEvent(sys->device_ready);
439 /* Wait until device change or exit */
440 WaitForSingleObject(sys->device_changed, INFINITE);
442 /* Deregister session control */
445 IAudioSessionControl_UnregisterAudioSessionNotification(control,
446 &sys->session_events);
447 IAudioSessionControl_Release(control);
450 if (sys->volume != NULL)
451 ISimpleAudioVolume_Release(sys->volume);
454 /** MMDevice audio output thread.
455 * This thread takes cares of the audio session control. Inconveniently enough,
456 * the audio session control interface must:
457 * - be created and destroyed from the same thread, and
458 * - survive across VLC audio output calls.
459 * The only way to reconcile both requirements is a custom thread.
460 * The thread also ensure that the COM Multi-Thread Apartment is continuously
461 * referenced so that MMDevice objects are not destroyed early.
463 static void *MMThread(void *data)
465 audio_output_t *aout = data;
466 aout_sys_t *sys = aout->sys;
469 while (sys->it != NULL)
470 MMSession(aout, sys);
475 /*** Audio devices ***/
476 static int DevicesEnum(audio_output_t *aout)
478 aout_sys_t *sys = aout->sys;
480 IMMDeviceCollection *devs;
482 hr = IMMDeviceEnumerator_EnumAudioEndpoints(sys->it, eRender,
483 DEVICE_STATE_ACTIVE, &devs);
486 msg_Warn(aout, "cannot enumerate audio endpoints (error 0x%lx)", hr);
491 hr = IMMDeviceCollection_GetCount(devs, &count);
494 msg_Warn(aout, "cannot count audio endpoints (error 0x%lx)", hr);
500 for (UINT i = 0; i < count; i++)
503 char *id, *name = NULL;
505 hr = IMMDeviceCollection_Item(devs, i, &dev);
509 /* Unique device ID */
511 hr = IMMDevice_GetId(dev, &devid);
514 IMMDevice_Release(dev);
517 id = FromWide(devid);
518 CoTaskMemFree(devid);
520 /* User-readable device name */
521 IPropertyStore *props;
522 hr = IMMDevice_OpenPropertyStore(dev, STGM_READ, &props);
528 hr = IPropertyStore_GetValue(props, &PKEY_Device_FriendlyName, &v);
530 name = FromWide(v.pwszVal);
531 PropVariantClear(&v);
532 IPropertyStore_Release(props);
534 IMMDevice_Release(dev);
536 aout_HotplugReport(aout, id, (name != NULL) ? name : id);
541 IMMDeviceCollection_Release(devs);
546 * Opens the selected audio output device.
548 static HRESULT OpenDevice(audio_output_t *aout, const char *devid)
550 aout_sys_t *sys = aout->sys;
553 assert(sys->dev == NULL);
555 if (devid != NULL) /* Device selected explicitly */
557 msg_Dbg(aout, "using selected device %s", devid);
559 wchar_t *wdevid = ToWide(devid);
560 if (likely(wdevid != NULL))
562 hr = IMMDeviceEnumerator_GetDevice(sys->it, wdevid, &sys->dev);
568 else /* Default device selected by policy */
570 msg_Dbg(aout, "using default device");
571 hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(sys->it, eRender,
572 eConsole, &sys->dev);
574 assert(sys->manager == NULL);
577 msg_Err(aout, "cannot get device (error 0x%lx)", hr);
581 /* Create session manager (for controls even w/o active audio client) */
583 hr = IMMDevice_Activate(sys->dev, &IID_IAudioSessionManager,
584 CLSCTX_ALL, NULL, &pv);
586 msg_Err(aout, "cannot activate session manager (error 0x%lx)", hr);
590 /* Report actual device */
592 hr = IMMDevice_GetId(sys->dev, &wdevid);
595 char *id = FromWide(wdevid);
596 CoTaskMemFree(wdevid);
597 if (likely(id != NULL))
599 aout_DeviceReport(aout, id);
604 SetEvent(sys->device_changed);
605 WaitForSingleObject(sys->device_ready, INFINITE);
610 * Closes the opened audio output device (if any).
612 static void CloseDevice(audio_output_t *aout)
614 aout_sys_t *sys = aout->sys;
616 assert(sys->dev != NULL);
618 if (sys->manager != NULL)
620 IAudioSessionManager_Release(sys->manager);
624 IMMDevice_Release(sys->dev);
628 static int DeviceSelect(audio_output_t *aout, const char *id)
630 aout_sys_t *sys = aout->sys;
633 if (TryEnterMTA(aout))
636 if (sys->dev != NULL)
639 hr = OpenDevice(aout, id);
640 while (hr == AUDCLNT_E_DEVICE_INVALIDATED)
641 hr = OpenDevice(aout, NULL); /* Fallback to default device */
644 if (sys->stream != NULL)
645 /* Request restart of stream with the new device */
646 aout_RestartRequest(aout, AOUT_RESTART_OUTPUT);
647 return FAILED(hr) ? -1 : 0;
651 * Callback for aout_stream_t to create a stream on the device.
652 * This can instantiate an IAudioClient or IDirectSound(8) object.
654 static HRESULT ActivateDevice(void *opaque, REFIID iid, PROPVARIANT *actparms,
657 IMMDevice *dev = opaque;
659 return IMMDevice_Activate(dev, iid, CLSCTX_ALL, actparms, pv);
662 static int Start(audio_output_t *aout, audio_sample_format_t *restrict fmt)
664 aout_sys_t *sys = aout->sys;
667 assert (sys->stream == NULL);
668 /* Open the default device if required (to deal with restarts) */
669 if (sys->dev == NULL && FAILED(DeviceSelect(aout, NULL)))
672 aout_stream_t *s = vlc_object_create(aout, sizeof (*s));
673 if (unlikely(s == NULL))
676 s->owner.device = sys->dev;
677 s->owner.activate = ActivateDevice;
680 hr = aout_stream_Start(s, fmt, &GUID_VLC_AUD_OUT);
684 vlc_object_release(s);
687 return vlc_FromHR(aout, hr);
690 static void Stop(audio_output_t *aout)
692 aout_sys_t *sys = aout->sys;
694 assert (sys->stream != NULL);
697 aout_stream_Stop(sys->stream);
700 vlc_object_release(sys->stream);
704 static int Open(vlc_object_t *obj)
706 audio_output_t *aout = (audio_output_t *)obj;
710 if (!aout->b_force && var_InheritBool(aout, "spdif"))
711 /* Fallback to other plugin until pass-through is implemented */
714 aout_sys_t *sys = malloc(sizeof (*sys));
715 if (unlikely(sys == NULL))
724 sys->session_events.lpVtbl = &vlc_AudioSessionEvents;
727 sys->device_changed = CreateEvent(NULL, FALSE, FALSE, NULL);
728 sys->device_ready = CreateEvent(NULL, FALSE, FALSE, NULL);
729 if (unlikely(sys->device_changed == NULL || sys->device_ready == NULL))
732 /* Initialize MMDevice API */
733 if (TryEnterMTA(aout))
736 hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL,
737 &IID_IMMDeviceEnumerator, &pv);
741 msg_Dbg(aout, "cannot create device enumerator (error 0x%lx)", hr);
746 if (vlc_clone(&sys->thread, MMThread, aout, VLC_THREAD_PRIORITY_LOW))
748 WaitForSingleObject(sys->device_ready, INFINITE);
750 DeviceSelect(aout, NULL); /* Get a device to start with */
751 LeaveMTA(); /* leave MTA after thread has entered MTA */
755 aout->time_get = TimeGet;
759 aout->volume_set = VolumeSet;
760 aout->mute_set = MuteSet;
761 aout->device_select = DeviceSelect;
768 IMMDeviceEnumerator_Release(sys->it);
771 if (sys->device_ready != NULL)
772 CloseHandle(sys->device_ready);
773 if (sys->device_changed != NULL)
774 CloseHandle(sys->device_changed);
779 static void Close(vlc_object_t *obj)
781 audio_output_t *aout = (audio_output_t *)obj;
782 aout_sys_t *sys = aout->sys;
784 EnterMTA(); /* enter MTA before thread leaves MTA */
785 if (sys->dev != NULL)
788 IMMDeviceEnumerator_Release(sys->it);
791 SetEvent(sys->device_changed);
792 vlc_join(sys->thread, NULL);
795 CloseHandle(sys->device_ready);
796 CloseHandle(sys->device_changed);
801 set_shortname("MMDevice")
802 set_description(N_("Windows Multimedia Device output"))
803 set_capability("audio output", /*150*/0)
804 set_category(CAT_AUDIO)
805 set_subcategory(SUBCAT_AUDIO_AOUT)
806 add_shortcut("wasapi")
807 set_callbacks(Open, Close)