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