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