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