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