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