]> git.sesse.net Git - vlc/blob - modules/audio_output/directx.c
* modules/audio_output/directx.c: forgot to enable channel re-ordering.
[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.13 2003/02/19 22:08:39 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", 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         /* To prevent channel re-ordering */
634         waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
635         waveformat.Format.wBitsPerSample = 16;
636         waveformat.Samples.wValidBitsPerSample =
637             waveformat.Format.wBitsPerSample;
638         waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
639         waveformat.SubFormat = KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
640         break;
641
642     case VLC_FOURCC('f','l','3','2'):
643         waveformat.Format.wBitsPerSample = sizeof(float) * 8;
644         waveformat.Samples.wValidBitsPerSample =
645             waveformat.Format.wBitsPerSample;
646         waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
647         waveformat.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
648         break;
649
650     case VLC_FOURCC('s','1','6','l'):
651         waveformat.Format.wBitsPerSample = 16;
652         waveformat.Samples.wValidBitsPerSample =
653             waveformat.Format.wBitsPerSample;
654         waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
655         waveformat.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
656         break;
657     }
658
659     waveformat.Format.nChannels = i_nb_channels;
660     waveformat.Format.nSamplesPerSec = i_rate;
661     waveformat.Format.nBlockAlign =
662         waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
663     waveformat.Format.nAvgBytesPerSec =
664         waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;
665
666     /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
667     if( i_nb_channels <= 2 )
668     {
669         waveformat.Format.cbSize = 0;
670     }
671     else
672     {
673         waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
674         waveformat.Format.cbSize =
675             sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
676     }
677
678
679     /* Then fill in the direct sound descriptor */
680     memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
681     dsbdesc.dwSize = sizeof(DSBUFFERDESC);
682     dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2/* Better position accuracy */
683                     | DSBCAPS_CTRLPOSITIONNOTIFY     /* We need notification */
684                     | DSBCAPS_GLOBALFOCUS;      /* Allows background playing */
685     dsbdesc.dwBufferBytes = FRAMES_NUM * i_bytes_per_frame;   /* buffer size */
686     dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&waveformat;
687
688     if FAILED( IDirectSound_CreateSoundBuffer(
689                    p_aout->output.p_sys->p_dsobject, &dsbdesc,
690                    &p_aout->output.p_sys->p_dsbuffer, NULL) )
691     {
692         goto error;
693     }
694
695     /* Stop here if we were just probing */
696     if( b_probe )
697     {
698         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
699         p_aout->output.p_sys->p_dsbuffer = NULL;
700         return VLC_SUCCESS;
701     }
702
703     /* Backup the size of a frame */
704     p_aout->output.p_sys->p_notif->i_frame_size = i_bytes_per_frame;
705
706     /* Now the secondary buffer is created, we need to setup its position
707      * notification */
708     for( i = 0; i < FRAMES_NUM; i++ )
709     {
710         p_aout->output.p_sys->p_notif->p_events[i].dwOffset = i *
711             p_aout->output.p_sys->p_notif->i_frame_size;
712
713         p_aout->output.p_sys->p_notif->i_frame_status[i] = FRAME_EMPTY;
714     }
715
716     /* Get the IDirectSoundNotify interface */
717     if FAILED( IDirectSoundBuffer_QueryInterface(
718                                 p_aout->output.p_sys->p_dsbuffer,
719                                 &IID_IDirectSoundNotify,
720                                 (LPVOID *)&p_aout->output.p_sys->p_dsnotify ) )
721     {
722         msg_Err( p_aout, "cannot get IDirectSoundNotify interface" );
723         goto error;
724     }
725
726     if FAILED( IDirectSoundNotify_SetNotificationPositions(
727                                     p_aout->output.p_sys->p_dsnotify,
728                                     FRAMES_NUM,
729                                     p_aout->output.p_sys->p_notif->p_events ) )
730     {
731         msg_Err( p_aout, "cannot set position notification" );
732         goto error;
733     }
734
735     p_aout->output.p_sys->i_channel_mask = waveformat.dwChannelMask;
736     CheckReordering( p_aout, i_nb_channels );
737
738     return VLC_SUCCESS;
739
740  error:
741     if( p_aout->output.p_sys->p_dsbuffer )
742     {
743         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
744         p_aout->output.p_sys->p_dsbuffer = NULL;
745     }
746     if( p_aout->output.p_sys->p_dsnotify )
747     {
748         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
749         p_aout->output.p_sys->p_dsnotify = NULL;
750     }
751     return VLC_EGENERIC;
752 }
753
754 /*****************************************************************************
755  * CreateDSBufferPCM: creates a PCM direct sound buffer.
756  *****************************************************************************
757  * We first try to create a WAVE_FORMAT_IEEE_FLOAT buffer if supported by
758  * the hardware, otherwise we create a WAVE_FORMAT_PCM buffer.
759  ****************************************************************************/
760 static int CreateDSBufferPCM( aout_instance_t *p_aout, int *i_format,
761                               int i_channels, int i_nb_channels, int i_rate,
762                               vlc_bool_t b_probe )
763 {
764     if( CreateDSBuffer( p_aout, VLC_FOURCC('f','l','3','2'),
765                         i_channels, i_nb_channels, i_rate,
766                         FRAME_SIZE * 4 * i_nb_channels, b_probe )
767         != VLC_SUCCESS )
768     {
769         if ( CreateDSBuffer( p_aout, VLC_FOURCC('s','1','6','l'),
770                              i_channels, i_nb_channels, i_rate,
771                              FRAME_SIZE * 2 * i_nb_channels, b_probe )
772              != VLC_SUCCESS )
773         {
774             return VLC_EGENERIC;
775         }
776         else
777         {
778             *i_format = VLC_FOURCC('s','1','6','l');
779             return VLC_SUCCESS;
780         }
781     }
782     else
783     {
784         *i_format = VLC_FOURCC('f','l','3','2');
785         return VLC_SUCCESS;
786     }
787 }
788
789 /*****************************************************************************
790  * DestroyDSBuffer
791  *****************************************************************************
792  * This function destroys the secondary buffer.
793  *****************************************************************************/
794 static void DestroyDSBuffer( aout_instance_t *p_aout )
795 {
796     if( p_aout->output.p_sys->p_dsnotify )
797     {
798         IDirectSoundNotify_Release( p_aout->output.p_sys->p_dsnotify );
799         p_aout->output.p_sys->p_dsnotify = NULL;
800     }
801
802     if( p_aout->output.p_sys->p_dsbuffer )
803     {
804         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
805         p_aout->output.p_sys->p_dsbuffer = NULL;
806     }
807 }
808
809 /*****************************************************************************
810  * FillBuffer: Fill in one of the direct sound frame buffers.
811  *****************************************************************************
812  * Returns VLC_SUCCESS on success.
813  *****************************************************************************/
814 static int FillBuffer( aout_instance_t *p_aout, int i_frame,
815                        aout_buffer_t *p_buffer )
816 {
817     notification_thread_t *p_notif = p_aout->output.p_sys->p_notif;
818     void *p_write_position, *p_wrap_around;
819     long l_bytes1, l_bytes2;
820     HRESULT dsresult;
821
822     /* Before copying anything, we have to lock the buffer */
823     dsresult = IDirectSoundBuffer_Lock(
824                 p_aout->output.p_sys->p_dsbuffer,               /* DS buffer */
825                 i_frame * p_notif->i_frame_size,             /* Start offset */
826                 p_notif->i_frame_size,                    /* Number of bytes */
827                 &p_write_position,                  /* Address of lock start */
828                 &l_bytes1,       /* Count of bytes locked before wrap around */
829                 &p_wrap_around,            /* Buffer adress (if wrap around) */
830                 &l_bytes2,               /* Count of bytes after wrap around */
831                 0 );                                                /* Flags */
832     if( dsresult == DSERR_BUFFERLOST )
833     {
834         IDirectSoundBuffer_Restore( p_aout->output.p_sys->p_dsbuffer );
835         dsresult = IDirectSoundBuffer_Lock(
836                                p_aout->output.p_sys->p_dsbuffer,
837                                i_frame * p_notif->i_frame_size,
838                                p_notif->i_frame_size,
839                                &p_write_position,
840                                &l_bytes1,
841                                &p_wrap_around,
842                                &l_bytes2,
843                                0 );
844     }
845     if( dsresult != DS_OK )
846     {
847         msg_Warn( p_notif, "cannot lock buffer" );
848         if( p_buffer ) aout_BufferFree( p_buffer );
849         return VLC_EGENERIC;
850     }
851
852     if( p_buffer == NULL )
853     {
854         memset( p_write_position, 0, l_bytes1 );
855     }
856     else if( p_aout->output.p_sys->b_chan_reorder )
857     {
858         /* Do the channel reordering here */
859
860         if( p_aout->output.output.i_format ==  VLC_FOURCC('s','1','6','l') )
861           InterleaveS16( (int16_t *)p_buffer->p_buffer,
862                          (int16_t *)p_write_position,
863                          p_aout->output.p_sys->pi_chan_table,
864                          aout_FormatNbChannels( &p_aout->output.output ) );
865         else
866           InterleaveFloat32( (float *)p_buffer->p_buffer,
867                              (float *)p_write_position,
868                              p_aout->output.p_sys->pi_chan_table,
869                              aout_FormatNbChannels( &p_aout->output.output ) );
870     }
871     else
872     {
873         p_aout->p_vlc->pf_memcpy( p_write_position, p_buffer->p_buffer,
874                                   l_bytes1 );
875         aout_BufferFree( p_buffer );
876     }
877
878     /* Now the data has been copied, unlock the buffer */
879     IDirectSoundBuffer_Unlock( p_aout->output.p_sys->p_dsbuffer,
880                                p_write_position, l_bytes1,
881                                p_wrap_around, l_bytes2 );
882
883     return VLC_SUCCESS;
884 }
885
886 /*****************************************************************************
887  * DirectSoundThread: this thread will capture play notification events. 
888  *****************************************************************************
889  * We use this thread to emulate a callback mechanism. The thread probes for
890  * event notification and fills up the DS secondary buffer when needed.
891  *****************************************************************************/
892 static void DirectSoundThread( notification_thread_t *p_notif )
893 {
894     HANDLE  notification_events[FRAMES_NUM];
895     HRESULT dsresult;
896     aout_instance_t *p_aout = p_notif->p_aout;
897     int i, i_which_frame, i_last_frame, i_next_frame;
898     mtime_t mtime;
899     vlc_bool_t b_sleek;
900
901     for( i = 0; i < FRAMES_NUM; i++ )
902         notification_events[i] = p_notif->p_events[i].hEventNotify;
903
904     /* We don't want any resampling when using S/PDIF output */
905     b_sleek = p_aout->output.output.i_format == VLC_FOURCC('s','p','d','i');
906
907     /* Tell the main thread that we are ready */
908     vlc_thread_ready( p_notif );
909
910     msg_Dbg( p_notif, "DirectSoundThread ready" );
911
912     /* Wait here until Play() is called */
913     WaitForSingleObject( notification_events[0], INFINITE );
914
915     if( !p_notif->b_die )
916     {
917         mwait( p_notif->start_date - AOUT_PTS_TOLERANCE / 2 );
918
919         /* start playing the buffer */
920         dsresult = IDirectSoundBuffer_Play( p_aout->output.p_sys->p_dsbuffer,
921                                         0,                         /* Unused */
922                                         0,                         /* Unused */
923                                         DSBPLAY_LOOPING );          /* Flags */
924         if( dsresult == DSERR_BUFFERLOST )
925         {
926             IDirectSoundBuffer_Restore( p_aout->output.p_sys->p_dsbuffer );
927             dsresult = IDirectSoundBuffer_Play(
928                                             p_aout->output.p_sys->p_dsbuffer,
929                                             0,                     /* Unused */
930                                             0,                     /* Unused */
931                                             DSBPLAY_LOOPING );      /* Flags */
932         }
933         if( dsresult != DS_OK )
934         {
935             msg_Err( p_aout, "cannot start playing buffer" );
936         }
937     }
938
939     while( !p_notif->b_die )
940     {
941         aout_buffer_t *p_buffer;
942         long l_latency;
943
944         /* wait for the position notification */
945         i_which_frame = WaitForMultipleObjects( FRAMES_NUM,
946                                                 notification_events, 0,
947                                                 INFINITE ) - WAIT_OBJECT_0;
948
949         if( p_notif->b_die )
950             break;
951
952         mtime = mdate();
953
954         /* We take into account the current latency */
955         if SUCCEEDED( IDirectSoundBuffer_GetCurrentPosition(
956                         p_aout->output.p_sys->p_dsbuffer,
957                         &l_latency, NULL ) )
958         {
959             if( l_latency > (i_which_frame * FRAME_SIZE)
960                   && l_latency < ((i_which_frame+1) * FRAME_SIZE) )
961             {
962                 l_latency = - ( l_latency /
963                                 p_aout->output.output.i_bytes_per_frame %
964                                 FRAME_SIZE );
965             }
966             else
967             {
968                 l_latency = FRAME_SIZE - ( l_latency /
969                                       p_aout->output.output.i_bytes_per_frame %
970                                       FRAME_SIZE );
971             }
972         }
973         else
974         {
975             l_latency = 0;
976         }
977
978         /* Mark last frame as empty */
979         i_last_frame = (i_which_frame + FRAMES_NUM -1) % FRAMES_NUM;
980         i_next_frame = (i_which_frame + 1) % FRAMES_NUM;
981         p_notif->i_frame_status[i_last_frame] = FRAME_EMPTY;
982
983         /* Try to fill in as many frame buffers as possible */
984         for( i = i_next_frame; (i % FRAMES_NUM) != i_which_frame; i++ )
985         {
986
987             /* Check if frame buf is already filled */
988             if( p_notif->i_frame_status[i % FRAMES_NUM] == FRAME_QUEUED )
989                 continue;
990
991             p_buffer = aout_OutputNextBuffer( p_aout,
992                 mtime + 1000000 / p_aout->output.output.i_rate *
993                 ((i - i_next_frame + 1) * FRAME_SIZE + l_latency), b_sleek );
994
995             /* If there is no audio data available and we have some buffered
996              * already, then just wait for the next time */
997             if( !p_buffer && (i != i_next_frame) )
998             {
999                 //msg_Err( p_aout, "only %i frame buffers filled!",
1000                 //         i - i_next_frame );
1001                 break;
1002             }
1003
1004             if( FillBuffer( p_aout, (i%FRAMES_NUM), p_buffer )
1005                 != VLC_SUCCESS )
1006                 break;
1007
1008             /* Mark the frame buffer as QUEUED */
1009             p_notif->i_frame_status[i%FRAMES_NUM] = FRAME_QUEUED;
1010         }
1011
1012     }
1013
1014     /* make sure the buffer isn't playing */
1015     IDirectSoundBuffer_Stop( p_aout->output.p_sys->p_dsbuffer );
1016
1017     /* free the events */
1018     for( i = 0; i < FRAMES_NUM; i++ )
1019         CloseHandle( notification_events[i] );
1020
1021     msg_Dbg( p_notif, "DirectSoundThread exiting" );
1022 }
1023
1024 /*****************************************************************************
1025  * CheckReordering: Check if we need to do some channel re-ordering (the ac3
1026  *                  channel order is different from the one chosen by
1027  *                  Microsoft).
1028  *****************************************************************************/
1029 static void CheckReordering( aout_instance_t *p_aout, int i_nb_channels )
1030 {
1031     int i, j, k, l;
1032
1033 #define i_channel_mask p_aout->output.p_sys->i_channel_mask
1034 #define pi_chan_table p_aout->output.p_sys->pi_chan_table
1035
1036     p_aout->output.p_sys->b_chan_reorder = VLC_FALSE;
1037
1038     pi_chan_table = malloc( i_nb_channels * sizeof(int) );
1039     if( !pi_chan_table )
1040     {
1041         return;
1042     }
1043
1044     for( i = 0, j = 0;
1045          i < (int)(sizeof(pi_channels_out)/sizeof(uint32_t)); i++ )
1046     {
1047         if( i_channel_mask & pi_channels_out[i] )
1048         {
1049             for( k = 0, l = 0;
1050                  pi_channels_out[i] != pi_channels_ordered[k]; k++ )
1051             {
1052                 if( i_channel_mask & pi_channels_ordered[k] )
1053                 {
1054                     l++;
1055                 }
1056             }
1057
1058             pi_chan_table[j] = l;
1059
1060             j++;
1061         }
1062     }
1063
1064     for( i = 0; i < i_nb_channels; i++ )
1065     {
1066         if( pi_chan_table[i] != i )
1067         {
1068             p_aout->output.p_sys->b_chan_reorder = VLC_TRUE;
1069         }
1070     }
1071
1072     if( p_aout->output.p_sys->b_chan_reorder )
1073     {
1074         msg_Dbg( p_aout, "channel reordering needed" );
1075     }
1076
1077 #undef pi_chan_table
1078 #undef waveformat
1079 }
1080
1081 /*****************************************************************************
1082  * InterleaveFloat32/S16: change the channel order to the Microsoft one.
1083  *****************************************************************************/
1084 static void InterleaveFloat32( float *p_buf, float *p_buf_out,
1085                                int *pi_chan_table, int i_nb_channels )
1086 {
1087     int i, j;
1088
1089     for( i = 0; i < FRAME_SIZE; i++ )
1090     {
1091         for( j = 0; j < i_nb_channels; j++ )
1092         {
1093             p_buf_out[i*i_nb_channels + pi_chan_table[j]] =
1094                 p_buf[i*i_nb_channels + j];
1095         }
1096     }
1097 }
1098
1099 static void InterleaveS16( int16_t *p_buf, int16_t *p_buf_out,
1100                            int *pi_chan_table, int i_nb_channels )
1101 {
1102     int i, j;
1103
1104     for( i = 0; i < FRAME_SIZE; i++ )
1105     {
1106         for( j = 0; j < i_nb_channels; j++ )
1107         {
1108             p_buf_out[ i*i_nb_channels + pi_chan_table[j]] =
1109                 p_buf[i*i_nb_channels + j];
1110         }
1111     }
1112 }