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