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