]> git.sesse.net Git - vlc/blob - modules/audio_output/directx.c
724bb0663bd543b3fc4082dd8d24e0942b70e1e9
[vlc] / modules / audio_output / directx.c
1 /*****************************************************************************
2  * directx.c: Windows DirectX audio output method
3  *****************************************************************************
4  * Copyright (C) 2001-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 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 General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation, Inc.,
21  * 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 #include <vlc_atomic.h>
39
40 #include "windows_audio_common.h"
41
42 #define FRAME_SIZE ((int)p_aout->format.i_rate/20) /* Size in samples */
43
44 /*****************************************************************************
45  * notification_thread_t: DirectX event thread
46  *****************************************************************************/
47 typedef struct notification_thread_t
48 {
49     int i_frame_size;                          /* size in bytes of one frame */
50     int i_write_slot;       /* current write position in our circular buffer */
51
52     mtime_t start_date;
53     HANDLE event;
54
55     vlc_thread_t thread;
56     vlc_atomic_t abort;
57
58 } notification_thread_t;
59
60 /*****************************************************************************
61  * aout_sys_t: directx audio output method descriptor
62  *****************************************************************************
63  * This structure is part of the audio output thread descriptor.
64  * It describes the direct sound specific properties of an audio device.
65  *****************************************************************************/
66 struct aout_sys_t
67 {
68     aout_packet_t       packet;
69     HINSTANCE           hdsound_dll;      /* handle of the opened dsound dll */
70
71     char *              psz_device;              /* user defined device name */
72     LPGUID              p_device_guid;
73
74     LPDIRECTSOUND       p_dsobject;              /* main Direct Sound object */
75     LPDIRECTSOUNDBUFFER p_dsbuffer;   /* the sound buffer we use (direct sound
76                                        * takes care of mixing all the
77                                        * secondary buffers into the primary) */
78     struct
79     {
80         LONG             volume;
81         LONG             mb;
82         bool             mute;
83     } volume;
84
85     notification_thread_t notif;                  /* DirectSoundThread id */
86
87     int      i_frame_size;                     /* Size in bytes of one frame */
88
89     int      i_speaker_setup;                      /* Speaker setup override */
90
91     bool     b_chan_reorder;                /* do we need channel reordering */
92     int      pi_chan_table[AOUT_CHAN_MAX];
93     uint32_t i_channel_mask;
94     uint32_t i_bits_per_sample;
95     uint32_t i_channels;
96 };
97
98 /*****************************************************************************
99  * Local prototypes.
100  *****************************************************************************/
101 static int  OpenAudio  ( vlc_object_t * );
102 static void CloseAudio ( vlc_object_t * );
103 static void Play       ( audio_output_t *, block_t *, mtime_t * );
104 static int  VolumeSet  ( audio_output_t *, float );
105 static int  MuteSet    ( audio_output_t *, bool );
106
107 /* local functions */
108 static void Probe             ( audio_output_t * );
109 static int  InitDirectSound   ( audio_output_t * );
110 static int  CreateDSBuffer    ( audio_output_t *, int, int, int, int, int, bool );
111 static int  CreateDSBufferPCM ( audio_output_t *, vlc_fourcc_t*, int, int, int, bool );
112 static void DestroyDSBuffer   ( audio_output_t * );
113 static void* DirectSoundThread( void * );
114 static int  FillBuffer        ( audio_output_t *, int, block_t * );
115
116 static int ReloadDirectXDevices( vlc_object_t *, char const *,
117                                 vlc_value_t, vlc_value_t, void * );
118
119 /* Speaker setup override options list */
120 static const char *const speaker_list[] = { "Windows default", "Mono", "Stereo",
121                                             "Quad", "5.1", "7.1" };
122
123 /*****************************************************************************
124  * Module descriptor
125  *****************************************************************************/
126 #define DEVICE_TEXT N_("Output device")
127 #define DEVICE_LONGTEXT N_("Select your audio output device")
128
129 #define SPEAKER_TEXT N_("Speaker configuration")
130 #define SPEAKER_LONGTEXT N_("Select speaker configuration you want to use. " \
131     "This option doesn't upmix! So NO e.g. Stereo -> 5.1 conversion." )
132
133 #define VOLUME_TEXT N_("Audio volume")
134 #define VOLUME_LONGTEXT N_("Audio volume in hundredths of decibels (dB).")
135
136 vlc_module_begin ()
137     set_description( N_("DirectX audio output") )
138     set_shortname( "DirectX" )
139     set_capability( "audio output", 100 )
140     set_category( CAT_AUDIO )
141     set_subcategory( SUBCAT_AUDIO_AOUT )
142     add_shortcut( "directx", "aout_directx" )
143
144     add_string( "directx-audio-device", "default",
145              DEVICE_TEXT, DEVICE_LONGTEXT, false )
146         change_string_cb( ReloadDirectXDevices )
147     add_obsolete_string( "directx-audio-device-name")
148     add_bool( "directx-audio-float32", false, FLOAT_TEXT,
149               FLOAT_LONGTEXT, true )
150     add_string( "directx-audio-speaker", "Windows default",
151                  SPEAKER_TEXT, SPEAKER_LONGTEXT, true )
152         change_string_list( speaker_list, speaker_list )
153     add_integer( "directx-volume", DSBVOLUME_MAX,
154                  VOLUME_TEXT, VOLUME_LONGTEXT, true )
155         change_integer_range( DSBVOLUME_MIN, DSBVOLUME_MAX )
156
157     set_callbacks( OpenAudio, CloseAudio )
158 vlc_module_end ()
159
160 /*****************************************************************************
161  * OpenAudio: open the audio device
162  *****************************************************************************
163  * This function opens and setups Direct Sound.
164  *****************************************************************************/
165 static int OpenAudio( vlc_object_t *p_this )
166 {
167     audio_output_t * p_aout = (audio_output_t *)p_this;
168     vlc_value_t val;
169     char * psz_speaker;
170     int i = 0;
171
172     const char * const * ppsz_compare = speaker_list;
173
174     msg_Dbg( p_aout, "Opening DirectSound Audio Output" );
175
176    /* Allocate structure */
177     p_aout->sys = calloc( 1, sizeof( aout_sys_t ) );
178     if( unlikely( p_aout->sys == NULL ) )
179         return VLC_ENOMEM;
180
181     /* Retrieve config values */
182     var_Create( p_aout, "directx-audio-float32",
183                 VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
184     psz_speaker = var_CreateGetString( p_aout, "directx-audio-speaker" );
185
186     while ( *ppsz_compare != NULL )
187     {
188         if ( !strncmp( *ppsz_compare, psz_speaker, strlen(*ppsz_compare) ) )
189         {
190             break;
191         }
192         ppsz_compare++; i++;
193     }
194
195     if ( *ppsz_compare == NULL )
196     {
197         msg_Err( p_aout, "(%s) isn't valid speaker setup option", psz_speaker );
198         msg_Err( p_aout, "Defaulting to Windows default speaker config");
199         i = 0;
200     }
201     free( psz_speaker );
202     p_aout->sys->i_speaker_setup = i;
203
204     /* Initialise DirectSound */
205     if( InitDirectSound( p_aout ) )
206     {
207         msg_Err( p_aout, "cannot initialize DirectSound" );
208         goto error;
209     }
210
211     if( var_Type( p_aout, "audio-device" ) == 0 )
212     {
213         Probe( p_aout );
214     }
215
216     if( var_Get( p_aout, "audio-device", &val ) < 0 )
217     {
218         msg_Err( p_aout, "DirectSound Probe failed()" );
219         goto error;
220     }
221
222     /* Open the device */
223     if( val.i_int == AOUT_VAR_SPDIF )
224     {
225         p_aout->format.i_format = VLC_CODEC_SPDIFL;
226
227         /* Calculate the frame size in bytes */
228         p_aout->format.i_bytes_per_frame = AOUT_SPDIF_SIZE;
229         p_aout->format.i_frame_length = A52_FRAME_NB;
230         p_aout->sys->i_frame_size = p_aout->format.i_bytes_per_frame;
231
232         if( CreateDSBuffer( p_aout, VLC_CODEC_SPDIFL,
233                             p_aout->format.i_physical_channels,
234                             aout_FormatNbChannels( &p_aout->format ),
235                             p_aout->format.i_rate,
236                             p_aout->sys->i_frame_size, false )
237             != VLC_SUCCESS )
238         {
239             msg_Err( p_aout, "cannot open directx audio device" );
240             goto error;
241         }
242
243         aout_PacketInit( p_aout, &p_aout->sys->packet, A52_FRAME_NB );
244     }
245     else
246     {
247         if( val.i_int == AOUT_VAR_5_1 )
248         {
249             p_aout->format.i_physical_channels
250                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
251                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
252                    | AOUT_CHAN_LFE;
253         }
254         else if( val.i_int == AOUT_VAR_7_1 )
255         {
256                     p_aout->format.i_physical_channels
257                         = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
258                            | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
259                            | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
260                            | AOUT_CHAN_LFE;
261         }
262         else if( val.i_int == AOUT_VAR_3F2R )
263         {
264             p_aout->format.i_physical_channels
265                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
266                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
267         }
268         else if( val.i_int == AOUT_VAR_2F2R )
269         {
270             p_aout->format.i_physical_channels
271                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
272                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
273         }
274         else if( val.i_int == AOUT_VAR_MONO )
275         {
276             p_aout->format.i_physical_channels = AOUT_CHAN_CENTER;
277         }
278         else
279         {
280             p_aout->format.i_physical_channels
281                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
282         }
283
284         if( CreateDSBufferPCM( p_aout, &p_aout->format.i_format,
285                                p_aout->format.i_physical_channels,
286                                aout_FormatNbChannels( &p_aout->format ),
287                                p_aout->format.i_rate, false )
288             != VLC_SUCCESS )
289         {
290             msg_Err( p_aout, "cannot open directx audio device" );
291             goto error;
292         }
293
294         /* Calculate the frame size in bytes */
295         aout_FormatPrepare( &p_aout->format );
296         aout_PacketInit( p_aout, &p_aout->sys->packet, FRAME_SIZE );
297     }
298
299     p_aout->sys->volume.volume = -1;
300
301     /* Now we need to setup our DirectSound play notification structure */
302     vlc_atomic_set(&p_aout->sys->notif.abort, 0);
303     p_aout->sys->notif.event = CreateEvent( 0, FALSE, FALSE, 0 );
304     if( unlikely(p_aout->sys->notif.event == NULL) )
305         abort();
306     p_aout->sys->notif.i_frame_size =  p_aout->sys->i_frame_size;
307
308     /* then launch the notification thread */
309     msg_Dbg( p_aout, "creating DirectSoundThread" );
310     if( vlc_clone( &p_aout->sys->notif.thread, DirectSoundThread, p_aout,
311                    VLC_THREAD_PRIORITY_HIGHEST ) )
312     {
313         msg_Err( p_aout, "cannot create DirectSoundThread" );
314         CloseHandle( p_aout->sys->notif.event );
315         p_aout->sys->notif.event = NULL;
316         aout_PacketDestroy( p_aout );
317         goto error;
318     }
319
320     p_aout->pf_play = Play;
321     p_aout->pf_pause = aout_PacketPause;
322     p_aout->pf_flush = aout_PacketFlush;
323
324     /* Volume */
325     if( val.i_int == AOUT_VAR_SPDIF )
326     {
327         p_aout->volume_set = NULL;
328         p_aout->mute_set = NULL;
329     }
330     else
331     {
332         LONG mb = var_InheritInteger( p_aout, "directx-volume" );
333
334         p_aout->volume_set = VolumeSet;
335         p_aout->mute_set = MuteSet;
336         p_aout->sys->volume.mb = mb;
337         aout_VolumeReport( p_aout, cbrtf(powf(10.f, ((float)mb) / 2000.f)) );
338         MuteSet( p_aout, var_InheritBool( p_aout, "mute" ) );
339     }
340     return VLC_SUCCESS;
341
342  error:
343     CloseAudio( VLC_OBJECT(p_aout) );
344     return VLC_EGENERIC;
345 }
346
347 /*****************************************************************************
348  * Probe: probe the audio device for available formats and channels
349  *****************************************************************************/
350 static void Probe( audio_output_t * p_aout )
351 {
352     vlc_value_t val, text;
353     vlc_fourcc_t i_format;
354     unsigned int i_physical_channels;
355     DWORD ui_speaker_config;
356     bool is_default_output_set = false;
357
358     var_Create( p_aout, "audio-device", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
359     text.psz_string = _("Audio Device");
360     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
361
362     /* Test for 5.1 support */
363     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
364                           AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
365                           AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE;
366     if( p_aout->format.i_physical_channels == i_physical_channels )
367     {
368         if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 6,
369                                p_aout->format.i_rate, true )
370             == VLC_SUCCESS )
371         {
372             val.i_int = AOUT_VAR_5_1;
373             text.psz_string = (char*) "5.1";
374             var_Change( p_aout, "audio-device",
375                         VLC_VAR_ADDCHOICE, &val, &text );
376             var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
377             is_default_output_set = true;
378             msg_Dbg( p_aout, "device supports 5.1 channels" );
379         }
380     }
381
382     /* Test for 7.1 support */
383     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
384                              AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
385                              AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT |
386                              AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE;
387     if( p_aout->format.i_physical_channels == i_physical_channels )
388     {
389         if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 8,
390                                   p_aout->format.i_rate, true )
391             == VLC_SUCCESS )
392         {
393             val.i_int = AOUT_VAR_7_1;
394             text.psz_string = (char*) "7.1";
395             var_Change( p_aout, "audio-device",
396                         VLC_VAR_ADDCHOICE, &val, &text );
397             var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
398             is_default_output_set = true;
399             msg_Dbg( p_aout, "device supports 7.1 channels" );
400         }
401     }
402
403     /* Test for 3 Front 2 Rear support */
404     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
405                           AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
406                           AOUT_CHAN_REARRIGHT;
407     if( p_aout->format.i_physical_channels == i_physical_channels )
408     {
409         if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 5,
410                                p_aout->format.i_rate, true )
411             == VLC_SUCCESS )
412         {
413             val.i_int = AOUT_VAR_3F2R;
414             text.psz_string = _("3 Front 2 Rear");
415             var_Change( p_aout, "audio-device",
416                         VLC_VAR_ADDCHOICE, &val, &text );
417             if(!is_default_output_set)
418             {
419                 var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
420                 is_default_output_set = true;
421             }
422             msg_Dbg( p_aout, "device supports 5 channels" );
423         }
424     }
425
426     /* Test for 2 Front 2 Rear support */
427     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
428                           AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
429     if( ( p_aout->format.i_physical_channels & i_physical_channels )
430         == i_physical_channels )
431     {
432         if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 4,
433                                p_aout->format.i_rate, true )
434             == VLC_SUCCESS )
435         {
436             val.i_int = AOUT_VAR_2F2R;
437             text.psz_string = _("2 Front 2 Rear");
438             var_Change( p_aout, "audio-device",
439                         VLC_VAR_ADDCHOICE, &val, &text );
440             if(!is_default_output_set)
441             {
442                 var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
443                 is_default_output_set = true;
444             }
445             msg_Dbg( p_aout, "device supports 4 channels" );
446         }
447     }
448
449     /* Test for stereo support */
450     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
451     if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 2,
452                            p_aout->format.i_rate, true )
453         == VLC_SUCCESS )
454     {
455         val.i_int = AOUT_VAR_STEREO;
456         text.psz_string = _("Stereo");
457         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
458         if(!is_default_output_set)
459         {
460             var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
461             is_default_output_set = true;
462             msg_Dbg( p_aout, "device supports 2 channels (DEFAULT!)" );
463         }
464         else msg_Dbg( p_aout, "device supports 2 channels" );
465     }
466
467     /* Test for mono support */
468     i_physical_channels = AOUT_CHAN_CENTER;
469     if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 1,
470                            p_aout->format.i_rate, true )
471         == VLC_SUCCESS )
472     {
473         val.i_int = AOUT_VAR_MONO;
474         text.psz_string = _("Mono");
475         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
476         msg_Dbg( p_aout, "device supports 1 channel" );
477     }
478
479     /* Check the speaker configuration to determine which channel config should
480      * be the default */
481     if FAILED( IDirectSound_GetSpeakerConfig( p_aout->sys->p_dsobject,
482                                               &ui_speaker_config ) )
483     {
484         ui_speaker_config = DSSPEAKER_STEREO;
485         msg_Dbg( p_aout, "GetSpeakerConfig failed" );
486     }
487     switch( DSSPEAKER_CONFIG(ui_speaker_config) )
488     {
489     case DSSPEAKER_7POINT1:
490         msg_Dbg( p_aout, "Windows says your SpeakerConfig is 7.1" );
491         val.i_int = AOUT_VAR_7_1;
492         break;
493     case DSSPEAKER_5POINT1:
494         msg_Dbg( p_aout, "Windows says your SpeakerConfig is 5.1" );
495         val.i_int = AOUT_VAR_5_1;
496         break;
497     case DSSPEAKER_QUAD:
498         msg_Dbg( p_aout, "Windows says your SpeakerConfig is Quad" );
499         val.i_int = AOUT_VAR_2F2R;
500         break;
501 #if 0 /* Lots of people just get their settings wrong and complain that
502        * this is a problem with VLC so just don't ever set mono by default. */
503     case DSSPEAKER_MONO:
504         val.i_int = AOUT_VAR_MONO;
505         break;
506 #endif
507     case DSSPEAKER_SURROUND:
508         msg_Dbg( p_aout, "Windows says your SpeakerConfig is surround" );
509     case DSSPEAKER_STEREO:
510         msg_Dbg( p_aout, "Windows says your SpeakerConfig is stereo" );
511     default:
512         /* If nothing else is found, choose stereo output */
513         val.i_int = AOUT_VAR_STEREO;
514         break;
515     }
516
517     /* Check if we want to override speaker config */
518     switch( p_aout->sys->i_speaker_setup )
519     {
520     case 0: /* Default value aka Windows default speaker setup */
521         break;
522     case 1: /* Mono */
523         msg_Dbg( p_aout, "SpeakerConfig is forced to Mono" );
524         val.i_int = AOUT_VAR_MONO;
525         break;
526     case 2: /* Stereo */
527         msg_Dbg( p_aout, "SpeakerConfig is forced to Stereo" );
528         val.i_int = AOUT_VAR_STEREO;
529         break;
530     case 3: /* Quad */
531         msg_Dbg( p_aout, "SpeakerConfig is forced to Quad" );
532         val.i_int = AOUT_VAR_2F2R;
533         break;
534     case 4: /* 5.1 */
535         msg_Dbg( p_aout, "SpeakerConfig is forced to 5.1" );
536         val.i_int = AOUT_VAR_5_1;
537         break;
538     case 5: /* 7.1 */
539         msg_Dbg( p_aout, "SpeakerConfig is forced to 7.1" );
540         val.i_int = AOUT_VAR_7_1;
541         break;
542     default:
543         msg_Dbg( p_aout, "SpeakerConfig is forced to non-existing value" );
544         break;
545     }
546
547     var_Set( p_aout, "audio-device", val );
548
549     /* Test for SPDIF support */
550     if ( AOUT_FMT_SPDIF( &p_aout->format ) )
551     {
552         if( CreateDSBuffer( p_aout, VLC_CODEC_SPDIFL,
553                             p_aout->format.i_physical_channels,
554                             aout_FormatNbChannels( &p_aout->format ),
555                             p_aout->format.i_rate,
556                             AOUT_SPDIF_SIZE, true )
557             == VLC_SUCCESS )
558         {
559             msg_Dbg( p_aout, "device supports A/52 over S/PDIF" );
560             val.i_int = AOUT_VAR_SPDIF;
561             text.psz_string = _("A/52 over S/PDIF");
562             var_Change( p_aout, "audio-device",
563                         VLC_VAR_ADDCHOICE, &val, &text );
564             if( var_InheritBool( p_aout, "spdif" ) )
565                 var_Set( p_aout, "audio-device", val );
566         }
567     }
568
569     var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
570     if( val.i_int <= 0 )
571     {
572         /* Probe() has failed. */
573         var_Destroy( p_aout, "audio-device" );
574         return;
575     }
576
577     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
578 }
579
580 /*****************************************************************************
581  * Play: we'll start playing the directsound buffer here because at least here
582  *       we know the first buffer has been put in the aout fifo and we also
583  *       know its date.
584  *****************************************************************************/
585 static void Play( audio_output_t *p_aout, block_t *p_buffer,
586                   mtime_t *restrict drift )
587 {
588     /* get the playing date of the first aout buffer */
589     p_aout->sys->notif.start_date = p_buffer->i_pts;
590
591     /* fill in the first samples (zeroes) */
592     FillBuffer( p_aout, 0, NULL );
593
594     /* wake up the audio output thread */
595     SetEvent( p_aout->sys->notif.event );
596
597     aout_PacketPlay( p_aout, p_buffer, drift );
598     p_aout->pf_play = aout_PacketPlay;
599 }
600
601 static int VolumeSet( audio_output_t *p_aout, float vol )
602 {
603     aout_sys_t *sys = p_aout->sys;
604     int ret = 0;
605
606     /* Convert UI volume to linear factor (cube) */
607     vol = vol * vol * vol;
608
609     /* millibels from linear amplification */
610     LONG mb = lroundf(2000.f * log10f(vol));
611
612     /* Clamp to allowed DirectSound range */
613     static_assert( DSBVOLUME_MIN < DSBVOLUME_MAX, "DSBVOLUME_* confused" );
614     if( mb >= DSBVOLUME_MAX )
615     {
616         mb = DSBVOLUME_MAX;
617         ret = -1;
618     }
619     if( mb <= DSBVOLUME_MIN )
620         mb = DSBVOLUME_MIN;
621
622     sys->volume.mb = mb;
623     if (!sys->volume.mute)
624         InterlockedExchange(&sys->volume.volume, mb);
625
626     /* Convert back to UI volume */
627     vol = cbrtf(powf(10.f, ((float)mb) / 2000.f));
628     aout_VolumeReport( p_aout, vol );
629
630     if( var_InheritBool( p_aout, "volume-save" ) )
631         config_PutInt( p_aout, "directx-volume", mb );
632     return ret;
633 }
634
635 static int MuteSet( audio_output_t *p_aout, bool mute )
636 {
637     aout_sys_t *sys = p_aout->sys;
638
639     sys->volume.mute = mute;
640     InterlockedExchange(&sys->volume.volume,
641                         mute ? DSBVOLUME_MIN : sys->volume.mb);
642
643     aout_MuteReport( p_aout, mute );
644     return 0;
645 }
646
647 /*****************************************************************************
648  * CloseAudio: close the audio device
649  *****************************************************************************/
650 static void CloseAudio( vlc_object_t *p_this )
651 {
652     audio_output_t * p_aout = (audio_output_t *)p_this;
653     aout_sys_t *p_sys = p_aout->sys;
654
655     msg_Dbg( p_aout, "closing audio device" );
656
657     /* kill the position notification thread, if any */
658     if( p_sys->notif.event != NULL )
659     {
660         vlc_atomic_set(&p_aout->sys->notif.abort, 1);
661         /* wake up the audio thread if needed */
662         if( p_aout->pf_play == Play )
663             SetEvent( p_sys->notif.event );
664
665         vlc_join( p_sys->notif.thread, NULL );
666         CloseHandle( p_sys->notif.event );
667         aout_PacketDestroy( p_aout );
668     }
669
670     /* release the secondary buffer */
671     DestroyDSBuffer( p_aout );
672
673     /* finally release the DirectSound object */
674     if( p_sys->p_dsobject ) IDirectSound_Release( p_sys->p_dsobject );
675
676     /* free DSOUND.DLL */
677     if( p_sys->hdsound_dll ) FreeLibrary( p_sys->hdsound_dll );
678
679     free( p_aout->sys->p_device_guid );
680     free( p_sys );
681 }
682
683 /*****************************************************************************
684  * CallBackDirectSoundEnum: callback to enumerate available devices
685  *****************************************************************************/
686 static int CALLBACK CallBackDirectSoundEnum( LPGUID p_guid, LPCWSTR psz_desc,
687                                              LPCWSTR psz_mod, LPVOID _p_aout )
688 {
689     VLC_UNUSED( psz_mod );
690
691     audio_output_t *p_aout = (audio_output_t *)_p_aout;
692
693     char *psz_device = FromWide( psz_desc );
694     msg_Dbg( p_aout, "found device: %s", psz_device );
695
696     if( p_aout->sys->psz_device &&
697         !strcmp(p_aout->sys->psz_device, psz_device) && p_guid )
698     {
699         /* Use the device corresponding to psz_device */
700         p_aout->sys->p_device_guid = malloc( sizeof( GUID ) );
701         *p_aout->sys->p_device_guid = *p_guid;
702         msg_Dbg( p_aout, "using device: %s", psz_device );
703     }
704     else
705     {
706         /* If no default device has been selected, chose the first one */
707         if( !p_aout->sys->psz_device && p_guid )
708         {
709             p_aout->sys->psz_device = strdup( psz_device );
710             p_aout->sys->p_device_guid = malloc( sizeof( GUID ) );
711             *p_aout->sys->p_device_guid = *p_guid;
712             msg_Dbg( p_aout, "using device: %s", psz_device );
713         }
714     }
715
716     free( psz_device );
717     return true;
718 }
719
720 /*****************************************************************************
721  * InitDirectSound: handle all the gory details of DirectSound initialisation
722  *****************************************************************************/
723 static int InitDirectSound( audio_output_t *p_aout )
724 {
725     HRESULT (WINAPI *OurDirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
726     HRESULT (WINAPI *OurDirectSoundEnumerate)(LPDSENUMCALLBACKW, LPVOID);
727
728     p_aout->sys->hdsound_dll = LoadLibrary("DSOUND.DLL");
729     if( p_aout->sys->hdsound_dll == NULL )
730     {
731         msg_Warn( p_aout, "cannot open DSOUND.DLL" );
732         goto error;
733     }
734
735     OurDirectSoundCreate = (void *)
736         GetProcAddress( p_aout->sys->hdsound_dll,
737                         "DirectSoundCreate" );
738     if( OurDirectSoundCreate == NULL )
739     {
740         msg_Warn( p_aout, "GetProcAddress FAILED" );
741         goto error;
742     }
743
744     /* Get DirectSoundEnumerate */
745     OurDirectSoundEnumerate = (void *)
746        GetProcAddress( p_aout->sys->hdsound_dll,
747                        "DirectSoundEnumerateW" );
748     if( OurDirectSoundEnumerate )
749     {
750         p_aout->sys->psz_device = var_InheritString(p_aout, "directx-audio-device");
751         /* Attempt enumeration */
752         if( FAILED( OurDirectSoundEnumerate( CallBackDirectSoundEnum,
753                                              p_aout ) ) )
754         {
755             msg_Dbg( p_aout, "enumeration of DirectSound devices failed" );
756         }
757     }
758
759     /* Create the direct sound object */
760     if FAILED( OurDirectSoundCreate( p_aout->sys->p_device_guid,
761                                      &p_aout->sys->p_dsobject,
762                                      NULL ) )
763     {
764         msg_Warn( p_aout, "cannot create a direct sound device" );
765         goto error;
766     }
767
768     /* Set DirectSound Cooperative level, ie what control we want over Windows
769      * sound device. In our case, DSSCL_EXCLUSIVE means that we can modify the
770      * settings of the primary buffer, but also that only the sound of our
771      * application will be hearable when it will have the focus.
772      * !!! (this is not really working as intended yet because to set the
773      * cooperative level you need the window handle of your application, and
774      * I don't know of any easy way to get it. Especially since we might play
775      * sound without any video, and so what window handle should we use ???
776      * The hack for now is to use the Desktop window handle - it seems to be
777      * working */
778     if( IDirectSound_SetCooperativeLevel( p_aout->sys->p_dsobject,
779                                           GetDesktopWindow(),
780                                           DSSCL_EXCLUSIVE) )
781     {
782         msg_Warn( p_aout, "cannot set direct sound cooperative level" );
783     }
784
785     return VLC_SUCCESS;
786
787  error:
788     p_aout->sys->p_dsobject = NULL;
789     if( p_aout->sys->hdsound_dll )
790     {
791         FreeLibrary( p_aout->sys->hdsound_dll );
792         p_aout->sys->hdsound_dll = NULL;
793     }
794     return VLC_EGENERIC;
795
796 }
797
798 /*****************************************************************************
799  * CreateDSBuffer: Creates a direct sound buffer of the required format.
800  *****************************************************************************
801  * This function creates the buffer we'll use to play audio.
802  * In DirectSound there are two kinds of buffers:
803  * - the primary buffer: which is the actual buffer that the soundcard plays
804  * - the secondary buffer(s): these buffers are the one actually used by
805  *    applications and DirectSound takes care of mixing them into the primary.
806  *
807  * Once you create a secondary buffer, you cannot change its format anymore so
808  * you have to release the current one and create another.
809  *****************************************************************************/
810 static int CreateDSBuffer( audio_output_t *p_aout, int i_format,
811                            int i_channels, int i_nb_channels, int i_rate,
812                            int i_bytes_per_frame, bool b_probe )
813 {
814     WAVEFORMATEXTENSIBLE waveformat;
815     DSBUFFERDESC         dsbdesc;
816
817     /* First set the sound buffer format */
818     waveformat.dwChannelMask = 0;
819     for( unsigned i = 0; pi_vlc_chan_order_wg4[i]; i++ )
820         if( i_channels & pi_vlc_chan_order_wg4[i] )
821             waveformat.dwChannelMask |= pi_channels_in[i];
822
823     switch( i_format )
824     {
825     case VLC_CODEC_SPDIFL:
826         i_nb_channels = 2;
827         /* To prevent channel re-ordering */
828         waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
829         waveformat.Format.wBitsPerSample = 16;
830         waveformat.Samples.wValidBitsPerSample =
831             waveformat.Format.wBitsPerSample;
832         waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
833         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
834         break;
835
836     case VLC_CODEC_FL32:
837         waveformat.Format.wBitsPerSample = sizeof(float) * 8;
838         waveformat.Samples.wValidBitsPerSample =
839             waveformat.Format.wBitsPerSample;
840         waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
841         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
842         break;
843
844     case VLC_CODEC_S16L:
845         waveformat.Format.wBitsPerSample = 16;
846         waveformat.Samples.wValidBitsPerSample =
847             waveformat.Format.wBitsPerSample;
848         waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
849         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_PCM;
850         break;
851     }
852
853     waveformat.Format.nChannels = i_nb_channels;
854     waveformat.Format.nSamplesPerSec = i_rate;
855     waveformat.Format.nBlockAlign =
856         waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
857     waveformat.Format.nAvgBytesPerSec =
858         waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;
859
860     p_aout->sys->i_bits_per_sample = waveformat.Format.wBitsPerSample;
861     p_aout->sys->i_channels = i_nb_channels;
862
863     /* Then fill in the direct sound descriptor */
864     memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
865     dsbdesc.dwSize = sizeof(DSBUFFERDESC);
866     dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2/* Better position accuracy */
867                     | DSBCAPS_GLOBALFOCUS       /* Allows background playing */
868                     | DSBCAPS_CTRLVOLUME;       /* Allows volume control */
869
870     /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
871     if( i_nb_channels <= 2 )
872     {
873         waveformat.Format.cbSize = 0;
874     }
875     else
876     {
877         waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
878         waveformat.Format.cbSize =
879             sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
880
881         /* Needed for 5.1 on emu101k */
882         dsbdesc.dwFlags |= DSBCAPS_LOCHARDWARE;
883     }
884
885     dsbdesc.dwBufferBytes = FRAMES_NUM * i_bytes_per_frame;   /* buffer size */
886     dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&waveformat;
887
888     if FAILED( IDirectSound_CreateSoundBuffer(
889                    p_aout->sys->p_dsobject, &dsbdesc,
890                    &p_aout->sys->p_dsbuffer, NULL) )
891     {
892         if( dsbdesc.dwFlags & DSBCAPS_LOCHARDWARE )
893         {
894             /* Try without DSBCAPS_LOCHARDWARE */
895             dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE;
896             if FAILED( IDirectSound_CreateSoundBuffer(
897                    p_aout->sys->p_dsobject, &dsbdesc,
898                    &p_aout->sys->p_dsbuffer, NULL) )
899             {
900                 return VLC_EGENERIC;
901             }
902             if( !b_probe )
903                 msg_Dbg( p_aout, "couldn't use hardware sound buffer" );
904         }
905         else
906         {
907             return VLC_EGENERIC;
908         }
909     }
910
911     /* Stop here if we were just probing */
912     if( b_probe )
913     {
914         IDirectSoundBuffer_Release( p_aout->sys->p_dsbuffer );
915         p_aout->sys->p_dsbuffer = NULL;
916         return VLC_SUCCESS;
917     }
918
919     p_aout->sys->i_frame_size = i_bytes_per_frame;
920     p_aout->sys->i_channel_mask = waveformat.dwChannelMask;
921     p_aout->sys->b_chan_reorder =
922         aout_CheckChannelReorder( pi_channels_in, pi_channels_out,
923                                   waveformat.dwChannelMask, i_nb_channels,
924                                   p_aout->sys->pi_chan_table );
925
926     if( p_aout->sys->b_chan_reorder )
927     {
928         msg_Dbg( p_aout, "channel reordering needed" );
929     }
930
931     return VLC_SUCCESS;
932 }
933
934 /*****************************************************************************
935  * CreateDSBufferPCM: creates a PCM direct sound buffer.
936  *****************************************************************************
937  * We first try to create a WAVE_FORMAT_IEEE_FLOAT buffer if supported by
938  * the hardware, otherwise we create a WAVE_FORMAT_PCM buffer.
939  ****************************************************************************/
940 static int CreateDSBufferPCM( audio_output_t *p_aout, vlc_fourcc_t *i_format,
941                               int i_channels, int i_nb_channels, int i_rate,
942                               bool b_probe )
943 {
944     /* Float32 audio samples are not supported for 5.1 output on the emu101k */
945     if( !var_GetBool( p_aout, "directx-audio-float32" ) ||
946         i_nb_channels > 2 ||
947         CreateDSBuffer( p_aout, VLC_CODEC_FL32,
948                         i_channels, i_nb_channels, i_rate,
949                         FRAME_SIZE * 4 * i_nb_channels, b_probe )
950         != VLC_SUCCESS )
951     {
952         if ( CreateDSBuffer( p_aout, VLC_CODEC_S16L,
953                              i_channels, i_nb_channels, i_rate,
954                              FRAME_SIZE * 2 * i_nb_channels, b_probe )
955              != VLC_SUCCESS )
956         {
957             return VLC_EGENERIC;
958         }
959         else
960         {
961             *i_format = VLC_CODEC_S16L;
962             return VLC_SUCCESS;
963         }
964     }
965     else
966     {
967         *i_format = VLC_CODEC_FL32;
968         return VLC_SUCCESS;
969     }
970 }
971
972 /*****************************************************************************
973  * DestroyDSBuffer
974  *****************************************************************************
975  * This function destroys the secondary buffer.
976  *****************************************************************************/
977 static void DestroyDSBuffer( audio_output_t *p_aout )
978 {
979     if( p_aout->sys->p_dsbuffer )
980     {
981         IDirectSoundBuffer_Release( p_aout->sys->p_dsbuffer );
982         p_aout->sys->p_dsbuffer = NULL;
983     }
984 }
985
986 /*****************************************************************************
987  * FillBuffer: Fill in one of the direct sound frame buffers.
988  *****************************************************************************
989  * Returns VLC_SUCCESS on success.
990  *****************************************************************************/
991 static int FillBuffer( audio_output_t *p_aout, int i_frame, block_t *p_buffer )
992 {
993     aout_sys_t *p_sys = p_aout->sys;
994     notification_thread_t *p_notif = &p_sys->notif;
995     void *p_write_position, *p_wrap_around;
996     unsigned long l_bytes1, l_bytes2;
997     HRESULT dsresult;
998
999     /* Before copying anything, we have to lock the buffer */
1000     dsresult = IDirectSoundBuffer_Lock(
1001                 p_sys->p_dsbuffer,                              /* DS buffer */
1002                 i_frame * p_notif->i_frame_size,             /* Start offset */
1003                 p_notif->i_frame_size,                    /* Number of bytes */
1004                 &p_write_position,                  /* Address of lock start */
1005                 &l_bytes1,       /* Count of bytes locked before wrap around */
1006                 &p_wrap_around,           /* Buffer address (if wrap around) */
1007                 &l_bytes2,               /* Count of bytes after wrap around */
1008                 0 );                                                /* Flags */
1009     if( dsresult == DSERR_BUFFERLOST )
1010     {
1011         IDirectSoundBuffer_Restore( p_sys->p_dsbuffer );
1012         dsresult = IDirectSoundBuffer_Lock(
1013                                p_sys->p_dsbuffer,
1014                                i_frame * p_notif->i_frame_size,
1015                                p_notif->i_frame_size,
1016                                &p_write_position,
1017                                &l_bytes1,
1018                                &p_wrap_around,
1019                                &l_bytes2,
1020                                0 );
1021     }
1022     if( dsresult != DS_OK )
1023     {
1024         msg_Warn( p_aout, "cannot lock buffer" );
1025         if( p_buffer ) block_Release( p_buffer );
1026         return VLC_EGENERIC;
1027     }
1028
1029     if( p_buffer == NULL )
1030     {
1031         memset( p_write_position, 0, l_bytes1 );
1032     }
1033     else
1034     {
1035         if( p_sys->b_chan_reorder )
1036         {
1037             /* Do the channel reordering here */
1038             aout_ChannelReorder( p_buffer->p_buffer, p_buffer->i_buffer,
1039                                  p_sys->i_channels, p_sys->pi_chan_table,
1040                                  p_sys->i_bits_per_sample );
1041         }
1042
1043         memcpy( p_write_position, p_buffer->p_buffer, l_bytes1 );
1044         block_Release( p_buffer );
1045     }
1046
1047     /* Now the data has been copied, unlock the buffer */
1048     IDirectSoundBuffer_Unlock( p_sys->p_dsbuffer, p_write_position, l_bytes1,
1049                                p_wrap_around, l_bytes2 );
1050
1051     p_notif->i_write_slot = (i_frame + 1) % FRAMES_NUM;
1052     return VLC_SUCCESS;
1053 }
1054
1055 /*****************************************************************************
1056  * DirectSoundThread: this thread will capture play notification events.
1057  *****************************************************************************
1058  * We use this thread to emulate a callback mechanism. The thread probes for
1059  * event notification and fills up the DS secondary buffer when needed.
1060  *****************************************************************************/
1061 static void* DirectSoundThread( void *data )
1062 {
1063     audio_output_t *p_aout = (audio_output_t *)data;
1064     notification_thread_t *p_notif = &p_aout->sys->notif;
1065     mtime_t last_time;
1066
1067     msg_Dbg( p_aout, "DirectSoundThread ready" );
1068
1069     /* Wait here until Play() is called */
1070     WaitForSingleObject( p_notif->event, INFINITE );
1071
1072     if( !vlc_atomic_get( &p_notif->abort) )
1073     {
1074         HRESULT dsresult;
1075         mwait( p_notif->start_date - AOUT_MAX_PTS_ADVANCE / 2 );
1076
1077         /* start playing the buffer */
1078         dsresult = IDirectSoundBuffer_Play( p_aout->sys->p_dsbuffer,
1079                                         0,                         /* Unused */
1080                                         0,                         /* Unused */
1081                                         DSBPLAY_LOOPING );          /* Flags */
1082         if( dsresult == DSERR_BUFFERLOST )
1083         {
1084             IDirectSoundBuffer_Restore( p_aout->sys->p_dsbuffer );
1085             dsresult = IDirectSoundBuffer_Play(
1086                                             p_aout->sys->p_dsbuffer,
1087                                             0,                     /* Unused */
1088                                             0,                     /* Unused */
1089                                             DSBPLAY_LOOPING );      /* Flags */
1090         }
1091         if( dsresult != DS_OK )
1092         {
1093             msg_Err( p_aout, "cannot start playing buffer" );
1094         }
1095     }
1096     last_time = mdate();
1097
1098     while( !vlc_atomic_get( &p_notif->abort ) )
1099     {
1100         DWORD l_read;
1101         int l_queued = 0, l_free_slots;
1102         unsigned i_frame_siz = p_aout->sys->packet.samples;
1103         mtime_t mtime = mdate();
1104         int i;
1105
1106         /* Update volume if required */
1107         LONG volume = InterlockedExchange( &p_aout->sys->volume.volume, -1 );
1108         if( unlikely(volume != -1) )
1109             IDirectSoundBuffer_SetVolume( p_aout->sys->p_dsbuffer, volume );
1110
1111         /*
1112          * Fill in as much audio data as we can in our circular buffer
1113          */
1114
1115         /* Find out current play position */
1116         if FAILED( IDirectSoundBuffer_GetCurrentPosition(
1117                    p_aout->sys->p_dsbuffer, &l_read, NULL ) )
1118         {
1119             msg_Err( p_aout, "GetCurrentPosition() failed!" );
1120             l_read = 0;
1121         }
1122
1123         /* Detect underruns */
1124         if( l_queued && mtime - last_time >
1125             INT64_C(1000000) * l_queued / p_aout->format.i_rate )
1126         {
1127             msg_Dbg( p_aout, "detected underrun!" );
1128         }
1129         last_time = mtime;
1130
1131         /* Try to fill in as many frame buffers as possible */
1132         l_read /= (p_aout->format.i_bytes_per_frame /
1133             p_aout->format.i_frame_length);
1134         l_queued = p_notif->i_write_slot * i_frame_siz - l_read;
1135         if( l_queued < 0 ) l_queued += (i_frame_siz * FRAMES_NUM);
1136         l_free_slots = (FRAMES_NUM * i_frame_siz - l_queued) / i_frame_siz;
1137
1138         for( i = 0; i < l_free_slots; i++ )
1139         {
1140             block_t *p_buffer = aout_PacketNext( p_aout,
1141                 mtime + INT64_C(1000000) * (i * i_frame_siz + l_queued) /
1142                 p_aout->format.i_rate );
1143
1144             /* If there is no audio data available and we have some buffered
1145              * already, then just wait for the next time */
1146             if( !p_buffer && (i || l_queued / i_frame_siz) ) break;
1147
1148             if( FillBuffer( p_aout, p_notif->i_write_slot % FRAMES_NUM,
1149                             p_buffer ) != VLC_SUCCESS ) break;
1150         }
1151
1152         /* Sleep a reasonable amount of time */
1153         l_queued += (i * i_frame_siz);
1154         msleep( INT64_C(1000000) * l_queued / p_aout->format.i_rate / 2 );
1155     }
1156
1157     /* make sure the buffer isn't playing */
1158     IDirectSoundBuffer_Stop( p_aout->sys->p_dsbuffer );
1159
1160     msg_Dbg( p_aout, "DirectSoundThread exiting" );
1161     return NULL;
1162 }
1163
1164 /*****************************************************************************
1165  * CallBackConfigNBEnum: callback to get the number of available devices
1166  *****************************************************************************/
1167 static int CALLBACK CallBackConfigNBEnum( LPGUID p_guid, LPCWSTR psz_desc,
1168                                              LPCWSTR psz_mod, LPVOID p_nb )
1169 {
1170     VLC_UNUSED( psz_mod ); VLC_UNUSED( psz_desc ); VLC_UNUSED( p_guid );
1171
1172     int * a = (int *)p_nb;
1173     (*a)++;
1174     return true;
1175 }
1176
1177 /*****************************************************************************
1178  * CallBackConfigEnum: callback to add available devices to the preferences list
1179  *****************************************************************************/
1180 static int CALLBACK CallBackConfigEnum( LPGUID p_guid, LPCWSTR psz_desc,
1181                                              LPCWSTR psz_mod, LPVOID _p_item )
1182 {
1183     VLC_UNUSED( psz_mod ); VLC_UNUSED( p_guid );
1184
1185     module_config_t *p_item = (module_config_t *) _p_item;
1186
1187     p_item->ppsz_list[p_item->i_list] = FromWide( psz_desc );
1188     p_item->ppsz_list_text[p_item->i_list] = FromWide( psz_desc );
1189     p_item->i_list++;
1190     return true;
1191 }
1192
1193 /*****************************************************************************
1194  * ReloadDirectXDevices: store the list of devices in preferences
1195  *****************************************************************************/
1196 static int ReloadDirectXDevices( vlc_object_t *p_this, char const *psz_name,
1197                                  vlc_value_t newval, vlc_value_t oldval, void *data )
1198 {
1199     VLC_UNUSED( newval ); VLC_UNUSED( oldval ); VLC_UNUSED( data );
1200
1201     module_config_t *p_item = config_FindConfig( p_this, psz_name );
1202     if( !p_item ) return VLC_SUCCESS;
1203
1204     /* Clear-up the current list */
1205     if( p_item->i_list )
1206     {
1207         for( int i = 0; i < p_item->i_list; i++ )
1208         {
1209             free((char *)(p_item->ppsz_list[i]) );
1210             free((char *)(p_item->ppsz_list_text[i]) );
1211         }
1212     }
1213
1214     HRESULT (WINAPI *OurDirectSoundEnumerate)(LPDSENUMCALLBACKW, LPVOID);
1215
1216     HANDLE hdsound_dll = LoadLibrary("DSOUND.DLL");
1217     if( hdsound_dll == NULL )
1218     {
1219         msg_Warn( p_this, "cannot open DSOUND.DLL" );
1220         return VLC_SUCCESS;
1221     }
1222
1223     /* Get DirectSoundEnumerate */
1224     OurDirectSoundEnumerate = (void *)
1225                     GetProcAddress( hdsound_dll, "DirectSoundEnumerateW" );
1226
1227     if( OurDirectSoundEnumerate == NULL )
1228         goto error;
1229
1230     int nb_devices = 0;
1231     OurDirectSoundEnumerate(CallBackConfigNBEnum, &nb_devices);
1232     msg_Dbg(p_this,"found %d devices", nb_devices);
1233
1234     p_item->ppsz_list = xrealloc( p_item->ppsz_list,
1235                                   nb_devices * sizeof(char *) );
1236     p_item->ppsz_list_text = xrealloc( p_item->ppsz_list_text,
1237                                   nb_devices * sizeof(char *) );
1238
1239     p_item->i_list = 0;
1240     OurDirectSoundEnumerate(CallBackConfigEnum, p_item);
1241
1242 error:
1243     FreeLibrary(hdsound_dll);
1244
1245     return VLC_SUCCESS;
1246 }
1247