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