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