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