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