]> git.sesse.net Git - vlc/blob - modules/audio_output/wasapi.c
OSS: trivial fixes
[vlc] / modules / audio_output / wasapi.c
1 /*****************************************************************************
2  * wasapi.c : Windows Audio Session API output plugin for VLC
3  *****************************************************************************
4  * Copyright (C) 2012 RĂ©mi Denis-Courmont
5  *
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.
10  *
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.
15  *
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  *****************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #define INITGUID
26 #define COBJMACROS
27 #define CONST_VTABLE
28
29 #include <stdlib.h>
30 #include <assert.h>
31 #include <audioclient.h>
32
33 #include <vlc_common.h>
34 #include <vlc_aout.h>
35 #include "mmdevice.h"
36
37 static LARGE_INTEGER freq; /* performance counters frequency */
38
39 BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID); /* avoid warning */
40
41 BOOL WINAPI DllMain(HINSTANCE dll, DWORD reason, LPVOID reserved)
42 {
43     (void) dll;
44     (void) reserved;
45
46     switch (reason)
47     {
48         case DLL_PROCESS_ATTACH:
49             if (!QueryPerformanceFrequency(&freq))
50                 return FALSE;
51             break;
52     }
53     return TRUE;
54 }
55
56 static UINT64 GetQPC(void)
57 {
58     LARGE_INTEGER counter;
59
60     if (!QueryPerformanceCounter(&counter))
61         abort();
62
63     lldiv_t d = lldiv(counter.QuadPart, freq.QuadPart);
64     return (d.quot * 10000000) + ((d.rem * 10000000) / freq.QuadPart);
65 }
66
67 typedef struct aout_stream_sys
68 {
69     IAudioClient *client;
70
71     uint8_t chans_table[AOUT_CHAN_MAX];
72     uint8_t chans_to_reorder;
73
74     uint8_t bits; /**< Bits per sample */
75     unsigned rate; /**< Sample rate */
76     unsigned bytes_per_frame;
77     UINT32 written; /**< Frames written to the buffer */
78     UINT32 frames; /**< Total buffer size (frames) */
79 } aout_stream_sys_t;
80
81
82 /*** VLC audio output callbacks ***/
83 static HRESULT TimeGet(aout_stream_t *s, mtime_t *restrict delay)
84 {
85     aout_stream_sys_t *sys = s->sys;
86     void *pv;
87     UINT64 pos, qpcpos;
88     HRESULT hr;
89
90     hr = IAudioClient_GetService(sys->client, &IID_IAudioClock, &pv);
91     if (SUCCEEDED(hr))
92     {
93         IAudioClock *clock = pv;
94
95         hr = IAudioClock_GetPosition(clock, &pos, &qpcpos);
96         if (FAILED(hr))
97             msg_Err(s, "cannot get position (error 0x%lx)", hr);
98         IAudioClock_Release(clock);
99     }
100     else
101         msg_Err(s, "cannot get clock (error 0x%lx)", hr);
102
103     if (SUCCEEDED(hr))
104     {
105         if (pos != 0)
106         {
107             *delay = ((GetQPC() - qpcpos) / (10000000 / CLOCK_FREQ));
108             static_assert((10000000 % CLOCK_FREQ) == 0,
109                           "Frequency conversion broken");
110         }
111         else
112         {
113             *delay = sys->written * CLOCK_FREQ / sys->rate;
114             msg_Dbg(s, "extrapolating position: still propagating buffers");
115         }
116     }
117     return hr;
118 }
119
120 static HRESULT Play(aout_stream_t *s, block_t *block)
121 {
122     aout_stream_sys_t *sys = s->sys;
123     void *pv;
124     HRESULT hr;
125
126     if (sys->chans_to_reorder)
127         aout_ChannelReorder(block->p_buffer, block->i_buffer,
128                           sys->chans_to_reorder, sys->chans_table, sys->bits);
129
130     hr = IAudioClient_GetService(sys->client, &IID_IAudioRenderClient, &pv);
131     if (FAILED(hr))
132     {
133         msg_Err(s, "cannot get render client (error 0x%lx)", hr);
134         goto out;
135     }
136
137     IAudioRenderClient *render = pv;
138     for (;;)
139     {
140         UINT32 frames;
141         hr = IAudioClient_GetCurrentPadding(sys->client, &frames);
142         if (FAILED(hr))
143         {
144             msg_Err(s, "cannot get current padding (error 0x%lx)", hr);
145             break;
146         }
147
148         assert(frames <= sys->frames);
149         frames = sys->frames - frames;
150         if (frames > block->i_nb_samples)
151             frames = block->i_nb_samples;
152
153         BYTE *dst;
154         hr = IAudioRenderClient_GetBuffer(render, frames, &dst);
155         if (FAILED(hr))
156         {
157             msg_Err(s, "cannot get buffer (error 0x%lx)", hr);
158             break;
159         }
160
161         const size_t copy = frames * sys->bytes_per_frame;
162
163         memcpy(dst, block->p_buffer, copy);
164         hr = IAudioRenderClient_ReleaseBuffer(render, frames, 0);
165         if (FAILED(hr))
166         {
167             msg_Err(s, "cannot release buffer (error 0x%lx)", hr);
168             break;
169         }
170         IAudioClient_Start(sys->client);
171
172         block->p_buffer += copy;
173         block->i_buffer -= copy;
174         block->i_nb_samples -= frames;
175         sys->written += frames;
176         if (block->i_nb_samples == 0)
177             break; /* done */
178
179         /* Out of buffer space, sleep */
180         msleep(AOUT_MIN_PREPARE_TIME
181              + block->i_nb_samples * CLOCK_FREQ / sys->rate);
182     }
183     IAudioRenderClient_Release(render);
184 out:
185     block_Release(block);
186
187     return hr;
188 }
189
190 static HRESULT Pause(aout_stream_t *s, bool paused)
191 {
192     aout_stream_sys_t *sys = s->sys;
193     HRESULT hr;
194
195     if (paused)
196         hr = IAudioClient_Stop(sys->client);
197     else
198         hr = IAudioClient_Start(sys->client);
199     if (FAILED(hr))
200         msg_Warn(s, "cannot %s stream (error 0x%lx)",
201                  paused ? "stop" : "start", hr);
202     return hr;
203 }
204
205 static HRESULT Flush(aout_stream_t *s)
206 {
207     aout_stream_sys_t *sys = s->sys;
208     HRESULT hr;
209
210     IAudioClient_Stop(sys->client);
211
212     hr = IAudioClient_Reset(sys->client);
213     if (FAILED(hr))
214         msg_Warn(s, "cannot reset stream (error 0x%lx)", hr);
215     else
216         sys->written = 0;
217     return hr;
218 }
219
220
221 /*** Initialization / deinitialization **/
222 static const uint32_t chans_out[] = {
223     SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT,
224     SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY,
225     SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT, SPEAKER_BACK_CENTER,
226     SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT, 0
227 };
228 static const uint32_t chans_in[] = {
229     SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT,
230     SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT,
231     SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT, SPEAKER_BACK_CENTER,
232     SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY, 0
233 };
234
235 static void vlc_ToWave(WAVEFORMATEXTENSIBLE *restrict wf,
236                        audio_sample_format_t *restrict audio)
237 {
238     switch (audio->i_format)
239     {
240         case VLC_CODEC_FL64:
241             audio->i_format = VLC_CODEC_FL32;
242         case VLC_CODEC_FL32:
243             wf->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
244             break;
245
246         case VLC_CODEC_S8:
247         case VLC_CODEC_U8:
248             audio->i_format = VLC_CODEC_S16N;
249         case VLC_CODEC_S16N:
250             wf->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
251             break;
252
253         default:
254             audio->i_format = VLC_CODEC_FL32;
255             wf->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
256             break;
257     }
258     aout_FormatPrepare (audio);
259
260     wf->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
261     wf->Format.nChannels = audio->i_channels;
262     wf->Format.nSamplesPerSec = audio->i_rate;
263     wf->Format.nAvgBytesPerSec = audio->i_bytes_per_frame * audio->i_rate;
264     wf->Format.nBlockAlign = audio->i_bytes_per_frame;
265     wf->Format.wBitsPerSample = audio->i_bitspersample;
266     wf->Format.cbSize = sizeof (*wf) - sizeof (wf->Format);
267
268     wf->Samples.wValidBitsPerSample = audio->i_bitspersample;
269
270     wf->dwChannelMask = 0;
271     for (unsigned i = 0; pi_vlc_chan_order_wg4[i]; i++)
272         if (audio->i_physical_channels & pi_vlc_chan_order_wg4[i])
273             wf->dwChannelMask |= chans_in[i];
274 }
275
276 static int vlc_FromWave(const WAVEFORMATEX *restrict wf,
277                         audio_sample_format_t *restrict audio)
278 {
279     audio->i_rate = wf->nSamplesPerSec;
280     audio->i_physical_channels = 0;
281
282     if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
283     {
284         const WAVEFORMATEXTENSIBLE *wfe = (void *)wf;
285
286         for (unsigned i = 0; chans_in[i]; i++)
287             if (wfe->dwChannelMask & chans_in[i])
288                 audio->i_physical_channels |= pi_vlc_chan_order_wg4[i];
289     }
290
291     audio->i_original_channels = audio->i_physical_channels;
292     aout_FormatPrepare (audio);
293
294     if (wf->nChannels != audio->i_channels)
295         return -1;
296     return 0;
297 }
298
299 static unsigned vlc_CheckWaveOrder (const WAVEFORMATEX *restrict wf,
300                                     uint8_t *restrict table)
301 {
302     uint32_t mask = 0;
303
304     if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
305     {
306         const WAVEFORMATEXTENSIBLE *wfe = (void *)wf;
307
308         mask = wfe->dwChannelMask;
309     }
310     return aout_CheckChannelReorder(chans_in, chans_out, mask, table);
311 }
312
313 static HRESULT Start(aout_stream_t *s, audio_sample_format_t *restrict fmt,
314                      const GUID *sid)
315 {
316     aout_stream_sys_t *sys = malloc(sizeof (*sys));
317     if (unlikely(sys == NULL))
318         return E_OUTOFMEMORY;
319     sys->client = NULL;
320
321     void *pv;
322     HRESULT hr = aout_stream_Activate(s, &IID_IAudioClient, NULL, &pv);
323     if (FAILED(hr))
324     {
325         msg_Err(s, "cannot activate client (error 0x%lx)", hr);
326         goto error;
327     }
328     sys->client = pv;
329
330     /* Configure audio stream */
331     WAVEFORMATEXTENSIBLE wf;
332     WAVEFORMATEX *pwf;
333
334     vlc_ToWave(&wf, fmt);
335     hr = IAudioClient_IsFormatSupported(sys->client, AUDCLNT_SHAREMODE_SHARED,
336                                         &wf.Format, &pwf);
337     if (FAILED(hr))
338     {
339         msg_Err(s, "cannot negotiate audio format (error 0x%lx)", hr);
340         goto error;
341     }
342
343     if (hr == S_FALSE)
344     {
345         assert(pwf != NULL);
346         if (vlc_FromWave(pwf, fmt))
347         {
348             CoTaskMemFree(pwf);
349             msg_Err(s, "unsupported audio format");
350             hr = E_INVALIDARG;
351             goto error;
352         }
353         msg_Dbg(s, "modified format");
354     }
355     else
356         assert(pwf == NULL);
357
358     sys->chans_to_reorder = vlc_CheckWaveOrder((hr == S_OK) ? &wf.Format : pwf,
359                                                sys->chans_table);
360     sys->bits = fmt->i_bitspersample;
361
362     hr = IAudioClient_Initialize(sys->client, AUDCLNT_SHAREMODE_SHARED, 0,
363                                  AOUT_MAX_PREPARE_TIME * 10, 0,
364                                  (hr == S_OK) ? &wf.Format : pwf, sid);
365     CoTaskMemFree(pwf);
366     if (FAILED(hr))
367     {
368         msg_Err(s, "cannot initialize audio client (error 0x%lx)", hr);
369         goto error;
370     }
371
372     hr = IAudioClient_GetBufferSize(sys->client, &sys->frames);
373     if (FAILED(hr))
374     {
375         msg_Err(s, "cannot get buffer size (error 0x%lx)", hr);
376         goto error;
377     }
378
379     sys->rate = fmt->i_rate;
380     sys->bytes_per_frame = fmt->i_bytes_per_frame;
381     sys->written = 0;
382     s->sys = sys;
383     s->time_get = TimeGet;
384     s->play = Play;
385     s->pause = Pause;
386     s->flush = Flush;
387     return S_OK;
388 error:
389     if (sys->client != NULL)
390         IAudioClient_Release(sys->client);
391     free(sys);
392     return hr;
393 }
394
395 static void Stop(aout_stream_t *s)
396 {
397     aout_stream_sys_t *sys = s->sys;
398
399     IAudioClient_Stop(sys->client); /* should not be needed */
400     IAudioClient_Release(sys->client);
401 }
402
403 HRESULT aout_stream_Start(aout_stream_t *s,
404                           audio_sample_format_t *restrict fmt, const GUID *sid)
405 {
406     return Start(s, fmt, sid);
407 }
408
409 void aout_stream_Stop(aout_stream_t *s)
410 {
411     Stop(s);
412 }