]> git.sesse.net Git - vlc/blob - modules/audio_output/directx.c
6934214d058e49530ef0804f46b65c7f18cacdfe
[vlc] / modules / audio_output / directx.c
1 /*****************************************************************************
2  * directx.c: Windows DirectX audio output method
3  *****************************************************************************
4  * Copyright (C) 2001-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_aout.h>
35
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 *, vlc_fourcc_t*, 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_("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", false, NULL, 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     vlc_fourcc_t 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     VLC_UNUSED( psz_mod );
752
753     aout_instance_t *p_aout = (aout_instance_t *)_p_aout;
754
755     msg_Dbg( p_aout, "found device: %s", psz_desc );
756
757     if( p_aout->output.p_sys->i_device_id == 0 && p_guid )
758     {
759         p_aout->output.p_sys->p_device_guid = malloc( sizeof( GUID ) );
760         *p_aout->output.p_sys->p_device_guid = *p_guid;
761         msg_Dbg( p_aout, "using device: %s", psz_desc );
762     }
763
764     p_aout->output.p_sys->i_device_id--;
765     return 1;
766 }
767
768 /*****************************************************************************
769  * InitDirectSound: handle all the gory details of DirectSound initialisation
770  *****************************************************************************/
771 static int InitDirectSound( aout_instance_t *p_aout )
772 {
773     HRESULT (WINAPI *OurDirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
774     HRESULT (WINAPI *OurDirectSoundEnumerate)(LPDSENUMCALLBACK, LPVOID);
775
776     p_aout->output.p_sys->hdsound_dll = LoadLibrary("DSOUND.DLL");
777     if( p_aout->output.p_sys->hdsound_dll == NULL )
778     {
779         msg_Warn( p_aout, "cannot open DSOUND.DLL" );
780         goto error;
781     }
782
783     OurDirectSoundCreate = (void *)
784         GetProcAddress( p_aout->output.p_sys->hdsound_dll,
785                         "DirectSoundCreate" );
786     if( OurDirectSoundCreate == NULL )
787     {
788         msg_Warn( p_aout, "GetProcAddress FAILED" );
789         goto error;
790     }
791
792     /* Get DirectSoundEnumerate */
793     OurDirectSoundEnumerate = (void *)
794        GetProcAddress( p_aout->output.p_sys->hdsound_dll,
795                        "DirectSoundEnumerateA" );
796     if( OurDirectSoundEnumerate )
797     {
798         /* Attempt enumeration */
799         if( FAILED( OurDirectSoundEnumerate( CallBackDirectSoundEnum,
800                                              p_aout ) ) )
801         {
802             msg_Dbg( p_aout, "enumeration of DirectSound devices failed" );
803         }
804     }
805
806     /* Create the direct sound object */
807     if FAILED( OurDirectSoundCreate( p_aout->output.p_sys->p_device_guid,
808                                      &p_aout->output.p_sys->p_dsobject,
809                                      NULL ) )
810     {
811         msg_Warn( p_aout, "cannot create a direct sound device" );
812         goto error;
813     }
814
815     /* Set DirectSound Cooperative level, ie what control we want over Windows
816      * sound device. In our case, DSSCL_EXCLUSIVE means that we can modify the
817      * settings of the primary buffer, but also that only the sound of our
818      * application will be hearable when it will have the focus.
819      * !!! (this is not really working as intended yet because to set the
820      * cooperative level you need the window handle of your application, and
821      * I don't know of any easy way to get it. Especially since we might play
822      * sound without any video, and so what window handle should we use ???
823      * The hack for now is to use the Desktop window handle - it seems to be
824      * working */
825     if( IDirectSound_SetCooperativeLevel( p_aout->output.p_sys->p_dsobject,
826                                           GetDesktopWindow(),
827                                           DSSCL_EXCLUSIVE) )
828     {
829         msg_Warn( p_aout, "cannot set direct sound cooperative level" );
830     }
831
832     return VLC_SUCCESS;
833
834  error:
835     p_aout->output.p_sys->p_dsobject = NULL;
836     if( p_aout->output.p_sys->hdsound_dll )
837     {
838         FreeLibrary( p_aout->output.p_sys->hdsound_dll );
839         p_aout->output.p_sys->hdsound_dll = NULL;
840     }
841     return VLC_EGENERIC;
842
843 }
844
845 /*****************************************************************************
846  * CreateDSBuffer: Creates a direct sound buffer of the required format.
847  *****************************************************************************
848  * This function creates the buffer we'll use to play audio.
849  * In DirectSound there are two kinds of buffers:
850  * - the primary buffer: which is the actual buffer that the soundcard plays
851  * - the secondary buffer(s): these buffers are the one actually used by
852  *    applications and DirectSound takes care of mixing them into the primary.
853  *
854  * Once you create a secondary buffer, you cannot change its format anymore so
855  * you have to release the current one and create another.
856  *****************************************************************************/
857 static int CreateDSBuffer( aout_instance_t *p_aout, int i_format,
858                            int i_channels, int i_nb_channels, int i_rate,
859                            int i_bytes_per_frame, bool b_probe )
860 {
861     WAVEFORMATEXTENSIBLE waveformat;
862     DSBUFFERDESC         dsbdesc;
863     unsigned int         i;
864
865     /* First set the sound buffer format */
866     waveformat.dwChannelMask = 0;
867     for( i = 0; i < sizeof(pi_channels_src)/sizeof(uint32_t); i++ )
868     {
869         if( i_channels & pi_channels_src[i] )
870             waveformat.dwChannelMask |= pi_channels_in[i];
871     }
872
873     switch( i_format )
874     {
875     case VLC_CODEC_SPDIFL:
876         i_nb_channels = 2;
877         /* To prevent channel re-ordering */
878         waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
879         waveformat.Format.wBitsPerSample = 16;
880         waveformat.Samples.wValidBitsPerSample =
881             waveformat.Format.wBitsPerSample;
882         waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
883         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
884         break;
885
886     case VLC_CODEC_FL32:
887         waveformat.Format.wBitsPerSample = sizeof(float) * 8;
888         waveformat.Samples.wValidBitsPerSample =
889             waveformat.Format.wBitsPerSample;
890         waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
891         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
892         break;
893
894     case VLC_CODEC_S16L:
895         waveformat.Format.wBitsPerSample = 16;
896         waveformat.Samples.wValidBitsPerSample =
897             waveformat.Format.wBitsPerSample;
898         waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
899         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_PCM;
900         break;
901     }
902
903     waveformat.Format.nChannels = i_nb_channels;
904     waveformat.Format.nSamplesPerSec = i_rate;
905     waveformat.Format.nBlockAlign =
906         waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
907     waveformat.Format.nAvgBytesPerSec =
908         waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;
909
910     p_aout->output.p_sys->i_bits_per_sample = waveformat.Format.wBitsPerSample;
911     p_aout->output.p_sys->i_channels = i_nb_channels;
912
913     /* Then fill in the direct sound descriptor */
914     memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
915     dsbdesc.dwSize = sizeof(DSBUFFERDESC);
916     dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2/* Better position accuracy */
917                     | DSBCAPS_GLOBALFOCUS;      /* Allows background playing */
918
919     /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
920     if( i_nb_channels <= 2 )
921     {
922         waveformat.Format.cbSize = 0;
923     }
924     else
925     {
926         waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
927         waveformat.Format.cbSize =
928             sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
929
930         /* Needed for 5.1 on emu101k */
931         dsbdesc.dwFlags |= DSBCAPS_LOCHARDWARE;
932     }
933
934     dsbdesc.dwBufferBytes = FRAMES_NUM * i_bytes_per_frame;   /* buffer size */
935     dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&waveformat;
936
937     if FAILED( IDirectSound_CreateSoundBuffer(
938                    p_aout->output.p_sys->p_dsobject, &dsbdesc,
939                    &p_aout->output.p_sys->p_dsbuffer, NULL) )
940     {
941         if( dsbdesc.dwFlags & DSBCAPS_LOCHARDWARE )
942         {
943             /* Try without DSBCAPS_LOCHARDWARE */
944             dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE;
945             if FAILED( IDirectSound_CreateSoundBuffer(
946                    p_aout->output.p_sys->p_dsobject, &dsbdesc,
947                    &p_aout->output.p_sys->p_dsbuffer, NULL) )
948             {
949                 return VLC_EGENERIC;
950             }
951             if( !b_probe )
952                 msg_Dbg( p_aout, "couldn't use hardware sound buffer" );
953         }
954         else
955         {
956             return VLC_EGENERIC;
957         }
958     }
959
960     /* Stop here if we were just probing */
961     if( b_probe )
962     {
963         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
964         p_aout->output.p_sys->p_dsbuffer = NULL;
965         return VLC_SUCCESS;
966     }
967
968     p_aout->output.p_sys->i_frame_size = i_bytes_per_frame;
969     p_aout->output.p_sys->i_channel_mask = waveformat.dwChannelMask;
970     p_aout->output.p_sys->b_chan_reorder =
971         aout_CheckChannelReorder( pi_channels_in, pi_channels_out,
972                                   waveformat.dwChannelMask, i_nb_channels,
973                                   p_aout->output.p_sys->pi_chan_table );
974
975     if( p_aout->output.p_sys->b_chan_reorder )
976     {
977         msg_Dbg( p_aout, "channel reordering needed" );
978     }
979
980     return VLC_SUCCESS;
981 }
982
983 /*****************************************************************************
984  * CreateDSBufferPCM: creates a PCM direct sound buffer.
985  *****************************************************************************
986  * We first try to create a WAVE_FORMAT_IEEE_FLOAT buffer if supported by
987  * the hardware, otherwise we create a WAVE_FORMAT_PCM buffer.
988  ****************************************************************************/
989 static int CreateDSBufferPCM( aout_instance_t *p_aout, vlc_fourcc_t *i_format,
990                               int i_channels, int i_nb_channels, int i_rate,
991                               bool b_probe )
992 {
993     /* Float32 audio samples are not supported for 5.1 output on the emu101k */
994     if( !var_GetBool( p_aout, "directx-audio-float32" ) ||
995         i_nb_channels > 2 ||
996         CreateDSBuffer( p_aout, VLC_CODEC_FL32,
997                         i_channels, i_nb_channels, i_rate,
998                         FRAME_SIZE * 4 * i_nb_channels, b_probe )
999         != VLC_SUCCESS )
1000     {
1001         if ( CreateDSBuffer( p_aout, VLC_CODEC_S16L,
1002                              i_channels, i_nb_channels, i_rate,
1003                              FRAME_SIZE * 2 * i_nb_channels, b_probe )
1004              != VLC_SUCCESS )
1005         {
1006             return VLC_EGENERIC;
1007         }
1008         else
1009         {
1010             *i_format = VLC_CODEC_S16L;
1011             return VLC_SUCCESS;
1012         }
1013     }
1014     else
1015     {
1016         *i_format = VLC_CODEC_FL32;
1017         return VLC_SUCCESS;
1018     }
1019 }
1020
1021 /*****************************************************************************
1022  * DestroyDSBuffer
1023  *****************************************************************************
1024  * This function destroys the secondary buffer.
1025  *****************************************************************************/
1026 static void DestroyDSBuffer( aout_instance_t *p_aout )
1027 {
1028     if( p_aout->output.p_sys->p_dsbuffer )
1029     {
1030         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
1031         p_aout->output.p_sys->p_dsbuffer = NULL;
1032     }
1033 }
1034
1035 /*****************************************************************************
1036  * FillBuffer: Fill in one of the direct sound frame buffers.
1037  *****************************************************************************
1038  * Returns VLC_SUCCESS on success.
1039  *****************************************************************************/
1040 static int FillBuffer( aout_instance_t *p_aout, int i_frame,
1041                        aout_buffer_t *p_buffer )
1042 {
1043     notification_thread_t *p_notif = p_aout->output.p_sys->p_notif;
1044     aout_sys_t *p_sys = p_aout->output.p_sys;
1045     void *p_write_position, *p_wrap_around;
1046     unsigned long l_bytes1, l_bytes2;
1047     HRESULT dsresult;
1048
1049     /* Before copying anything, we have to lock the buffer */
1050     dsresult = IDirectSoundBuffer_Lock(
1051                 p_sys->p_dsbuffer,                              /* DS buffer */
1052                 i_frame * p_notif->i_frame_size,             /* Start offset */
1053                 p_notif->i_frame_size,                    /* Number of bytes */
1054                 &p_write_position,                  /* Address of lock start */
1055                 &l_bytes1,       /* Count of bytes locked before wrap around */
1056                 &p_wrap_around,            /* Buffer adress (if wrap around) */
1057                 &l_bytes2,               /* Count of bytes after wrap around */
1058                 0 );                                                /* Flags */
1059     if( dsresult == DSERR_BUFFERLOST )
1060     {
1061         IDirectSoundBuffer_Restore( p_sys->p_dsbuffer );
1062         dsresult = IDirectSoundBuffer_Lock(
1063                                p_sys->p_dsbuffer,
1064                                i_frame * p_notif->i_frame_size,
1065                                p_notif->i_frame_size,
1066                                &p_write_position,
1067                                &l_bytes1,
1068                                &p_wrap_around,
1069                                &l_bytes2,
1070                                0 );
1071     }
1072     if( dsresult != DS_OK )
1073     {
1074         msg_Warn( p_notif, "cannot lock buffer" );
1075         if( p_buffer ) aout_BufferFree( p_buffer );
1076         return VLC_EGENERIC;
1077     }
1078
1079     if( p_buffer == NULL )
1080     {
1081         memset( p_write_position, 0, l_bytes1 );
1082     }
1083     else
1084     {
1085         if( p_sys->b_chan_reorder )
1086         {
1087             /* Do the channel reordering here */
1088             aout_ChannelReorder( p_buffer->p_buffer, p_buffer->i_buffer,
1089                                  p_sys->i_channels, p_sys->pi_chan_table,
1090                                  p_sys->i_bits_per_sample );
1091         }
1092
1093         vlc_memcpy( p_write_position, p_buffer->p_buffer, l_bytes1 );
1094         aout_BufferFree( p_buffer );
1095     }
1096
1097     /* Now the data has been copied, unlock the buffer */
1098     IDirectSoundBuffer_Unlock( p_sys->p_dsbuffer, p_write_position, l_bytes1,
1099                                p_wrap_around, l_bytes2 );
1100
1101     p_notif->i_write_slot = (i_frame + 1) % FRAMES_NUM;
1102     return VLC_SUCCESS;
1103 }
1104
1105 /*****************************************************************************
1106  * DirectSoundThread: this thread will capture play notification events.
1107  *****************************************************************************
1108  * We use this thread to emulate a callback mechanism. The thread probes for
1109  * event notification and fills up the DS secondary buffer when needed.
1110  *****************************************************************************/
1111 static void* DirectSoundThread( vlc_object_t *p_this )
1112 {
1113     notification_thread_t *p_notif = (notification_thread_t*)p_this;
1114     aout_instance_t *p_aout = p_notif->p_aout;
1115     bool b_sleek;
1116     mtime_t last_time;
1117     HRESULT dsresult;
1118     long l_queued = 0;
1119     int canc = vlc_savecancel ();
1120
1121     /* We don't want any resampling when using S/PDIF output */
1122     b_sleek = p_aout->output.output.i_format == VLC_CODEC_SPDIFL;
1123
1124     msg_Dbg( p_notif, "DirectSoundThread ready" );
1125
1126     /* Wait here until Play() is called */
1127     WaitForSingleObject( p_notif->event, INFINITE );
1128
1129     if( vlc_object_alive (p_notif) )
1130     {
1131         mwait( p_notif->start_date - AOUT_PTS_TOLERANCE / 2 );
1132
1133         /* start playing the buffer */
1134         dsresult = IDirectSoundBuffer_Play( p_aout->output.p_sys->p_dsbuffer,
1135                                         0,                         /* Unused */
1136                                         0,                         /* Unused */
1137                                         DSBPLAY_LOOPING );          /* Flags */
1138         if( dsresult == DSERR_BUFFERLOST )
1139         {
1140             IDirectSoundBuffer_Restore( p_aout->output.p_sys->p_dsbuffer );
1141             dsresult = IDirectSoundBuffer_Play(
1142                                             p_aout->output.p_sys->p_dsbuffer,
1143                                             0,                     /* Unused */
1144                                             0,                     /* Unused */
1145                                             DSBPLAY_LOOPING );      /* Flags */
1146         }
1147         if( dsresult != DS_OK )
1148         {
1149             msg_Err( p_aout, "cannot start playing buffer" );
1150         }
1151     }
1152     last_time = mdate();
1153
1154     while( vlc_object_alive (p_notif) )
1155     {
1156         long l_read, l_free_slots;
1157         unsigned i_frame_siz = p_aout->output.i_nb_samples;
1158         mtime_t mtime = mdate();
1159         int i;
1160
1161         /*
1162          * Fill in as much audio data as we can in our circular buffer
1163          */
1164
1165         /* Find out current play position */
1166         if FAILED( IDirectSoundBuffer_GetCurrentPosition(
1167                    p_aout->output.p_sys->p_dsbuffer, &l_read, NULL ) )
1168         {
1169             msg_Err( p_aout, "GetCurrentPosition() failed!" );
1170             l_read = 0;
1171         }
1172
1173         /* Detect underruns */
1174         if( l_queued && mtime - last_time >
1175             INT64_C(1000000) * l_queued / p_aout->output.output.i_rate )
1176         {
1177             msg_Dbg( p_aout, "detected underrun!" );
1178         }
1179         last_time = mtime;
1180
1181         /* Try to fill in as many frame buffers as possible */
1182         l_read /= (p_aout->output.output.i_bytes_per_frame /
1183             p_aout->output.output.i_frame_length);
1184         l_queued = p_notif->i_write_slot * i_frame_siz - l_read;
1185         if( l_queued < 0 ) l_queued += (i_frame_siz * FRAMES_NUM);
1186         l_free_slots = (FRAMES_NUM * i_frame_siz - l_queued) / i_frame_siz;
1187
1188         for( i = 0; i < l_free_slots; i++ )
1189         {
1190             aout_buffer_t *p_buffer = aout_OutputNextBuffer( p_aout,
1191                 mtime + INT64_C(1000000) * (i * i_frame_siz + l_queued) /
1192                 p_aout->output.output.i_rate, b_sleek );
1193
1194             /* If there is no audio data available and we have some buffered
1195              * already, then just wait for the next time */
1196             if( !p_buffer && (i || l_queued / i_frame_siz) ) break;
1197
1198             if( FillBuffer( p_aout, p_notif->i_write_slot % FRAMES_NUM,
1199                             p_buffer ) != VLC_SUCCESS ) break;
1200         }
1201
1202         /* Sleep a reasonable amount of time */
1203         l_queued += (i * i_frame_siz);
1204         msleep( INT64_C(1000000) * l_queued / p_aout->output.output.i_rate / 2 );
1205     }
1206
1207     /* make sure the buffer isn't playing */
1208     IDirectSoundBuffer_Stop( p_aout->output.p_sys->p_dsbuffer );
1209
1210     /* free the event */
1211     CloseHandle( p_notif->event );
1212
1213     vlc_restorecancel (canc);
1214     msg_Dbg( p_notif, "DirectSoundThread exiting" );
1215     return NULL;
1216 }