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