]> git.sesse.net Git - vlc/blob - modules/audio_output/directx.c
PulseAudio: remove unused datum
[vlc] / modules / audio_output / directx.c
1 /*****************************************************************************
2  * directx.c: Windows DirectX audio output method
3  *****************************************************************************
4  * Copyright (C) 2001-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation, Inc.,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <math.h>
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_aout.h>
37 #include <vlc_charset.h>
38
39 #include "windows_audio_common.h"
40
41 #define DS_BUF_SIZE (6*1024*1024)
42
43 /*****************************************************************************
44  * aout_sys_t: directx audio output method descriptor
45  *****************************************************************************
46  * This structure is part of the audio output thread descriptor.
47  * It describes the direct sound specific properties of an audio device.
48  *****************************************************************************/
49 struct aout_sys_t
50 {
51     HINSTANCE           hdsound_dll;  /* handle of the opened dsound dll */
52
53     LPDIRECTSOUND       p_dsobject;   /* main Direct Sound object */
54     LPDIRECTSOUNDBUFFER p_dsbuffer;   /* the sound buffer we use (direct sound
55                                        * takes care of mixing all the
56                                        * secondary buffers into the primary) */
57
58     LPDIRECTSOUNDNOTIFY p_notify;
59     HANDLE hnotify_evt;
60     struct
61     {
62         float            volume;
63         LONG             mb;
64         bool             mute;
65     } volume;
66
67     int      i_bytes_per_sample;      /* Size in bytes of one frame */
68     int      i_rate;                  /* Sample rate */
69
70     uint8_t  chans_to_reorder;        /* do we need channel reordering */
71     uint8_t  chan_table[AOUT_CHAN_MAX];
72     uint32_t i_channel_mask;
73     vlc_fourcc_t format;
74
75     size_t  i_write;
76 };
77
78 /*****************************************************************************
79  * Local prototypes.
80  *****************************************************************************/
81 static int  Open( vlc_object_t * );
82 static void Close( vlc_object_t * );
83 static void Stop( audio_output_t * );
84 static void Play( audio_output_t *, block_t * );
85 static int  VolumeSet( audio_output_t *, float );
86 static int  MuteSet( audio_output_t *, bool );
87 static void Flush( audio_output_t *, bool );
88 static void Pause( audio_output_t *, bool, mtime_t );
89 static int  TimeGet( audio_output_t *, mtime_t *);
90
91 /* local functions */
92 static int  InitDirectSound   ( audio_output_t * );
93 static int  CreateDSBuffer    ( audio_output_t *, int, int, int, int, bool );
94 static int  CreateDSBufferPCM ( audio_output_t *, vlc_fourcc_t*, int, int, bool );
95 static void DestroyDSBuffer   ( audio_output_t * );
96 static int  FillBuffer        ( audio_output_t *, block_t * );
97
98 static int ReloadDirectXDevices( vlc_object_t *, const char *,
99                                  char ***, char *** );
100
101 /* Speaker setup override options list */
102 static const char *const speaker_list[] = { "Windows default", "Mono", "Stereo",
103                                             "Quad", "5.1", "7.1" };
104
105 /*****************************************************************************
106  * Module descriptor
107  *****************************************************************************/
108 #define DEVICE_TEXT N_("Output device")
109 #define DEVICE_LONGTEXT N_("Select your audio output device")
110
111 #define SPEAKER_TEXT N_("Speaker configuration")
112 #define SPEAKER_LONGTEXT N_("Select speaker configuration you want to use. " \
113     "This option doesn't upmix! So NO e.g. Stereo -> 5.1 conversion." )
114
115 #define VOLUME_TEXT N_("Audio volume")
116 #define VOLUME_LONGTEXT N_("Audio volume in hundredths of decibels (dB).")
117
118 vlc_module_begin ()
119     set_description( N_("DirectX audio output") )
120     set_shortname( "DirectX" )
121     set_capability( "audio output", 100 )
122     set_category( CAT_AUDIO )
123     set_subcategory( SUBCAT_AUDIO_AOUT )
124     add_shortcut( "directx", "aout_directx" )
125
126     add_string( "directx-audio-device", NULL,
127              DEVICE_TEXT, DEVICE_LONGTEXT, false )
128         change_string_cb( ReloadDirectXDevices )
129     add_obsolete_string( "directx-audio-device-name")
130     add_bool( "directx-audio-float32", true, FLOAT_TEXT,
131               FLOAT_LONGTEXT, true )
132     add_string( "directx-audio-speaker", "Windows default",
133                  SPEAKER_TEXT, SPEAKER_LONGTEXT, true )
134         change_string_list( speaker_list, speaker_list )
135     add_float( "directx-volume", 1.0f,
136                  VOLUME_TEXT, VOLUME_LONGTEXT, true )
137         change_integer_range( DSBVOLUME_MIN, DSBVOLUME_MAX )
138
139     set_callbacks( Open, Close )
140 vlc_module_end ()
141
142 /*****************************************************************************
143  * OpenAudio: open the audio device
144  *****************************************************************************
145  * This function opens and setups Direct Sound.
146  *****************************************************************************/
147 static int Start( audio_output_t *p_aout, audio_sample_format_t *restrict fmt )
148 {
149     char * psz_speaker;
150     int i = 0;
151
152     const char * const * ppsz_compare = speaker_list;
153
154     msg_Dbg( p_aout, "Opening DirectSound Audio Output" );
155
156     /* Retrieve config values */
157     var_Create( p_aout, "directx-audio-float32",
158                 VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
159     psz_speaker = var_CreateGetString( p_aout, "directx-audio-speaker" );
160
161     while ( *ppsz_compare != NULL )
162     {
163         if ( !strncmp( *ppsz_compare, psz_speaker, strlen(*ppsz_compare) ) )
164         {
165             break;
166         }
167         ppsz_compare++; i++;
168     }
169
170     if ( *ppsz_compare == NULL )
171     {
172         msg_Err( p_aout, "(%s) isn't valid speaker setup option", psz_speaker );
173         msg_Err( p_aout, "Defaulting to Windows default speaker config");
174         i = 0;
175     }
176     free( psz_speaker );
177
178     /* Initialise DirectSound */
179     if( InitDirectSound( p_aout ) )
180     {
181         msg_Err( p_aout, "cannot initialize DirectSound" );
182         goto error;
183     }
184
185     if( i == 0 )
186     {
187         DWORD ui_speaker_config;
188
189         /* Check the speaker configuration to determine which channel config
190          * should be the default */
191         if( FAILED( IDirectSound_GetSpeakerConfig( p_aout->sys->p_dsobject,
192                                               &ui_speaker_config ) ) )
193         {
194             ui_speaker_config = DSSPEAKER_STEREO;
195             msg_Dbg( p_aout, "GetSpeakerConfig failed" );
196         }
197         fmt->i_physical_channels = AOUT_CHANS_2_0;
198
199         const char *name = "Unknown";
200         switch( DSSPEAKER_CONFIG(ui_speaker_config) )
201         {
202         case DSSPEAKER_7POINT1:
203         case DSSPEAKER_7POINT1_SURROUND:
204             name = "7.1";
205             fmt->i_physical_channels = AOUT_CHANS_7_1;
206             break;
207         case DSSPEAKER_5POINT1:
208         case DSSPEAKER_5POINT1_SURROUND:
209             name = "5.1";
210             fmt->i_physical_channels = AOUT_CHANS_5_1;
211             break;
212         case DSSPEAKER_QUAD:
213             name = "Quad";
214             fmt->i_physical_channels = AOUT_CHANS_4_0;
215             break;
216 #if 0 /* Lots of people just get their settings wrong and complain that
217        * this is a problem with VLC so just don't ever set mono by default. */
218         case DSSPEAKER_MONO:
219             name = "Mono";
220             fmt->i_physical_channels = AOUT_CHAN_CENTER;
221             break;
222 #endif
223         case DSSPEAKER_SURROUND: /* XXX: stereo, really? -- Courmisch */
224             name = "Surround";
225             break;
226         case DSSPEAKER_STEREO:
227             name = "Stereo";
228             break;
229         }
230         msg_Dbg( p_aout, "%s speaker config: %s", "Windows", name );
231     }
232     else
233     {   /* Overriden speaker configuration */
234         const char *name = "Non-existant";
235         switch( i )
236         {
237         case 1: /* Mono */
238             name = "Mono";
239             fmt->i_physical_channels = AOUT_CHAN_CENTER;
240             break;
241         case 2: /* Stereo */
242             name = "Stereo";
243             fmt->i_physical_channels = AOUT_CHANS_2_0;
244             break;
245         case 3: /* Quad */
246             name = "Quad";
247             fmt->i_physical_channels = AOUT_CHANS_4_0;
248             break;
249         case 4: /* 5.1 */
250             name = "5.1";
251             fmt->i_physical_channels = AOUT_CHANS_5_1;
252             break;
253         case 5: /* 7.1 */
254             name = "7.1";
255             fmt->i_physical_channels = AOUT_CHANS_7_1;
256             break;
257         }
258         msg_Dbg( p_aout, "%s speaker config: %s", "VLC", name );
259     }
260
261     /* Open the device */
262     if ( AOUT_FMT_SPDIF( fmt )
263      && var_InheritBool( p_aout, "spdif" )
264      && CreateDSBuffer( p_aout, VLC_CODEC_SPDIFL, fmt->i_physical_channels,
265                         aout_FormatNbChannels( fmt ), fmt->i_rate, true )
266                                                                == VLC_SUCCESS )
267     {
268         msg_Dbg( p_aout, "using A/52 pass-through over S/PDIF" );
269         fmt->i_format = VLC_CODEC_SPDIFL;
270
271         /* Calculate the frame size in bytes */
272         fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
273         fmt->i_frame_length = A52_FRAME_NB;
274     }
275     else
276     {
277         aout_FormatPrepare( fmt );
278
279         if( CreateDSBufferPCM( p_aout, &fmt->i_format,
280                                fmt->i_physical_channels, fmt->i_rate, false )
281             != VLC_SUCCESS )
282         {
283             msg_Err( p_aout, "cannot open directx audio device" );
284             goto error;
285         }
286     }
287     p_aout->sys->i_write = 0;
288
289     /* Force volume update */
290     VolumeSet( p_aout, p_aout->sys->volume.volume );
291     MuteSet( p_aout, p_aout->sys->volume.mute );
292
293     /* then launch the notification thread */
294     p_aout->time_get = TimeGet;
295     p_aout->play = Play;
296     p_aout->pause = Pause;
297     p_aout->flush = Flush;
298
299     return VLC_SUCCESS;
300
301  error:
302     Stop( p_aout );
303     return VLC_EGENERIC;
304 }
305
306 /*****************************************************************************
307  * Play: we'll start playing the directsound buffer here because at least here
308  *       we know the first buffer has been put in the aout fifo and we also
309  *       know its date.
310  *****************************************************************************/
311 static void Play( audio_output_t *p_aout, block_t *p_buffer )
312 {
313     if(  FillBuffer( p_aout, p_buffer ) ==  VLC_SUCCESS )
314     {
315         /* start playing the buffer */
316         HRESULT dsresult = IDirectSoundBuffer_Play( p_aout->sys->p_dsbuffer,
317                                                     0, 0, DSBPLAY_LOOPING );
318         if( dsresult == DSERR_BUFFERLOST )
319         {
320             IDirectSoundBuffer_Restore( p_aout->sys->p_dsbuffer );
321             dsresult = IDirectSoundBuffer_Play( p_aout->sys->p_dsbuffer,
322                                                 0, 0, DSBPLAY_LOOPING );
323         }
324         if( dsresult != DS_OK )
325             msg_Err( p_aout, "cannot start playing buffer" );
326     }
327 }
328
329 static int VolumeSet( audio_output_t *p_aout, float volume )
330 {
331     aout_sys_t *sys = p_aout->sys;
332     int ret = 0;
333
334     /* millibels from linear amplification map 200% on DSBVOLUME_MAX */
335     LONG mb = lroundf( 5000.f * log10f( volume / 2.f ));
336
337     /* Clamp to allowed DirectSound range */
338     static_assert( DSBVOLUME_MIN < DSBVOLUME_MAX, "DSBVOLUME_* confused" );
339     if( mb > DSBVOLUME_MAX )
340     {
341         mb = DSBVOLUME_MAX;
342         ret = -1;
343     }
344     if( mb <= DSBVOLUME_MIN )
345         mb = DSBVOLUME_MIN;
346
347     sys->volume.mb = mb;
348     sys->volume.volume = volume;
349     if( !sys->volume.mute && sys->p_dsbuffer &&
350         IDirectSoundBuffer_SetVolume( sys->p_dsbuffer, mb ) != DS_OK )
351         return -1;
352     /* Convert back to UI volume */
353     aout_VolumeReport( p_aout, volume );
354
355     if( var_InheritBool( p_aout, "volume-save" ) )
356         config_PutFloat( p_aout, "directx-volume", volume );
357     return ret;
358 }
359
360 static int MuteSet( audio_output_t *p_aout, bool mute )
361 {
362     HRESULT res = DS_OK;
363     aout_sys_t *sys = p_aout->sys;
364
365     sys->volume.mute = mute;
366
367     if( sys->p_dsbuffer )
368         res = IDirectSoundBuffer_SetVolume( sys->p_dsbuffer,
369                                             mute? DSBVOLUME_MIN : sys->volume.mb );
370
371     aout_MuteReport( p_aout, mute );
372     return (res != DS_OK);
373 }
374
375 /*****************************************************************************
376  * CloseAudio: close the audio device
377  *****************************************************************************/
378 static void Stop( audio_output_t *p_aout )
379 {
380     aout_sys_t *p_sys = p_aout->sys;
381     msg_Dbg( p_aout, "closing audio device" );
382
383     if( p_sys->p_notify )
384         IDirectSoundNotify_Release(p_sys->p_notify );
385     p_sys->p_notify = NULL;
386
387     IDirectSoundBuffer_Stop( p_sys->p_dsbuffer );
388     /* release the secondary buffer */
389     DestroyDSBuffer( p_aout );
390
391     /* finally release the DirectSound object */
392     if( p_sys->p_dsobject )
393         IDirectSound_Release( p_sys->p_dsobject );
394 }
395
396 /*****************************************************************************
397  * InitDirectSound: handle all the gory details of DirectSound initialisation
398  *****************************************************************************/
399 static int InitDirectSound( audio_output_t *p_aout )
400 {
401     aout_sys_t *sys = p_aout->sys;
402     GUID guid, *p_guid = NULL;
403     HRESULT (WINAPI *OurDirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
404
405     OurDirectSoundCreate = (void *)
406         GetProcAddress( p_aout->sys->hdsound_dll,
407                         "DirectSoundCreate" );
408     if( OurDirectSoundCreate == NULL )
409     {
410         msg_Warn( p_aout, "GetProcAddress FAILED" );
411         goto error;
412     }
413
414     char *dev = var_GetNonEmptyString( p_aout, "directx-audio-device" );
415     if( dev != NULL )
416     {
417         LPOLESTR lpsz = ToWide( dev );
418         free( dev );
419
420         if( SUCCEEDED( IIDFromString( lpsz, &guid ) ) )
421             p_guid = &guid;
422         else
423             msg_Err( p_aout, "bad device GUID: %ls", lpsz );
424         free( lpsz );
425     }
426
427     /* Create the direct sound object */
428     if FAILED( OurDirectSoundCreate( p_guid, &sys->p_dsobject, NULL ) )
429     {
430         msg_Warn( p_aout, "cannot create a direct sound device" );
431         goto error;
432     }
433
434     /* Set DirectSound Cooperative level, ie what control we want over Windows
435      * sound device. In our case, DSSCL_EXCLUSIVE means that we can modify the
436      * settings of the primary buffer, but also that only the sound of our
437      * application will be hearable when it will have the focus.
438      * !!! (this is not really working as intended yet because to set the
439      * cooperative level you need the window handle of your application, and
440      * I don't know of any easy way to get it. Especially since we might play
441      * sound without any video, and so what window handle should we use ???
442      * The hack for now is to use the Desktop window handle - it seems to be
443      * working */
444 #if !VLC_WINSTORE_APP
445     if( IDirectSound_SetCooperativeLevel( p_aout->sys->p_dsobject,
446                                           GetDesktopWindow(),
447                                           DSSCL_EXCLUSIVE) )
448     {
449         msg_Warn( p_aout, "cannot set direct sound cooperative level" );
450     }
451 #endif
452     return VLC_SUCCESS;
453
454  error:
455     sys->p_dsobject = NULL;
456     return VLC_EGENERIC;
457
458 }
459
460 /*****************************************************************************
461  * CreateDSBuffer: Creates a direct sound buffer of the required format.
462  *****************************************************************************
463  * This function creates the buffer we'll use to play audio.
464  * In DirectSound there are two kinds of buffers:
465  * - the primary buffer: which is the actual buffer that the soundcard plays
466  * - the secondary buffer(s): these buffers are the one actually used by
467  *    applications and DirectSound takes care of mixing them into the primary.
468  *
469  * Once you create a secondary buffer, you cannot change its format anymore so
470  * you have to release the current one and create another.
471  *****************************************************************************/
472 static int CreateDSBuffer( audio_output_t *p_aout, int i_format,
473                            int i_channels, int i_nb_channels, int i_rate,
474                            bool b_probe )
475 {
476     WAVEFORMATEXTENSIBLE waveformat;
477     DSBUFFERDESC         dsbdesc;
478
479     /* First set the sound buffer format */
480     waveformat.dwChannelMask = 0;
481     for( unsigned i = 0; pi_vlc_chan_order_wg4[i]; i++ )
482         if( i_channels & pi_vlc_chan_order_wg4[i] )
483             waveformat.dwChannelMask |= pi_channels_in[i];
484
485     switch( i_format )
486     {
487     case VLC_CODEC_SPDIFL:
488         i_nb_channels = 2;
489         /* To prevent channel re-ordering */
490         waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
491         waveformat.Format.wBitsPerSample = 16;
492         waveformat.Samples.wValidBitsPerSample =
493             waveformat.Format.wBitsPerSample;
494         waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
495         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
496         break;
497
498     case VLC_CODEC_FL32:
499         waveformat.Format.wBitsPerSample = sizeof(float) * 8;
500         waveformat.Samples.wValidBitsPerSample =
501             waveformat.Format.wBitsPerSample;
502         waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
503         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
504         aout_GainRequest(p_aout, 8.f);
505         break;
506
507     case VLC_CODEC_S16N:
508         waveformat.Format.wBitsPerSample = 16;
509         waveformat.Samples.wValidBitsPerSample =
510             waveformat.Format.wBitsPerSample;
511         waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
512         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_PCM;
513         aout_GainRequest(p_aout, 8.f);
514         break;
515     }
516
517     waveformat.Format.nChannels = i_nb_channels;
518     waveformat.Format.nSamplesPerSec = i_rate;
519     waveformat.Format.nBlockAlign =
520         waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
521     waveformat.Format.nAvgBytesPerSec =
522         waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;
523
524     p_aout->sys->i_bytes_per_sample = waveformat.Format.nBlockAlign;
525     p_aout->sys->format = i_format;
526
527     /* Then fill in the direct sound descriptor */
528     memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
529     dsbdesc.dwSize = sizeof(DSBUFFERDESC);
530     dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 /* Better position accuracy */
531                     | DSBCAPS_GLOBALFOCUS         /* Allows background playing */
532                     | DSBCAPS_CTRLVOLUME          /* Allows volume control */
533                     | DSBCAPS_CTRLPOSITIONNOTIFY; /* Allow position notifications */
534
535     /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
536     if( i_nb_channels <= 2 )
537     {
538         waveformat.Format.cbSize = 0;
539     }
540     else
541     {
542         waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
543         waveformat.Format.cbSize =
544             sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
545
546         /* Needed for 5.1 on emu101k */
547         dsbdesc.dwFlags |= DSBCAPS_LOCHARDWARE;
548     }
549
550     dsbdesc.dwBufferBytes = DS_BUF_SIZE; /* buffer size */
551     dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&waveformat;
552
553     if FAILED( IDirectSound_CreateSoundBuffer(
554                    p_aout->sys->p_dsobject, &dsbdesc,
555                    &p_aout->sys->p_dsbuffer, NULL) )
556     {
557         if( dsbdesc.dwFlags & DSBCAPS_LOCHARDWARE )
558         {
559             /* Try without DSBCAPS_LOCHARDWARE */
560             dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE;
561             if FAILED( IDirectSound_CreateSoundBuffer(
562                    p_aout->sys->p_dsobject, &dsbdesc,
563                    &p_aout->sys->p_dsbuffer, NULL) )
564             {
565                 return VLC_EGENERIC;
566             }
567             if( !b_probe )
568                 msg_Dbg( p_aout, "couldn't use hardware sound buffer" );
569         }
570         else
571         {
572             return VLC_EGENERIC;
573         }
574     }
575
576     /* Stop here if we were just probing */
577     if( b_probe )
578     {
579         IDirectSoundBuffer_Release( p_aout->sys->p_dsbuffer );
580         p_aout->sys->p_dsbuffer = NULL;
581         return VLC_SUCCESS;
582     }
583
584     p_aout->sys->i_rate = i_rate;
585     p_aout->sys->i_channel_mask = waveformat.dwChannelMask;
586     p_aout->sys->chans_to_reorder =
587         aout_CheckChannelReorder( pi_channels_in, pi_channels_out,
588                                   waveformat.dwChannelMask,
589                                   p_aout->sys->chan_table );
590     if( p_aout->sys->chans_to_reorder )
591     {
592         msg_Dbg( p_aout, "channel reordering needed" );
593     }
594
595     if( IDirectSoundBuffer_QueryInterface( p_aout->sys->p_dsbuffer,
596                                            &IID_IDirectSoundNotify,
597                                            (void **) &p_aout->sys->p_notify )
598             != DS_OK )
599     {
600
601         msg_Err(p_aout, "Couldn't query IDirectSoundNotify");
602         p_aout->sys->p_notify = NULL;
603     }
604
605     FillBuffer(p_aout,NULL);
606
607     return VLC_SUCCESS;
608 }
609
610 /*****************************************************************************
611  * CreateDSBufferPCM: creates a PCM direct sound buffer.
612  *****************************************************************************
613  * We first try to create a WAVE_FORMAT_IEEE_FLOAT buffer if supported by
614  * the hardware, otherwise we create a WAVE_FORMAT_PCM buffer.
615  ****************************************************************************/
616 static int CreateDSBufferPCM( audio_output_t *p_aout, vlc_fourcc_t *i_format,
617                               int i_channels, int i_rate, bool b_probe )
618 {
619     unsigned i_nb_channels = popcount( i_channels );
620
621     if( !var_GetBool( p_aout, "directx-audio-float32" ) ||
622         CreateDSBuffer( p_aout, VLC_CODEC_FL32,
623                         i_channels, i_nb_channels, i_rate, b_probe )
624         != VLC_SUCCESS )
625     {
626         if ( CreateDSBuffer( p_aout, VLC_CODEC_S16N,
627                              i_channels, i_nb_channels, i_rate, b_probe )
628              != VLC_SUCCESS )
629         {
630             return VLC_EGENERIC;
631         }
632         else
633         {
634             *i_format = VLC_CODEC_S16N;
635             return VLC_SUCCESS;
636         }
637     }
638     else
639     {
640         *i_format = VLC_CODEC_FL32;
641         return VLC_SUCCESS;
642     }
643 }
644
645 /*****************************************************************************
646  * DestroyDSBuffer
647  *****************************************************************************
648  * This function destroys the secondary buffer.
649  *****************************************************************************/
650 static void DestroyDSBuffer( audio_output_t *p_aout )
651 {
652     if( p_aout->sys->p_dsbuffer )
653     {
654         IDirectSoundBuffer_Release( p_aout->sys->p_dsbuffer );
655         p_aout->sys->p_dsbuffer = NULL;
656     }
657 }
658
659 /*****************************************************************************
660  * FillBuffer: Fill in one of the direct sound frame buffers.
661  *****************************************************************************
662  * Returns VLC_SUCCESS on success.
663  *****************************************************************************/
664 static int FillBuffer( audio_output_t *p_aout, block_t *p_buffer )
665 {
666     aout_sys_t *p_sys = p_aout->sys;
667
668     size_t towrite = (p_buffer)?p_buffer->i_buffer:DS_BUF_SIZE;
669     void *p_write_position, *p_wrap_around;
670     unsigned long l_bytes1, l_bytes2;
671     uint32_t i_read;
672     size_t i_size;
673     mtime_t i_buf;
674     HRESULT dsresult;
675
676     if( IDirectSoundBuffer_GetCurrentPosition( p_aout->sys->p_dsbuffer, (LPDWORD) &i_read, NULL) ==  DS_OK )
677     {
678         /* Compute the outer interval between the write and read pointers within the ring buffer */
679         i_buf = (mtime_t)i_read - (mtime_t)p_aout->sys->i_write;
680         if( i_buf <= 0 )
681             i_buf += DS_BUF_SIZE;
682     }
683     else
684         i_buf = towrite;
685
686     /* Before copying anything, we have to lock the buffer */
687     dsresult = IDirectSoundBuffer_Lock(
688                 p_sys->p_dsbuffer,         /* DS buffer */
689                 p_aout->sys->i_write,      /* Start offset */
690                 i_buf,                     /* Number of bytes */
691                 &p_write_position,         /* Address of lock start */
692                 &l_bytes1,                 /* Count of bytes locked before wrap around */
693                 &p_wrap_around,            /* Buffer address (if wrap around) */
694                 &l_bytes2,                 /* Count of bytes after wrap around */
695                 0 );                       /* Flags: DSBLOCK_FROMWRITECURSOR is buggy */
696     if( dsresult == DSERR_BUFFERLOST )
697     {
698         IDirectSoundBuffer_Restore( p_sys->p_dsbuffer );
699         dsresult = IDirectSoundBuffer_Lock(
700                                p_sys->p_dsbuffer,
701                                p_aout->sys->i_write,
702                                i_buf,
703                                &p_write_position,
704                                &l_bytes1,
705                                &p_wrap_around,
706                                &l_bytes2,
707                                0 );
708     }
709     if( dsresult != DS_OK )
710     {
711         msg_Warn( p_aout, "cannot lock buffer" );
712         if( p_buffer ) block_Release( p_buffer );
713         return VLC_EGENERIC;
714     }
715
716     if( p_buffer == NULL )
717     {
718         memset( p_write_position, 0, l_bytes1 );
719         memset( p_wrap_around, 0, l_bytes2 );
720     }
721     else
722     {
723         if( p_sys->chans_to_reorder )
724             /* Do the channel reordering here */
725             aout_ChannelReorder( p_buffer->p_buffer, p_buffer->i_buffer,
726                                  p_sys->chans_to_reorder, p_sys->chan_table,
727                                  p_sys->format );
728
729
730         i_size = ( p_buffer->i_buffer < l_bytes1 ) ? p_buffer->i_buffer : l_bytes1;
731         memcpy( p_write_position, p_buffer->p_buffer, i_size );
732         memset( (uint8_t*) p_write_position + i_size, 0, l_bytes1 - i_size );
733
734         if( l_bytes1 < p_buffer->i_buffer)
735         {
736             /* Compute the remaining buffer space to be written */
737             i_buf = i_buf - i_size - (l_bytes1 - i_size);
738             i_size = ( p_buffer->i_buffer - l_bytes1 < l_bytes2 ) ? p_buffer->i_buffer - l_bytes1 : l_bytes2;
739             memcpy( p_wrap_around, p_buffer->p_buffer + l_bytes1, i_size );
740             memset( (uint8_t*) p_wrap_around + i_size, 0, i_buf - i_size );
741         }
742         block_Release( p_buffer );
743     }
744
745     /* Now the data has been copied, unlock the buffer */
746     IDirectSoundBuffer_Unlock( p_sys->p_dsbuffer, p_write_position, l_bytes1,
747                                p_wrap_around, l_bytes2 );
748
749     p_sys->i_write += towrite;
750     p_sys->i_write %= DS_BUF_SIZE;
751
752     return VLC_SUCCESS;
753 }
754
755 typedef struct
756 {
757     unsigned count;
758     char **ids;
759     char **names;
760 } ds_list_t;
761
762 static int CALLBACK DeviceEnumCallback( LPGUID guid, LPCWSTR desc,
763                                         LPCWSTR mod, LPVOID data )
764 {
765     ds_list_t *list = data;
766     OLECHAR buf[48];
767
768     if( StringFromGUID2( guid, buf, 48 ) <= 0 )
769         return true;
770
771     list->count++;
772     list->ids = xrealloc( list->ids, list->count * sizeof(char *) );
773     list->names = xrealloc( list->names, list->count * sizeof(char *) );
774     list->ids[list->count - 1] = FromWide( buf );
775     list->names[list->count - 1] = FromWide( desc );
776     if( list->ids == NULL || list->names == NULL )
777         abort();
778
779     (void) mod;
780     return true;
781 }
782
783 /*****************************************************************************
784  * ReloadDirectXDevices: store the list of devices in preferences
785  *****************************************************************************/
786 static int ReloadDirectXDevices( vlc_object_t *p_this, char const *psz_name,
787                                  char ***values, char ***descs )
788 {
789     ds_list_t list = {
790         .count = 1,
791         .ids = xmalloc(sizeof (char *)),
792         .names = xmalloc(sizeof (char *)),
793     };
794     list.ids[0] = xstrdup("");
795     list.names[0] = xstrdup(_("Default"));
796
797     (void) psz_name;
798
799     HANDLE hdsound_dll = LoadLibrary(_T("DSOUND.DLL"));
800     if( hdsound_dll == NULL )
801     {
802         msg_Warn( p_this, "cannot open DSOUND.DLL" );
803         goto out;
804     }
805
806     /* Get DirectSoundEnumerate */
807     HRESULT (WINAPI *OurDirectSoundEnumerate)(LPDSENUMCALLBACKW, LPVOID) =
808             (void *)GetProcAddress( hdsound_dll, "DirectSoundEnumerateW" );
809     if( OurDirectSoundEnumerate != NULL )
810     {
811         OurDirectSoundEnumerate( DeviceEnumCallback, &list );
812         msg_Dbg( p_this, "found %u devices", list.count );
813     }
814     FreeLibrary(hdsound_dll);
815
816 out:
817     *values = list.ids;
818     *descs = list.names;
819     return list.count;
820 }
821
822 static int DeviceSelect (audio_output_t *aout, const char *id)
823 {
824     var_SetString(aout, "directx-audio-device", (id != NULL) ? id : "");
825     aout_DeviceReport (aout, id);
826     aout_RestartRequest (aout, AOUT_RESTART_OUTPUT);
827     return 0;
828 }
829
830 static int Open(vlc_object_t *obj)
831 {
832     audio_output_t *aout = (audio_output_t *)obj;
833     aout_sys_t *sys = calloc(1, sizeof (*sys));
834     if (unlikely(sys == NULL))
835         return VLC_ENOMEM;
836
837     sys->hdsound_dll = LoadLibrary(_T("DSOUND.DLL"));
838     if (sys->hdsound_dll == NULL)
839     {
840         msg_Warn(aout, "cannot open DSOUND.DLL");
841         free(sys);
842         return VLC_EGENERIC;
843     }
844
845     aout->sys = sys;
846     aout->start = Start;
847     aout->stop = Stop;
848     aout->volume_set = VolumeSet;
849     aout->mute_set = MuteSet;
850     aout->device_select = DeviceSelect;
851
852     /* Volume */
853     sys->volume.volume = var_InheritFloat(aout, "directx-volume");
854     aout_VolumeReport(aout, sys->volume.volume );
855     MuteSet(aout, var_InheritBool(aout, "mute"));
856
857     sys->hnotify_evt = CreateEvent(NULL, FALSE, TRUE, NULL);
858     if( !sys->hnotify_evt )
859     {
860         msg_Err(aout, "cannot create Event");
861         FreeLibrary(sys->hdsound_dll);
862         free(sys);
863         return VLC_EGENERIC;
864     }
865
866     /* DirectSound does not support hot-plug events (unless with WASAPI) */
867     char **ids, **names;
868     int count = ReloadDirectXDevices(obj, NULL, &ids, &names);
869     if (count >= 0)
870     {
871         for (int i = 0; i < count; i++)
872         {
873             aout_HotplugReport(aout, ids[i], names[i]);
874             free(names[i]);
875             free(ids[i]);
876         }
877         free(names);
878         free(ids);
879     }
880
881     char *dev = var_CreateGetNonEmptyString(aout, "directx-audio-device");
882     aout_DeviceReport(aout, dev);
883     free(dev);
884
885     return VLC_SUCCESS;
886 }
887
888 static void Close(vlc_object_t *obj)
889 {
890     audio_output_t *aout = (audio_output_t *)obj;
891     aout_sys_t *sys = aout->sys;
892
893     var_Destroy(aout, "directx-audio-device");
894     CloseHandle(sys->hnotify_evt);
895     FreeLibrary(sys->hdsound_dll); /* free DSOUND.DLL */
896     free(sys);
897 }
898
899 static void Flush ( audio_output_t * aout, bool drain )
900 {
901     IDirectSoundBuffer_Stop( aout->sys->p_dsbuffer );
902     if( !drain )
903         IDirectSoundBuffer_SetCurrentPosition( aout->sys->p_dsbuffer,
904                                                aout->sys->i_write );
905 }
906
907 static void Pause( audio_output_t * aout, bool pause, mtime_t date )
908 {
909     (void) date;
910     if( pause )
911         IDirectSoundBuffer_Stop( aout->sys->p_dsbuffer );
912     else
913         IDirectSoundBuffer_Play( aout->sys->p_dsbuffer, 0, 0, DSBPLAY_LOOPING );
914 }
915
916
917 static int TimeGet( audio_output_t * aout, mtime_t * delay )
918 {
919     uint32_t read;
920     mtime_t size;
921
922     if( IDirectSoundBuffer_GetCurrentPosition( aout->sys->p_dsbuffer, (LPDWORD) &read, NULL) !=  DS_OK )
923         return 1;
924
925     read %= DS_BUF_SIZE;
926
927     size = (mtime_t)aout->sys->i_write - (mtime_t) read;
928     if( size < 0 )
929         size += DS_BUF_SIZE;
930
931     *delay = ( size / aout->sys->i_bytes_per_sample ) * CLOCK_FREQ / aout->sys->i_rate;
932     return 0;
933 }