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