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