]> git.sesse.net Git - vlc/blob - modules/audio_output/directx.c
adds speaker setup override option
[vlc] / modules / audio_output / directx.c
1 /*****************************************************************************
2  * directx.c: Windows DirectX audio output method
3  *****************************************************************************
4  * Copyright (C) 2001 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
36 #include <windows.h>
37 #include <mmsystem.h>
38 #include <dsound.h>
39
40 #define FRAME_SIZE ((int)p_aout->output.output.i_rate/20) /* Size in samples */
41 #define FRAMES_NUM 8                                      /* Needs to be > 3 */
42
43 /*****************************************************************************
44  * DirectSound GUIDs.
45  * Defining them here allows us to get rid of the dxguid library during
46  * the linking stage.
47  *****************************************************************************/
48 #include <initguid.h>
49
50 /*****************************************************************************
51  * Useful macros
52  *****************************************************************************/
53 #ifndef WAVE_FORMAT_IEEE_FLOAT
54 #   define WAVE_FORMAT_IEEE_FLOAT 0x0003
55 #endif
56
57 #ifndef WAVE_FORMAT_DOLBY_AC3_SPDIF
58 #   define WAVE_FORMAT_DOLBY_AC3_SPDIF 0x0092
59 #endif
60
61 #ifndef WAVE_FORMAT_EXTENSIBLE
62 #define  WAVE_FORMAT_EXTENSIBLE   0xFFFE
63 #endif
64
65 #ifndef SPEAKER_FRONT_LEFT
66 #   define SPEAKER_FRONT_LEFT             0x1
67 #   define SPEAKER_FRONT_RIGHT            0x2
68 #   define SPEAKER_FRONT_CENTER           0x4
69 #   define SPEAKER_LOW_FREQUENCY          0x8
70 #   define SPEAKER_BACK_LEFT              0x10
71 #   define SPEAKER_BACK_RIGHT             0x20
72 #   define SPEAKER_FRONT_LEFT_OF_CENTER   0x40
73 #   define SPEAKER_FRONT_RIGHT_OF_CENTER  0x80
74 #   define SPEAKER_BACK_CENTER            0x100
75 #   define SPEAKER_SIDE_LEFT              0x200
76 #   define SPEAKER_SIDE_RIGHT             0x400
77 #   define SPEAKER_TOP_CENTER             0x800
78 #   define SPEAKER_TOP_FRONT_LEFT         0x1000
79 #   define SPEAKER_TOP_FRONT_CENTER       0x2000
80 #   define SPEAKER_TOP_FRONT_RIGHT        0x4000
81 #   define SPEAKER_TOP_BACK_LEFT          0x8000
82 #   define SPEAKER_TOP_BACK_CENTER        0x10000
83 #   define SPEAKER_TOP_BACK_RIGHT         0x20000
84 #   define SPEAKER_RESERVED               0x80000000
85 #endif
86
87 #ifndef DSSPEAKER_DSSPEAKER_DIRECTOUT
88 #   define DSSPEAKER_DSSPEAKER_DIRECTOUT         0x00000000
89 #endif
90 #ifndef DSSPEAKER_HEADPHONE
91 #   define DSSPEAKER_HEADPHONE         0x00000001
92 #endif
93 #ifndef DSSPEAKER_MONO
94 #   define DSSPEAKER_MONO              0x00000002
95 #endif
96 #ifndef DSSPEAKER_QUAD
97 #   define DSSPEAKER_QUAD              0x00000003
98 #endif
99 #ifndef DSSPEAKER_STEREO
100 #   define DSSPEAKER_STEREO            0x00000004
101 #endif
102 #ifndef DSSPEAKER_SURROUND
103 #   define DSSPEAKER_SURROUND          0x00000005
104 #endif
105 #ifndef DSSPEAKER_5POINT1
106 #   define DSSPEAKER_5POINT1           0x00000006
107 #endif
108 #ifndef DSSPEAKER_7POINT1
109 #   define DSSPEAKER_7POINT1           0x00000007
110 #endif
111 #ifndef DSSPEAKER_7POINT1_SURROUND
112 #   define DSSPEAKER_7POINT1_SURROUND           0x00000008
113 #endif
114 #ifndef DSSPEAKER_7POINT1_WIDE
115 #   define DSSPEAKER_7POINT1_WIDE           DSSPEAKER_7POINT1
116 #endif
117
118 #ifndef _WAVEFORMATEXTENSIBLE_
119 typedef struct {
120     WAVEFORMATEX    Format;
121     union {
122         WORD wValidBitsPerSample;       /* bits of precision  */
123         WORD wSamplesPerBlock;          /* valid if wBitsPerSample==0 */
124         WORD wReserved;                 /* If neither applies, set to zero. */
125     } Samples;
126     DWORD           dwChannelMask;      /* which channels are */
127                                         /* present in stream  */
128     GUID            SubFormat;
129 } WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;
130 #endif
131
132 DEFINE_GUID( _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, WAVE_FORMAT_IEEE_FLOAT, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
133 DEFINE_GUID( _KSDATAFORMAT_SUBTYPE_PCM, WAVE_FORMAT_PCM, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
134 DEFINE_GUID( _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF, WAVE_FORMAT_DOLBY_AC3_SPDIF, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
135
136 /*****************************************************************************
137  * notification_thread_t: DirectX event thread
138  *****************************************************************************/
139 typedef struct notification_thread_t
140 {
141     VLC_COMMON_MEMBERS
142
143     aout_instance_t *p_aout;
144     int i_frame_size;                          /* size in bytes of one frame */
145     int i_write_slot;       /* current write position in our circular buffer */
146
147     mtime_t start_date;
148     HANDLE event;
149
150 } notification_thread_t;
151
152 /*****************************************************************************
153  * aout_sys_t: directx audio output method descriptor
154  *****************************************************************************
155  * This structure is part of the audio output thread descriptor.
156  * It describes the direct sound specific properties of an audio device.
157  *****************************************************************************/
158 struct aout_sys_t
159 {
160     HINSTANCE           hdsound_dll;      /* handle of the opened dsound dll */
161
162     int                 i_device_id;                 /*  user defined device */
163     LPGUID              p_device_guid;
164
165     LPDIRECTSOUND       p_dsobject;              /* main Direct Sound object */
166     LPDIRECTSOUNDBUFFER p_dsbuffer;   /* the sound buffer we use (direct sound
167                                        * takes care of mixing all the
168                                        * secondary buffers into the primary) */
169
170     notification_thread_t *p_notif;                  /* DirectSoundThread id */
171
172     int b_playing;                                         /* playing status */
173
174     int i_frame_size;                         /* Size in bytes of one frame */
175
176     int i_speaker_setup;                 /* Speaker setup override */
177
178     bool b_chan_reorder;              /* do we need channel reordering */
179     int pi_chan_table[AOUT_CHAN_MAX];
180     uint32_t i_channel_mask;
181     uint32_t i_bits_per_sample;
182     uint32_t i_channels;
183 };
184
185 static const uint32_t pi_channels_src[] =
186     { AOUT_CHAN_LEFT, AOUT_CHAN_RIGHT,
187       AOUT_CHAN_MIDDLELEFT, AOUT_CHAN_MIDDLERIGHT,
188       AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT, AOUT_CHAN_REARCENTER,
189       AOUT_CHAN_CENTER, AOUT_CHAN_LFE, 0 };
190 static const uint32_t pi_channels_in[] =
191     { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT,
192       SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT,
193       SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT, SPEAKER_BACK_CENTER,
194       SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY, 0 };
195 static const uint32_t pi_channels_out[] =
196     { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT,
197       SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY,
198       SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT,
199       SPEAKER_BACK_CENTER,
200       SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT, 0 };
201
202 /*****************************************************************************
203  * Local prototypes.
204  *****************************************************************************/
205 static int  OpenAudio  ( vlc_object_t * );
206 static void CloseAudio ( vlc_object_t * );
207 static void Play       ( aout_instance_t * );
208
209 /* local functions */
210 static void Probe             ( aout_instance_t * );
211 static int  InitDirectSound   ( aout_instance_t * );
212 static int  CreateDSBuffer    ( aout_instance_t *, int, int, int, int, int, bool );
213 static int  CreateDSBufferPCM ( aout_instance_t *, int*, int, int, int, bool );
214 static void DestroyDSBuffer   ( aout_instance_t * );
215 static void* DirectSoundThread( vlc_object_t * );
216 static int  FillBuffer        ( aout_instance_t *, int, aout_buffer_t * );
217
218 /* Speaker setup override options list */
219 static const char *const speaker_list[] = { "Windows default", "Mono", "Stereo",
220                                             "Quad", "5.1", "7.1" };
221
222 /*****************************************************************************
223  * Module descriptor
224  *****************************************************************************/
225 #define DEVICE_TEXT N_("Output device")
226 #define DEVICE_LONGTEXT N_( \
227     "DirectX device number: 0 default device, 1..N device by number" \
228     "(Note that the default device appears as 0 AND another number)." )
229 #define FLOAT_TEXT N_("Use float32 output")
230 #define FLOAT_LONGTEXT N_( \
231     "The option allows you to enable or disable the high-quality float32 " \
232     "audio output mode (which is not well supported by some soundcards)." )
233 #define SPEAKER_TEXT N_("Select speaker configuration")
234 #define SPEAKER_LONGTEXT N_("Select speaker configuration you want to use. " \
235     "This option doesn't upmix! So NO e.g. Stereo -> 5.1 conversion." )
236
237 vlc_module_begin ()
238     set_description( N_("DirectX audio output") )
239     set_shortname( "DirectX" )
240     set_capability( "audio output", 100 )
241     set_category( CAT_AUDIO )
242     set_subcategory( SUBCAT_AUDIO_AOUT )
243     add_shortcut( "directx" )
244     add_integer( "directx-audio-device", 0, NULL, DEVICE_TEXT,
245                  DEVICE_LONGTEXT, true )
246     add_bool( "directx-audio-float32", 0, 0, FLOAT_TEXT,
247               FLOAT_LONGTEXT, true )
248     add_string( "directx-audio-speaker", "Windows default", NULL,
249                  SPEAKER_TEXT, SPEAKER_LONGTEXT, true )
250         change_string_list( speaker_list, 0, 0 )
251         change_need_restart ()
252     set_callbacks( OpenAudio, CloseAudio )
253 vlc_module_end ()
254
255 /*****************************************************************************
256  * OpenAudio: open the audio device
257  *****************************************************************************
258  * This function opens and setups Direct Sound.
259  *****************************************************************************/
260 static int OpenAudio( vlc_object_t *p_this )
261 {
262     aout_instance_t * p_aout = (aout_instance_t *)p_this;
263     vlc_value_t val;
264     char * psz_speaker;
265     int i = 0;
266
267     const char * const * ppsz_compare = speaker_list;
268
269     msg_Dbg( p_aout, "OpenAudio" );
270
271    /* Allocate structure */
272     p_aout->output.p_sys = malloc( sizeof( aout_sys_t ) );
273     if( p_aout->output.p_sys == NULL )
274         return VLC_ENOMEM;
275
276     /* Initialize some variables */
277     p_aout->output.p_sys->p_dsobject = NULL;
278     p_aout->output.p_sys->p_dsbuffer = NULL;
279     p_aout->output.p_sys->p_notif = NULL;
280     p_aout->output.p_sys->b_playing = 0;
281
282     p_aout->output.pf_play = Play;
283     aout_VolumeSoftInit( p_aout );
284
285     /* Retrieve config values */
286     var_Create( p_aout, "directx-audio-float32",
287                 VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
288
289     var_Create( p_aout, "directx-audio-speaker",
290                 VLC_VAR_STRING | VLC_VAR_DOINHERIT );
291     var_Get( p_this, "directx-audio-speaker", &val );
292     psz_speaker = val.psz_string;
293
294     while ( *ppsz_compare != NULL )
295     {
296         if ( !strncmp( *ppsz_compare, psz_speaker, strlen(*ppsz_compare) ) )
297         {
298             break;
299         }
300         ppsz_compare++; i++;
301     }
302
303     if ( *ppsz_compare == NULL )
304     {
305         msg_Err( p_aout, "(%s) isn't valid speaker setup option",
306                  psz_speaker );
307         msg_Err( p_aout, "Defaulting to Windows default speaker config");
308         i = 0;
309     }
310     p_aout->output.p_sys->i_speaker_setup = i;
311
312     var_Create( p_aout, "directx-audio-device",
313                 VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
314     var_Get( p_aout, "directx-audio-device", &val );
315     p_aout->output.p_sys->i_device_id = val.i_int;
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_FOURCC('s','p','d','i');
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_FOURCC('s','p','d','i'),
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     int 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_FOURCC('s','p','d','i'),
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
682     val.b_bool = true;
683     var_Set( p_aout, "intf-change", val );
684 }
685
686 /*****************************************************************************
687  * Play: we'll start playing the directsound buffer here because at least here
688  *       we know the first buffer has been put in the aout fifo and we also
689  *       know its date.
690  *****************************************************************************/
691 static void Play( aout_instance_t *p_aout )
692 {
693     if( !p_aout->output.p_sys->b_playing )
694     {
695         aout_buffer_t *p_buffer;
696         int i;
697
698         p_aout->output.p_sys->b_playing = 1;
699
700         /* get the playing date of the first aout buffer */
701         p_aout->output.p_sys->p_notif->start_date =
702             aout_FifoFirstDate( p_aout, &p_aout->output.fifo );
703
704         /* fill in the first samples */
705         for( i = 0; i < FRAMES_NUM; i++ )
706         {
707             p_buffer = aout_FifoPop( p_aout, &p_aout->output.fifo );
708             if( !p_buffer ) break;
709             FillBuffer( p_aout, i, p_buffer );
710         }
711
712         /* wake up the audio output thread */
713         SetEvent( p_aout->output.p_sys->p_notif->event );
714     }
715 }
716
717 /*****************************************************************************
718  * CloseAudio: close the audio device
719  *****************************************************************************/
720 static void CloseAudio( vlc_object_t *p_this )
721 {
722     aout_instance_t * p_aout = (aout_instance_t *)p_this;
723     aout_sys_t *p_sys = p_aout->output.p_sys;
724
725     msg_Dbg( p_aout, "closing audio device" );
726
727     /* kill the position notification thread, if any */
728     if( p_sys->p_notif )
729     {
730         vlc_object_detach( p_sys->p_notif );
731         vlc_object_kill( p_sys->p_notif );
732         /* wake up the audio thread if needed */
733         if( !p_sys->b_playing ) SetEvent( p_sys->p_notif->event );
734
735         vlc_thread_join( p_sys->p_notif );
736         vlc_object_release( p_sys->p_notif );
737     }
738
739     /* release the secondary buffer */
740     DestroyDSBuffer( p_aout );
741
742     /* finally release the DirectSound object */
743     if( p_sys->p_dsobject ) IDirectSound_Release( p_sys->p_dsobject );
744
745     /* free DSOUND.DLL */
746     if( p_sys->hdsound_dll ) FreeLibrary( p_sys->hdsound_dll );
747
748     free( p_aout->output.p_sys->p_device_guid );
749     free( p_sys );
750 }
751
752 /*****************************************************************************
753  * CallBackDirectSoundEnum: callback to enumerate available devices
754  *****************************************************************************/
755 static int CALLBACK CallBackDirectSoundEnum( LPGUID p_guid, LPCSTR psz_desc,
756                                              LPCSTR psz_mod, LPVOID _p_aout )
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->i_device_id == 0 && p_guid )
763     {
764         p_aout->output.p_sys->p_device_guid = malloc( sizeof( GUID ) );
765         *p_aout->output.p_sys->p_device_guid = *p_guid;
766         msg_Dbg( p_aout, "using device: %s", psz_desc );
767     }
768
769     p_aout->output.p_sys->i_device_id--;
770     return 1;
771 }
772
773 /*****************************************************************************
774  * InitDirectSound: handle all the gory details of DirectSound initialisation
775  *****************************************************************************/
776 static int InitDirectSound( aout_instance_t *p_aout )
777 {
778     HRESULT (WINAPI *OurDirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
779     HRESULT (WINAPI *OurDirectSoundEnumerate)(LPDSENUMCALLBACK, LPVOID);
780
781     p_aout->output.p_sys->hdsound_dll = LoadLibrary("DSOUND.DLL");
782     if( p_aout->output.p_sys->hdsound_dll == NULL )
783     {
784         msg_Warn( p_aout, "cannot open DSOUND.DLL" );
785         goto error;
786     }
787
788     OurDirectSoundCreate = (void *)
789         GetProcAddress( p_aout->output.p_sys->hdsound_dll,
790                         "DirectSoundCreate" );
791     if( OurDirectSoundCreate == NULL )
792     {
793         msg_Warn( p_aout, "GetProcAddress FAILED" );
794         goto error;
795     }
796
797     /* Get DirectSoundEnumerate */
798     OurDirectSoundEnumerate = (void *)
799        GetProcAddress( p_aout->output.p_sys->hdsound_dll,
800                        "DirectSoundEnumerateA" );
801     if( OurDirectSoundEnumerate )
802     {
803         /* Attempt enumeration */
804         if( FAILED( OurDirectSoundEnumerate( CallBackDirectSoundEnum,
805                                              p_aout ) ) )
806         {
807             msg_Dbg( p_aout, "enumeration of DirectSound devices failed" );
808         }
809     }
810
811     /* Create the direct sound object */
812     if FAILED( OurDirectSoundCreate( p_aout->output.p_sys->p_device_guid,
813                                      &p_aout->output.p_sys->p_dsobject,
814                                      NULL ) )
815     {
816         msg_Warn( p_aout, "cannot create a direct sound device" );
817         goto error;
818     }
819
820     /* Set DirectSound Cooperative level, ie what control we want over Windows
821      * sound device. In our case, DSSCL_EXCLUSIVE means that we can modify the
822      * settings of the primary buffer, but also that only the sound of our
823      * application will be hearable when it will have the focus.
824      * !!! (this is not really working as intended yet because to set the
825      * cooperative level you need the window handle of your application, and
826      * I don't know of any easy way to get it. Especially since we might play
827      * sound without any video, and so what window handle should we use ???
828      * The hack for now is to use the Desktop window handle - it seems to be
829      * working */
830     if( IDirectSound_SetCooperativeLevel( p_aout->output.p_sys->p_dsobject,
831                                           GetDesktopWindow(),
832                                           DSSCL_EXCLUSIVE) )
833     {
834         msg_Warn( p_aout, "cannot set direct sound cooperative level" );
835     }
836
837     return VLC_SUCCESS;
838
839  error:
840     p_aout->output.p_sys->p_dsobject = NULL;
841     if( p_aout->output.p_sys->hdsound_dll )
842     {
843         FreeLibrary( p_aout->output.p_sys->hdsound_dll );
844         p_aout->output.p_sys->hdsound_dll = NULL;
845     }
846     return VLC_EGENERIC;
847
848 }
849
850 /*****************************************************************************
851  * CreateDSBuffer: Creates a direct sound buffer of the required format.
852  *****************************************************************************
853  * This function creates the buffer we'll use to play audio.
854  * In DirectSound there are two kinds of buffers:
855  * - the primary buffer: which is the actual buffer that the soundcard plays
856  * - the secondary buffer(s): these buffers are the one actually used by
857  *    applications and DirectSound takes care of mixing them into the primary.
858  *
859  * Once you create a secondary buffer, you cannot change its format anymore so
860  * you have to release the current one and create another.
861  *****************************************************************************/
862 static int CreateDSBuffer( aout_instance_t *p_aout, int i_format,
863                            int i_channels, int i_nb_channels, int i_rate,
864                            int i_bytes_per_frame, bool b_probe )
865 {
866     WAVEFORMATEXTENSIBLE waveformat;
867     DSBUFFERDESC         dsbdesc;
868     unsigned int         i;
869
870     /* First set the sound buffer format */
871     waveformat.dwChannelMask = 0;
872     for( i = 0; i < sizeof(pi_channels_src)/sizeof(uint32_t); i++ )
873     {
874         if( i_channels & pi_channels_src[i] )
875             waveformat.dwChannelMask |= pi_channels_in[i];
876     }
877
878     switch( i_format )
879     {
880     case VLC_FOURCC('s','p','d','i'):
881         i_nb_channels = 2;
882         /* To prevent channel re-ordering */
883         waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
884         waveformat.Format.wBitsPerSample = 16;
885         waveformat.Samples.wValidBitsPerSample =
886             waveformat.Format.wBitsPerSample;
887         waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
888         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
889         break;
890
891     case VLC_FOURCC('f','l','3','2'):
892         waveformat.Format.wBitsPerSample = sizeof(float) * 8;
893         waveformat.Samples.wValidBitsPerSample =
894             waveformat.Format.wBitsPerSample;
895         waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
896         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
897         break;
898
899     case VLC_FOURCC('s','1','6','l'):
900         waveformat.Format.wBitsPerSample = 16;
901         waveformat.Samples.wValidBitsPerSample =
902             waveformat.Format.wBitsPerSample;
903         waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
904         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_PCM;
905         break;
906     }
907
908     waveformat.Format.nChannels = i_nb_channels;
909     waveformat.Format.nSamplesPerSec = i_rate;
910     waveformat.Format.nBlockAlign =
911         waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
912     waveformat.Format.nAvgBytesPerSec =
913         waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;
914
915     p_aout->output.p_sys->i_bits_per_sample = waveformat.Format.wBitsPerSample;
916     p_aout->output.p_sys->i_channels = i_nb_channels;
917
918     /* Then fill in the direct sound descriptor */
919     memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
920     dsbdesc.dwSize = sizeof(DSBUFFERDESC);
921     dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2/* Better position accuracy */
922                     | DSBCAPS_GLOBALFOCUS;      /* Allows background playing */
923
924     /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
925     if( i_nb_channels <= 2 )
926     {
927         waveformat.Format.cbSize = 0;
928     }
929     else
930     {
931         waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
932         waveformat.Format.cbSize =
933             sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
934
935         /* Needed for 5.1 on emu101k */
936         dsbdesc.dwFlags |= DSBCAPS_LOCHARDWARE;
937     }
938
939     dsbdesc.dwBufferBytes = FRAMES_NUM * i_bytes_per_frame;   /* buffer size */
940     dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&waveformat;
941
942     if FAILED( IDirectSound_CreateSoundBuffer(
943                    p_aout->output.p_sys->p_dsobject, &dsbdesc,
944                    &p_aout->output.p_sys->p_dsbuffer, NULL) )
945     {
946         if( dsbdesc.dwFlags & DSBCAPS_LOCHARDWARE )
947         {
948             /* Try without DSBCAPS_LOCHARDWARE */
949             dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE;
950             if FAILED( IDirectSound_CreateSoundBuffer(
951                    p_aout->output.p_sys->p_dsobject, &dsbdesc,
952                    &p_aout->output.p_sys->p_dsbuffer, NULL) )
953             {
954                 return VLC_EGENERIC;
955             }
956             if( !b_probe )
957                 msg_Dbg( p_aout, "couldn't use hardware sound buffer" );
958         }
959         else
960         {
961             return VLC_EGENERIC;
962         }
963     }
964
965     /* Stop here if we were just probing */
966     if( b_probe )
967     {
968         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
969         p_aout->output.p_sys->p_dsbuffer = NULL;
970         return VLC_SUCCESS;
971     }
972
973     p_aout->output.p_sys->i_frame_size = i_bytes_per_frame;
974     p_aout->output.p_sys->i_channel_mask = waveformat.dwChannelMask;
975     p_aout->output.p_sys->b_chan_reorder =
976         aout_CheckChannelReorder( pi_channels_in, pi_channels_out,
977                                   waveformat.dwChannelMask, i_nb_channels,
978                                   p_aout->output.p_sys->pi_chan_table );
979
980     if( p_aout->output.p_sys->b_chan_reorder )
981     {
982         msg_Dbg( p_aout, "channel reordering needed" );
983     }
984
985     return VLC_SUCCESS;
986 }
987
988 /*****************************************************************************
989  * CreateDSBufferPCM: creates a PCM direct sound buffer.
990  *****************************************************************************
991  * We first try to create a WAVE_FORMAT_IEEE_FLOAT buffer if supported by
992  * the hardware, otherwise we create a WAVE_FORMAT_PCM buffer.
993  ****************************************************************************/
994 static int CreateDSBufferPCM( aout_instance_t *p_aout, int *i_format,
995                               int i_channels, int i_nb_channels, int i_rate,
996                               bool b_probe )
997 {
998     vlc_value_t val;
999
1000     var_Get( p_aout, "directx-audio-float32", &val );
1001
1002     /* Float32 audio samples are not supported for 5.1 output on the emu101k */
1003
1004     if( !val.b_bool || i_nb_channels > 2 ||
1005         CreateDSBuffer( p_aout, VLC_FOURCC('f','l','3','2'),
1006                         i_channels, i_nb_channels, i_rate,
1007                         FRAME_SIZE * 4 * i_nb_channels, b_probe )
1008         != VLC_SUCCESS )
1009     {
1010         if ( CreateDSBuffer( p_aout, VLC_FOURCC('s','1','6','l'),
1011                              i_channels, i_nb_channels, i_rate,
1012                              FRAME_SIZE * 2 * i_nb_channels, b_probe )
1013              != VLC_SUCCESS )
1014         {
1015             return VLC_EGENERIC;
1016         }
1017         else
1018         {
1019             *i_format = VLC_FOURCC('s','1','6','l');
1020             return VLC_SUCCESS;
1021         }
1022     }
1023     else
1024     {
1025         *i_format = VLC_FOURCC('f','l','3','2');
1026         return VLC_SUCCESS;
1027     }
1028 }
1029
1030 /*****************************************************************************
1031  * DestroyDSBuffer
1032  *****************************************************************************
1033  * This function destroys the secondary buffer.
1034  *****************************************************************************/
1035 static void DestroyDSBuffer( aout_instance_t *p_aout )
1036 {
1037     if( p_aout->output.p_sys->p_dsbuffer )
1038     {
1039         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
1040         p_aout->output.p_sys->p_dsbuffer = NULL;
1041     }
1042 }
1043
1044 /*****************************************************************************
1045  * FillBuffer: Fill in one of the direct sound frame buffers.
1046  *****************************************************************************
1047  * Returns VLC_SUCCESS on success.
1048  *****************************************************************************/
1049 static int FillBuffer( aout_instance_t *p_aout, int i_frame,
1050                        aout_buffer_t *p_buffer )
1051 {
1052     notification_thread_t *p_notif = p_aout->output.p_sys->p_notif;
1053     aout_sys_t *p_sys = p_aout->output.p_sys;
1054     void *p_write_position, *p_wrap_around;
1055     long l_bytes1, l_bytes2;
1056     HRESULT dsresult;
1057
1058     /* Before copying anything, we have to lock the buffer */
1059     dsresult = IDirectSoundBuffer_Lock(
1060                 p_sys->p_dsbuffer,                              /* DS buffer */
1061                 i_frame * p_notif->i_frame_size,             /* Start offset */
1062                 p_notif->i_frame_size,                    /* Number of bytes */
1063                 &p_write_position,                  /* Address of lock start */
1064                 &l_bytes1,       /* Count of bytes locked before wrap around */
1065                 &p_wrap_around,            /* Buffer adress (if wrap around) */
1066                 &l_bytes2,               /* Count of bytes after wrap around */
1067                 0 );                                                /* Flags */
1068     if( dsresult == DSERR_BUFFERLOST )
1069     {
1070         IDirectSoundBuffer_Restore( p_sys->p_dsbuffer );
1071         dsresult = IDirectSoundBuffer_Lock(
1072                                p_sys->p_dsbuffer,
1073                                i_frame * p_notif->i_frame_size,
1074                                p_notif->i_frame_size,
1075                                &p_write_position,
1076                                &l_bytes1,
1077                                &p_wrap_around,
1078                                &l_bytes2,
1079                                0 );
1080     }
1081     if( dsresult != DS_OK )
1082     {
1083         msg_Warn( p_notif, "cannot lock buffer" );
1084         if( p_buffer ) aout_BufferFree( p_buffer );
1085         return VLC_EGENERIC;
1086     }
1087
1088     if( p_buffer == NULL )
1089     {
1090         memset( p_write_position, 0, l_bytes1 );
1091     }
1092     else
1093     {
1094         if( p_sys->b_chan_reorder )
1095         {
1096             /* Do the channel reordering here */
1097             aout_ChannelReorder( p_buffer->p_buffer, p_buffer->i_nb_bytes,
1098                                  p_sys->i_channels, p_sys->pi_chan_table,
1099                                  p_sys->i_bits_per_sample );
1100         }
1101
1102         vlc_memcpy( p_write_position, p_buffer->p_buffer, l_bytes1 );
1103         aout_BufferFree( p_buffer );
1104     }
1105
1106     /* Now the data has been copied, unlock the buffer */
1107     IDirectSoundBuffer_Unlock( p_sys->p_dsbuffer, p_write_position, l_bytes1,
1108                                p_wrap_around, l_bytes2 );
1109
1110     p_notif->i_write_slot = (i_frame + 1) % FRAMES_NUM;
1111     return VLC_SUCCESS;
1112 }
1113
1114 /*****************************************************************************
1115  * DirectSoundThread: this thread will capture play notification events.
1116  *****************************************************************************
1117  * We use this thread to emulate a callback mechanism. The thread probes for
1118  * event notification and fills up the DS secondary buffer when needed.
1119  *****************************************************************************/
1120 static void* DirectSoundThread( vlc_object_t *p_this )
1121 {
1122     notification_thread_t *p_notif = (notification_thread_t*)p_this;
1123     aout_instance_t *p_aout = p_notif->p_aout;
1124     bool b_sleek;
1125     mtime_t last_time;
1126     HRESULT dsresult;
1127     long l_queued = 0;
1128     int canc = vlc_savecancel ();
1129
1130     /* We don't want any resampling when using S/PDIF output */
1131     b_sleek = p_aout->output.output.i_format == VLC_FOURCC('s','p','d','i');
1132
1133     msg_Dbg( p_notif, "DirectSoundThread ready" );
1134
1135     /* Wait here until Play() is called */
1136     WaitForSingleObject( p_notif->event, INFINITE );
1137
1138     if( vlc_object_alive (p_notif) )
1139     {
1140         mwait( p_notif->start_date - AOUT_PTS_TOLERANCE / 2 );
1141
1142         /* start playing the buffer */
1143         dsresult = IDirectSoundBuffer_Play( p_aout->output.p_sys->p_dsbuffer,
1144                                         0,                         /* Unused */
1145                                         0,                         /* Unused */
1146                                         DSBPLAY_LOOPING );          /* Flags */
1147         if( dsresult == DSERR_BUFFERLOST )
1148         {
1149             IDirectSoundBuffer_Restore( p_aout->output.p_sys->p_dsbuffer );
1150             dsresult = IDirectSoundBuffer_Play(
1151                                             p_aout->output.p_sys->p_dsbuffer,
1152                                             0,                     /* Unused */
1153                                             0,                     /* Unused */
1154                                             DSBPLAY_LOOPING );      /* Flags */
1155         }
1156         if( dsresult != DS_OK )
1157         {
1158             msg_Err( p_aout, "cannot start playing buffer" );
1159         }
1160     }
1161     last_time = mdate();
1162
1163     while( vlc_object_alive (p_notif) )
1164     {
1165         long l_read, l_free_slots;
1166         mtime_t mtime = mdate();
1167         int i;
1168
1169         /*
1170          * Fill in as much audio data as we can in our circular buffer
1171          */
1172
1173         /* Find out current play position */
1174         if FAILED( IDirectSoundBuffer_GetCurrentPosition(
1175                    p_aout->output.p_sys->p_dsbuffer, &l_read, NULL ) )
1176         {
1177             msg_Err( p_aout, "GetCurrentPosition() failed!" );
1178             l_read = 0;
1179         }
1180
1181         /* Detect underruns */
1182         if( l_queued && mtime - last_time >
1183             INT64_C(1000000) * l_queued / p_aout->output.output.i_rate )
1184         {
1185             msg_Dbg( p_aout, "detected underrun!" );
1186         }
1187         last_time = mtime;
1188
1189         /* Try to fill in as many frame buffers as possible */
1190         l_read /= p_aout->output.output.i_bytes_per_frame;
1191         l_queued = p_notif->i_write_slot * FRAME_SIZE - l_read;
1192         if( l_queued < 0 ) l_queued += (FRAME_SIZE * FRAMES_NUM);
1193         l_free_slots = (FRAMES_NUM * FRAME_SIZE - l_queued) / FRAME_SIZE;
1194
1195         for( i = 0; i < l_free_slots; i++ )
1196         {
1197             aout_buffer_t *p_buffer = aout_OutputNextBuffer( p_aout,
1198                 mtime + INT64_C(1000000) * (i * FRAME_SIZE + l_queued) /
1199                 p_aout->output.output.i_rate, b_sleek );
1200
1201             /* If there is no audio data available and we have some buffered
1202              * already, then just wait for the next time */
1203             if( !p_buffer && (i || l_queued / FRAME_SIZE) ) break;
1204
1205             if( FillBuffer( p_aout, p_notif->i_write_slot % FRAMES_NUM,
1206                             p_buffer ) != VLC_SUCCESS ) break;
1207         }
1208
1209         /* Sleep a reasonable amount of time */
1210         l_queued += (i * FRAME_SIZE);
1211         msleep( INT64_C(1000000) * l_queued / p_aout->output.output.i_rate / 2 );
1212     }
1213
1214     /* make sure the buffer isn't playing */
1215     IDirectSoundBuffer_Stop( p_aout->output.p_sys->p_dsbuffer );
1216
1217     /* free the event */
1218     CloseHandle( p_notif->event );
1219
1220     vlc_restorecancel (canc);
1221     msg_Dbg( p_notif, "DirectSoundThread exiting" );
1222     return NULL;
1223 }