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