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