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