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