]> git.sesse.net Git - vlc/blob - modules/audio_output/directx.c
Cosmetics: DirectX now sets maximum volume without returning an error.
[vlc] / modules / audio_output / directx.c
1 /*****************************************************************************
2  * directx.c: Windows DirectX audio output method
3  *****************************************************************************
4  * Copyright (C) 2001-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation, Inc.,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <math.h>
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_aout.h>
37 #include <vlc_charset.h>
38 #include <vlc_atomic.h>
39
40 #include "windows_audio_common.h"
41
42 /*****************************************************************************
43  * notification_thread_t: DirectX event thread
44  *****************************************************************************/
45 typedef struct notification_thread_t
46 {
47     int i_frame_size;                          /* size in bytes of one frame */
48     int i_write_slot;       /* current write position in our circular buffer */
49
50     mtime_t start_date;
51     HANDLE event;
52
53     vlc_thread_t thread;
54     vlc_atomic_t abort;
55
56 } notification_thread_t;
57
58 /*****************************************************************************
59  * aout_sys_t: directx audio output method descriptor
60  *****************************************************************************
61  * This structure is part of the audio output thread descriptor.
62  * It describes the direct sound specific properties of an audio device.
63  *****************************************************************************/
64 struct aout_sys_t
65 {
66     aout_packet_t       packet;
67     HINSTANCE           hdsound_dll;      /* handle of the opened dsound dll */
68
69     LPDIRECTSOUND       p_dsobject;              /* main Direct Sound object */
70     LPDIRECTSOUNDBUFFER p_dsbuffer;   /* the sound buffer we use (direct sound
71                                        * takes care of mixing all the
72                                        * secondary buffers into the primary) */
73     struct
74     {
75         LONG             volume;
76         LONG             mb;
77         bool             mute;
78     } volume;
79
80     notification_thread_t notif;                  /* DirectSoundThread id */
81
82     int      i_frame_size;                     /* Size in bytes of one frame */
83
84     int      i_speaker_setup;                      /* Speaker setup override */
85
86     uint8_t  chans_to_reorder;              /* do we need channel reordering */
87     uint8_t  chan_table[AOUT_CHAN_MAX];
88     uint32_t i_channel_mask;
89     vlc_fourcc_t format;
90 };
91
92 /*****************************************************************************
93  * Local prototypes.
94  *****************************************************************************/
95 static int  Open( vlc_object_t * );
96 static void Close( vlc_object_t * );
97 static void Stop( audio_output_t * );
98 static void Play       ( audio_output_t *, block_t * );
99 static int  VolumeSet  ( audio_output_t *, float );
100 static int  MuteSet    ( audio_output_t *, bool );
101
102 /* local functions */
103 static void Probe( audio_output_t *, const audio_sample_format_t * );
104 static int  InitDirectSound   ( audio_output_t * );
105 static int  CreateDSBuffer    ( audio_output_t *, int, int, int, int, int, bool );
106 static int  CreateDSBufferPCM ( audio_output_t *, vlc_fourcc_t*, int, int, bool );
107 static void DestroyDSBuffer   ( audio_output_t * );
108 static void* DirectSoundThread( void * );
109 static int  FillBuffer        ( audio_output_t *, int, block_t * );
110
111 static int ReloadDirectXDevices( vlc_object_t *, const char *,
112                                  char ***, char *** );
113
114 /* Speaker setup override options list */
115 static const char *const speaker_list[] = { "Windows default", "Mono", "Stereo",
116                                             "Quad", "5.1", "7.1" };
117
118 /*****************************************************************************
119  * Module descriptor
120  *****************************************************************************/
121 #define DEVICE_TEXT N_("Output device")
122 #define DEVICE_LONGTEXT N_("Select your audio output device")
123
124 #define SPEAKER_TEXT N_("Speaker configuration")
125 #define SPEAKER_LONGTEXT N_("Select speaker configuration you want to use. " \
126     "This option doesn't upmix! So NO e.g. Stereo -> 5.1 conversion." )
127
128 #define VOLUME_TEXT N_("Audio volume")
129 #define VOLUME_LONGTEXT N_("Audio volume in hundredths of decibels (dB).")
130
131 vlc_module_begin ()
132     set_description( N_("DirectX audio output") )
133     set_shortname( "DirectX" )
134     set_capability( "audio output", 100 )
135     set_category( CAT_AUDIO )
136     set_subcategory( SUBCAT_AUDIO_AOUT )
137     add_shortcut( "directx", "aout_directx" )
138
139     add_string( "directx-audio-device", NULL,
140              DEVICE_TEXT, DEVICE_LONGTEXT, false )
141         change_string_cb( ReloadDirectXDevices )
142     add_obsolete_string( "directx-audio-device-name")
143     add_bool( "directx-audio-float32", false, FLOAT_TEXT,
144               FLOAT_LONGTEXT, true )
145     add_string( "directx-audio-speaker", "Windows default",
146                  SPEAKER_TEXT, SPEAKER_LONGTEXT, true )
147         change_string_list( speaker_list, speaker_list )
148     add_integer( "directx-volume", DSBVOLUME_MAX,
149                  VOLUME_TEXT, VOLUME_LONGTEXT, true )
150         change_integer_range( DSBVOLUME_MIN, DSBVOLUME_MAX )
151
152     set_callbacks( Open, Close )
153 vlc_module_end ()
154
155 /*****************************************************************************
156  * OpenAudio: open the audio device
157  *****************************************************************************
158  * This function opens and setups Direct Sound.
159  *****************************************************************************/
160 static int Start( audio_output_t *p_aout, audio_sample_format_t *restrict fmt )
161 {
162     vlc_value_t val;
163     char * psz_speaker;
164     int i = 0;
165
166     const char * const * ppsz_compare = speaker_list;
167
168     msg_Dbg( p_aout, "Opening DirectSound Audio Output" );
169
170     /* Retrieve config values */
171     var_Create( p_aout, "directx-audio-float32",
172                 VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
173     psz_speaker = var_CreateGetString( p_aout, "directx-audio-speaker" );
174
175     while ( *ppsz_compare != NULL )
176     {
177         if ( !strncmp( *ppsz_compare, psz_speaker, strlen(*ppsz_compare) ) )
178         {
179             break;
180         }
181         ppsz_compare++; i++;
182     }
183
184     if ( *ppsz_compare == NULL )
185     {
186         msg_Err( p_aout, "(%s) isn't valid speaker setup option", psz_speaker );
187         msg_Err( p_aout, "Defaulting to Windows default speaker config");
188         i = 0;
189     }
190     free( psz_speaker );
191     p_aout->sys->i_speaker_setup = i;
192
193     /* Initialise DirectSound */
194     if( InitDirectSound( p_aout ) )
195     {
196         msg_Err( p_aout, "cannot initialize DirectSound" );
197         goto error;
198     }
199
200     if( var_Type( p_aout, "audio-device" ) == 0 )
201     {
202         Probe( p_aout, fmt );
203     }
204
205     if( var_Get( p_aout, "audio-device", &val ) < 0 )
206     {
207         msg_Err( p_aout, "DirectSound Probe failed()" );
208         goto error;
209     }
210
211     /* Open the device */
212     if( val.i_int == AOUT_VAR_SPDIF )
213     {
214         fmt->i_format = VLC_CODEC_SPDIFL;
215
216         /* Calculate the frame size in bytes */
217         fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
218         fmt->i_frame_length = A52_FRAME_NB;
219         p_aout->sys->i_frame_size = fmt->i_bytes_per_frame;
220
221         if( CreateDSBuffer( p_aout, VLC_CODEC_SPDIFL,
222                             fmt->i_physical_channels,
223                             aout_FormatNbChannels( fmt ), fmt->i_rate,
224                             p_aout->sys->i_frame_size, false )
225             != VLC_SUCCESS )
226         {
227             msg_Err( p_aout, "cannot open directx audio device" );
228             goto error;
229         }
230
231         aout_PacketInit( p_aout, &p_aout->sys->packet, A52_FRAME_NB, fmt );
232     }
233     else
234     {
235         if( val.i_int == AOUT_VAR_5_1 )
236             fmt->i_physical_channels = AOUT_CHANS_5_0;
237         else if( val.i_int == AOUT_VAR_7_1 )
238             fmt->i_physical_channels = AOUT_CHANS_7_1;
239         else if( val.i_int == AOUT_VAR_3F2R )
240             fmt->i_physical_channels = AOUT_CHANS_5_0;
241         else if( val.i_int == AOUT_VAR_2F2R )
242             fmt->i_physical_channels = AOUT_CHANS_4_0;
243         else if( val.i_int == AOUT_VAR_MONO )
244             fmt->i_physical_channels = AOUT_CHAN_CENTER;
245         else
246             fmt->i_physical_channels = AOUT_CHANS_2_0;
247
248         aout_FormatPrepare( fmt );
249
250         if( CreateDSBufferPCM( p_aout, &fmt->i_format,
251                                fmt->i_physical_channels, fmt->i_rate, false )
252             != VLC_SUCCESS )
253         {
254             msg_Err( p_aout, "cannot open directx audio device" );
255             goto error;
256         }
257
258         /* Calculate the frame size in bytes */
259         aout_PacketInit( p_aout, &p_aout->sys->packet, fmt->i_rate / 20, fmt );
260     }
261
262     /* Force volume update in thread. TODO: use session volume on Vista+ */
263     p_aout->sys->volume.volume = p_aout->sys->volume.mb;
264
265     /* Now we need to setup our DirectSound play notification structure */
266     vlc_atomic_set(&p_aout->sys->notif.abort, 0);
267     p_aout->sys->notif.event = CreateEvent( 0, FALSE, FALSE, 0 );
268     if( unlikely(p_aout->sys->notif.event == NULL) )
269         abort();
270     p_aout->sys->notif.i_frame_size =  p_aout->sys->i_frame_size;
271
272     /* then launch the notification thread */
273     msg_Dbg( p_aout, "creating DirectSoundThread" );
274     if( vlc_clone( &p_aout->sys->notif.thread, DirectSoundThread, p_aout,
275                    VLC_THREAD_PRIORITY_HIGHEST ) )
276     {
277         msg_Err( p_aout, "cannot create DirectSoundThread" );
278         CloseHandle( p_aout->sys->notif.event );
279         p_aout->sys->notif.event = NULL;
280         aout_PacketDestroy( p_aout );
281         goto error;
282     }
283
284     p_aout->time_get = aout_PacketTimeGet;
285     p_aout->play = Play;
286     p_aout->pause = NULL;
287     p_aout->flush = aout_PacketFlush;
288     return VLC_SUCCESS;
289
290  error:
291     Stop( p_aout );
292     return VLC_EGENERIC;
293 }
294
295 /*****************************************************************************
296  * Probe: probe the audio device for available formats and channels
297  *****************************************************************************/
298 static void Probe( audio_output_t * p_aout, const audio_sample_format_t *fmt )
299 {
300     vlc_value_t val, text;
301     vlc_fourcc_t i_format;
302     DWORD ui_speaker_config;
303     bool is_default_output_set = false;
304
305     var_Create( p_aout, "audio-device", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
306     text.psz_string = _("Audio Device");
307     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
308
309     /* Test for 5.1 support */
310     if( fmt->i_physical_channels == AOUT_CHANS_5_1 )
311     {
312         if( CreateDSBufferPCM( p_aout, &i_format, AOUT_CHANS_5_1,
313                                fmt->i_rate, true ) == VLC_SUCCESS )
314         {
315             val.i_int = AOUT_VAR_5_1;
316             text.psz_string = (char*) "5.1";
317             var_Change( p_aout, "audio-device",
318                         VLC_VAR_ADDCHOICE, &val, &text );
319             var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
320             is_default_output_set = true;
321             msg_Dbg( p_aout, "device supports 5.1 channels" );
322         }
323     }
324
325     /* Test for 7.1 support */
326     if( fmt->i_physical_channels == AOUT_CHANS_7_1 )
327     {
328         if( CreateDSBufferPCM( p_aout, &i_format, AOUT_CHANS_7_1,
329                                fmt->i_rate, true ) == VLC_SUCCESS )
330         {
331             val.i_int = AOUT_VAR_7_1;
332             text.psz_string = (char*) "7.1";
333             var_Change( p_aout, "audio-device",
334                         VLC_VAR_ADDCHOICE, &val, &text );
335             var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
336             is_default_output_set = true;
337             msg_Dbg( p_aout, "device supports 7.1 channels" );
338         }
339     }
340
341     /* Test for 3 Front 2 Rear support */
342     if( fmt->i_physical_channels == AOUT_CHANS_5_0 )
343     {
344         if( CreateDSBufferPCM( p_aout, &i_format, AOUT_CHANS_5_0,
345                                fmt->i_rate, true ) == VLC_SUCCESS )
346         {
347             val.i_int = AOUT_VAR_3F2R;
348             text.psz_string = _("3 Front 2 Rear");
349             var_Change( p_aout, "audio-device",
350                         VLC_VAR_ADDCHOICE, &val, &text );
351             if(!is_default_output_set)
352             {
353                 var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
354                 is_default_output_set = true;
355             }
356             msg_Dbg( p_aout, "device supports 5 channels" );
357         }
358     }
359
360     /* Test for 2 Front 2 Rear support */
361     if( ( fmt->i_physical_channels & AOUT_CHANS_4_0 ) == AOUT_CHANS_4_0 )
362     {
363         if( CreateDSBufferPCM( p_aout, &i_format, AOUT_CHANS_4_0,
364                                fmt->i_rate, true ) == VLC_SUCCESS )
365         {
366             val.i_int = AOUT_VAR_2F2R;
367             text.psz_string = _("2 Front 2 Rear");
368             var_Change( p_aout, "audio-device",
369                         VLC_VAR_ADDCHOICE, &val, &text );
370             if(!is_default_output_set)
371             {
372                 var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
373                 is_default_output_set = true;
374             }
375             msg_Dbg( p_aout, "device supports 4 channels" );
376         }
377     }
378
379     /* Test for stereo support */
380     if( CreateDSBufferPCM( p_aout, &i_format, AOUT_CHANS_2_0,
381                            fmt->i_rate, true ) == VLC_SUCCESS )
382     {
383         val.i_int = AOUT_VAR_STEREO;
384         text.psz_string = _("Stereo");
385         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
386         if(!is_default_output_set)
387         {
388             var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
389             is_default_output_set = true;
390             msg_Dbg( p_aout, "device supports 2 channels (DEFAULT!)" );
391         }
392         else msg_Dbg( p_aout, "device supports 2 channels" );
393     }
394
395     /* Test for mono support */
396     if( CreateDSBufferPCM( p_aout, &i_format, AOUT_CHAN_CENTER,
397                            fmt->i_rate, true ) == VLC_SUCCESS )
398     {
399         val.i_int = AOUT_VAR_MONO;
400         text.psz_string = _("Mono");
401         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
402         msg_Dbg( p_aout, "device supports 1 channel" );
403     }
404
405     /* Check the speaker configuration to determine which channel config should
406      * be the default */
407     if FAILED( IDirectSound_GetSpeakerConfig( p_aout->sys->p_dsobject,
408                                               &ui_speaker_config ) )
409     {
410         ui_speaker_config = DSSPEAKER_STEREO;
411         msg_Dbg( p_aout, "GetSpeakerConfig failed" );
412     }
413     switch( DSSPEAKER_CONFIG(ui_speaker_config) )
414     {
415     case DSSPEAKER_7POINT1:
416     case DSSPEAKER_7POINT1_SURROUND:
417         msg_Dbg( p_aout, "Windows says your SpeakerConfig is 7.1" );
418         val.i_int = AOUT_VAR_7_1;
419         break;
420     case DSSPEAKER_5POINT1:
421     case DSSPEAKER_5POINT1_SURROUND:
422         msg_Dbg( p_aout, "Windows says your SpeakerConfig is 5.1" );
423         val.i_int = AOUT_VAR_5_1;
424         break;
425     case DSSPEAKER_QUAD:
426         msg_Dbg( p_aout, "Windows says your SpeakerConfig is Quad" );
427         val.i_int = AOUT_VAR_2F2R;
428         break;
429 #if 0 /* Lots of people just get their settings wrong and complain that
430        * this is a problem with VLC so just don't ever set mono by default. */
431     case DSSPEAKER_MONO:
432         val.i_int = AOUT_VAR_MONO;
433         break;
434 #endif
435     case DSSPEAKER_SURROUND:
436         msg_Dbg( p_aout, "Windows says your SpeakerConfig is surround" );
437     case DSSPEAKER_STEREO:
438         msg_Dbg( p_aout, "Windows says your SpeakerConfig is stereo" );
439     default:
440         /* If nothing else is found, choose stereo output */
441         val.i_int = AOUT_VAR_STEREO;
442         break;
443     }
444
445     /* Check if we want to override speaker config */
446     switch( p_aout->sys->i_speaker_setup )
447     {
448     case 0: /* Default value aka Windows default speaker setup */
449         break;
450     case 1: /* Mono */
451         msg_Dbg( p_aout, "SpeakerConfig is forced to Mono" );
452         val.i_int = AOUT_VAR_MONO;
453         break;
454     case 2: /* Stereo */
455         msg_Dbg( p_aout, "SpeakerConfig is forced to Stereo" );
456         val.i_int = AOUT_VAR_STEREO;
457         break;
458     case 3: /* Quad */
459         msg_Dbg( p_aout, "SpeakerConfig is forced to Quad" );
460         val.i_int = AOUT_VAR_2F2R;
461         break;
462     case 4: /* 5.1 */
463         msg_Dbg( p_aout, "SpeakerConfig is forced to 5.1" );
464         val.i_int = AOUT_VAR_5_1;
465         break;
466     case 5: /* 7.1 */
467         msg_Dbg( p_aout, "SpeakerConfig is forced to 7.1" );
468         val.i_int = AOUT_VAR_7_1;
469         break;
470     default:
471         msg_Dbg( p_aout, "SpeakerConfig is forced to non-existing value" );
472         break;
473     }
474
475     var_Set( p_aout, "audio-device", val );
476
477     /* Test for SPDIF support */
478     if ( AOUT_FMT_SPDIF( fmt ) )
479     {
480         if( CreateDSBuffer( p_aout, VLC_CODEC_SPDIFL,
481                             fmt->i_physical_channels,
482                             aout_FormatNbChannels( fmt ), fmt->i_rate,
483                             AOUT_SPDIF_SIZE, true )
484             == VLC_SUCCESS )
485         {
486             msg_Dbg( p_aout, "device supports A/52 over S/PDIF" );
487             val.i_int = AOUT_VAR_SPDIF;
488             text.psz_string = _("A/52 over S/PDIF");
489             var_Change( p_aout, "audio-device",
490                         VLC_VAR_ADDCHOICE, &val, &text );
491             if( var_InheritBool( p_aout, "spdif" ) )
492                 var_Set( p_aout, "audio-device", val );
493         }
494     }
495
496     var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
497     if( val.i_int <= 0 )
498     {
499         /* Probe() has failed. */
500         var_Destroy( p_aout, "audio-device" );
501         return;
502     }
503
504     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
505 }
506
507 /*****************************************************************************
508  * Play: we'll start playing the directsound buffer here because at least here
509  *       we know the first buffer has been put in the aout fifo and we also
510  *       know its date.
511  *****************************************************************************/
512 static void Play( audio_output_t *p_aout, block_t *p_buffer )
513 {
514     /* get the playing date of the first aout buffer */
515     p_aout->sys->notif.start_date = p_buffer->i_pts;
516
517     /* fill in the first samples (zeroes) */
518     FillBuffer( p_aout, 0, NULL );
519
520     /* wake up the audio output thread */
521     SetEvent( p_aout->sys->notif.event );
522
523     aout_PacketPlay( p_aout, p_buffer );
524     p_aout->play = aout_PacketPlay;
525 }
526
527 static int VolumeSet( audio_output_t *p_aout, float vol )
528 {
529     aout_sys_t *sys = p_aout->sys;
530     int ret = 0;
531
532     /* Convert UI volume to linear factor (cube) */
533     vol = vol * vol * vol;
534
535     /* millibels from linear amplification */
536     LONG mb = lroundf(2000.f * log10f(vol));
537
538     /* Clamp to allowed DirectSound range */
539     static_assert( DSBVOLUME_MIN < DSBVOLUME_MAX, "DSBVOLUME_* confused" );
540     if( mb > DSBVOLUME_MAX )
541     {
542         mb = DSBVOLUME_MAX;
543         ret = -1;
544     }
545     if( mb <= DSBVOLUME_MIN )
546         mb = DSBVOLUME_MIN;
547
548     sys->volume.mb = mb;
549     if (!sys->volume.mute)
550         InterlockedExchange(&sys->volume.volume, mb);
551
552     /* Convert back to UI volume */
553     vol = cbrtf(powf(10.f, ((float)mb) / 2000.f));
554     aout_VolumeReport( p_aout, vol );
555
556     if( var_InheritBool( p_aout, "volume-save" ) )
557         config_PutInt( p_aout, "directx-volume", mb );
558     return ret;
559 }
560
561 static int MuteSet( audio_output_t *p_aout, bool mute )
562 {
563     aout_sys_t *sys = p_aout->sys;
564
565     sys->volume.mute = mute;
566     InterlockedExchange(&sys->volume.volume,
567                         mute ? DSBVOLUME_MIN : sys->volume.mb);
568
569     aout_MuteReport( p_aout, mute );
570     return 0;
571 }
572
573 /*****************************************************************************
574  * CloseAudio: close the audio device
575  *****************************************************************************/
576 static void Stop( audio_output_t *p_aout )
577 {
578     aout_sys_t *p_sys = p_aout->sys;
579
580     msg_Dbg( p_aout, "closing audio device" );
581
582     /* kill the position notification thread, if any */
583     if( p_sys->notif.event != NULL )
584     {
585         vlc_atomic_set(&p_aout->sys->notif.abort, 1);
586         /* wake up the audio thread if needed */
587         if( p_aout->play == Play )
588             SetEvent( p_sys->notif.event );
589
590         vlc_join( p_sys->notif.thread, NULL );
591         CloseHandle( p_sys->notif.event );
592         aout_PacketDestroy( p_aout );
593     }
594
595     /* release the secondary buffer */
596     DestroyDSBuffer( p_aout );
597
598     /* finally release the DirectSound object */
599     if( p_sys->p_dsobject ) IDirectSound_Release( p_sys->p_dsobject );
600 }
601
602 /*****************************************************************************
603  * InitDirectSound: handle all the gory details of DirectSound initialisation
604  *****************************************************************************/
605 static int InitDirectSound( audio_output_t *p_aout )
606 {
607     aout_sys_t *sys = p_aout->sys;
608     GUID guid, *p_guid = NULL;
609     HRESULT (WINAPI *OurDirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
610
611     OurDirectSoundCreate = (void *)
612         GetProcAddress( p_aout->sys->hdsound_dll,
613                         "DirectSoundCreate" );
614     if( OurDirectSoundCreate == NULL )
615     {
616         msg_Warn( p_aout, "GetProcAddress FAILED" );
617         goto error;
618     }
619
620     char *dev = var_InheritString( p_aout, "directx-audio-device" );
621     if( dev != NULL )
622     {
623         LPOLESTR lpsz = ToWide( dev );
624
625         if( SUCCEEDED( IIDFromString( lpsz, &guid ) ) )
626             p_guid = &guid;
627         else
628             msg_Err( p_aout, "bad device GUID: %ls", lpsz );
629         free( lpsz );
630         free( dev );
631     }
632
633     /* Create the direct sound object */
634     if FAILED( OurDirectSoundCreate( p_guid, &sys->p_dsobject, NULL ) )
635     {
636         msg_Warn( p_aout, "cannot create a direct sound device" );
637         goto error;
638     }
639
640     /* Set DirectSound Cooperative level, ie what control we want over Windows
641      * sound device. In our case, DSSCL_EXCLUSIVE means that we can modify the
642      * settings of the primary buffer, but also that only the sound of our
643      * application will be hearable when it will have the focus.
644      * !!! (this is not really working as intended yet because to set the
645      * cooperative level you need the window handle of your application, and
646      * I don't know of any easy way to get it. Especially since we might play
647      * sound without any video, and so what window handle should we use ???
648      * The hack for now is to use the Desktop window handle - it seems to be
649      * working */
650     if( IDirectSound_SetCooperativeLevel( p_aout->sys->p_dsobject,
651                                           GetDesktopWindow(),
652                                           DSSCL_EXCLUSIVE) )
653     {
654         msg_Warn( p_aout, "cannot set direct sound cooperative level" );
655     }
656     return VLC_SUCCESS;
657
658  error:
659     sys->p_dsobject = NULL;
660     return VLC_EGENERIC;
661
662 }
663
664 /*****************************************************************************
665  * CreateDSBuffer: Creates a direct sound buffer of the required format.
666  *****************************************************************************
667  * This function creates the buffer we'll use to play audio.
668  * In DirectSound there are two kinds of buffers:
669  * - the primary buffer: which is the actual buffer that the soundcard plays
670  * - the secondary buffer(s): these buffers are the one actually used by
671  *    applications and DirectSound takes care of mixing them into the primary.
672  *
673  * Once you create a secondary buffer, you cannot change its format anymore so
674  * you have to release the current one and create another.
675  *****************************************************************************/
676 static int CreateDSBuffer( audio_output_t *p_aout, int i_format,
677                            int i_channels, int i_nb_channels, int i_rate,
678                            int i_bytes_per_frame, bool b_probe )
679 {
680     WAVEFORMATEXTENSIBLE waveformat;
681     DSBUFFERDESC         dsbdesc;
682
683     /* First set the sound buffer format */
684     waveformat.dwChannelMask = 0;
685     for( unsigned i = 0; pi_vlc_chan_order_wg4[i]; i++ )
686         if( i_channels & pi_vlc_chan_order_wg4[i] )
687             waveformat.dwChannelMask |= pi_channels_in[i];
688
689     switch( i_format )
690     {
691     case VLC_CODEC_SPDIFL:
692         i_nb_channels = 2;
693         /* To prevent channel re-ordering */
694         waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
695         waveformat.Format.wBitsPerSample = 16;
696         waveformat.Samples.wValidBitsPerSample =
697             waveformat.Format.wBitsPerSample;
698         waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
699         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
700         break;
701
702     case VLC_CODEC_FL32:
703         waveformat.Format.wBitsPerSample = sizeof(float) * 8;
704         waveformat.Samples.wValidBitsPerSample =
705             waveformat.Format.wBitsPerSample;
706         waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
707         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
708         break;
709
710     case VLC_CODEC_S16N:
711         waveformat.Format.wBitsPerSample = 16;
712         waveformat.Samples.wValidBitsPerSample =
713             waveformat.Format.wBitsPerSample;
714         waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
715         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_PCM;
716         break;
717     }
718
719     waveformat.Format.nChannels = i_nb_channels;
720     waveformat.Format.nSamplesPerSec = i_rate;
721     waveformat.Format.nBlockAlign =
722         waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
723     waveformat.Format.nAvgBytesPerSec =
724         waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;
725
726     p_aout->sys->format = i_format;
727
728     /* Then fill in the direct sound descriptor */
729     memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
730     dsbdesc.dwSize = sizeof(DSBUFFERDESC);
731     dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2/* Better position accuracy */
732                     | DSBCAPS_GLOBALFOCUS       /* Allows background playing */
733                     | DSBCAPS_CTRLVOLUME;       /* Allows volume control */
734
735     /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
736     if( i_nb_channels <= 2 )
737     {
738         waveformat.Format.cbSize = 0;
739     }
740     else
741     {
742         waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
743         waveformat.Format.cbSize =
744             sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
745
746         /* Needed for 5.1 on emu101k */
747         dsbdesc.dwFlags |= DSBCAPS_LOCHARDWARE;
748     }
749
750     dsbdesc.dwBufferBytes = FRAMES_NUM * i_bytes_per_frame;   /* buffer size */
751     dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&waveformat;
752
753     if FAILED( IDirectSound_CreateSoundBuffer(
754                    p_aout->sys->p_dsobject, &dsbdesc,
755                    &p_aout->sys->p_dsbuffer, NULL) )
756     {
757         if( dsbdesc.dwFlags & DSBCAPS_LOCHARDWARE )
758         {
759             /* Try without DSBCAPS_LOCHARDWARE */
760             dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE;
761             if FAILED( IDirectSound_CreateSoundBuffer(
762                    p_aout->sys->p_dsobject, &dsbdesc,
763                    &p_aout->sys->p_dsbuffer, NULL) )
764             {
765                 return VLC_EGENERIC;
766             }
767             if( !b_probe )
768                 msg_Dbg( p_aout, "couldn't use hardware sound buffer" );
769         }
770         else
771         {
772             return VLC_EGENERIC;
773         }
774     }
775
776     /* Stop here if we were just probing */
777     if( b_probe )
778     {
779         IDirectSoundBuffer_Release( p_aout->sys->p_dsbuffer );
780         p_aout->sys->p_dsbuffer = NULL;
781         return VLC_SUCCESS;
782     }
783
784     p_aout->sys->i_frame_size = i_bytes_per_frame;
785     p_aout->sys->i_channel_mask = waveformat.dwChannelMask;
786     p_aout->sys->chans_to_reorder =
787         aout_CheckChannelReorder( pi_channels_in, pi_channels_out,
788                                   waveformat.dwChannelMask,
789                                   p_aout->sys->chan_table );
790     if( p_aout->sys->chans_to_reorder )
791     {
792         msg_Dbg( p_aout, "channel reordering needed" );
793     }
794
795     return VLC_SUCCESS;
796 }
797
798 /*****************************************************************************
799  * CreateDSBufferPCM: creates a PCM direct sound buffer.
800  *****************************************************************************
801  * We first try to create a WAVE_FORMAT_IEEE_FLOAT buffer if supported by
802  * the hardware, otherwise we create a WAVE_FORMAT_PCM buffer.
803  ****************************************************************************/
804 static int CreateDSBufferPCM( audio_output_t *p_aout, vlc_fourcc_t *i_format,
805                               int i_channels, int i_rate, bool b_probe )
806 {
807     unsigned i_nb_channels = popcount( i_channels );
808
809     /* Float32 audio samples are not supported for 5.1 output on the emu101k */
810     if( !var_GetBool( p_aout, "directx-audio-float32" ) ||
811         i_nb_channels > 2 ||
812         CreateDSBuffer( p_aout, VLC_CODEC_FL32,
813                         i_channels, i_nb_channels, i_rate,
814                         (i_rate / 20) * 4 * i_nb_channels, b_probe )
815         != VLC_SUCCESS )
816     {
817         if ( CreateDSBuffer( p_aout, VLC_CODEC_S16N,
818                              i_channels, i_nb_channels, i_rate,
819                              (i_rate / 20) * 2 * i_nb_channels, b_probe )
820              != VLC_SUCCESS )
821         {
822             return VLC_EGENERIC;
823         }
824         else
825         {
826             *i_format = VLC_CODEC_S16N;
827             return VLC_SUCCESS;
828         }
829     }
830     else
831     {
832         *i_format = VLC_CODEC_FL32;
833         return VLC_SUCCESS;
834     }
835 }
836
837 /*****************************************************************************
838  * DestroyDSBuffer
839  *****************************************************************************
840  * This function destroys the secondary buffer.
841  *****************************************************************************/
842 static void DestroyDSBuffer( audio_output_t *p_aout )
843 {
844     if( p_aout->sys->p_dsbuffer )
845     {
846         IDirectSoundBuffer_Release( p_aout->sys->p_dsbuffer );
847         p_aout->sys->p_dsbuffer = NULL;
848     }
849 }
850
851 /*****************************************************************************
852  * FillBuffer: Fill in one of the direct sound frame buffers.
853  *****************************************************************************
854  * Returns VLC_SUCCESS on success.
855  *****************************************************************************/
856 static int FillBuffer( audio_output_t *p_aout, int i_frame, block_t *p_buffer )
857 {
858     aout_sys_t *p_sys = p_aout->sys;
859     notification_thread_t *p_notif = &p_sys->notif;
860     void *p_write_position, *p_wrap_around;
861     unsigned long l_bytes1, l_bytes2;
862     HRESULT dsresult;
863
864     /* Before copying anything, we have to lock the buffer */
865     dsresult = IDirectSoundBuffer_Lock(
866                 p_sys->p_dsbuffer,                              /* DS buffer */
867                 i_frame * p_notif->i_frame_size,             /* Start offset */
868                 p_notif->i_frame_size,                    /* Number of bytes */
869                 &p_write_position,                  /* Address of lock start */
870                 &l_bytes1,       /* Count of bytes locked before wrap around */
871                 &p_wrap_around,           /* Buffer address (if wrap around) */
872                 &l_bytes2,               /* Count of bytes after wrap around */
873                 0 );                                                /* Flags */
874     if( dsresult == DSERR_BUFFERLOST )
875     {
876         IDirectSoundBuffer_Restore( p_sys->p_dsbuffer );
877         dsresult = IDirectSoundBuffer_Lock(
878                                p_sys->p_dsbuffer,
879                                i_frame * p_notif->i_frame_size,
880                                p_notif->i_frame_size,
881                                &p_write_position,
882                                &l_bytes1,
883                                &p_wrap_around,
884                                &l_bytes2,
885                                0 );
886     }
887     if( dsresult != DS_OK )
888     {
889         msg_Warn( p_aout, "cannot lock buffer" );
890         if( p_buffer ) block_Release( p_buffer );
891         return VLC_EGENERIC;
892     }
893
894     if( p_buffer == NULL )
895     {
896         memset( p_write_position, 0, l_bytes1 );
897     }
898     else
899     {
900         if( p_sys->chans_to_reorder )
901             /* Do the channel reordering here */
902             aout_ChannelReorder( p_buffer->p_buffer, p_buffer->i_buffer,
903                                  p_sys->chans_to_reorder, p_sys->chan_table,
904                                  p_sys->format );
905
906         memcpy( p_write_position, p_buffer->p_buffer, l_bytes1 );
907         block_Release( p_buffer );
908     }
909
910     /* Now the data has been copied, unlock the buffer */
911     IDirectSoundBuffer_Unlock( p_sys->p_dsbuffer, p_write_position, l_bytes1,
912                                p_wrap_around, l_bytes2 );
913
914     p_notif->i_write_slot = (i_frame + 1) % FRAMES_NUM;
915     return VLC_SUCCESS;
916 }
917
918 /*****************************************************************************
919  * DirectSoundThread: this thread will capture play notification events.
920  *****************************************************************************
921  * We use this thread to emulate a callback mechanism. The thread probes for
922  * event notification and fills up the DS secondary buffer when needed.
923  *****************************************************************************/
924 static void* DirectSoundThread( void *data )
925 {
926     audio_output_t *p_aout = (audio_output_t *)data;
927     notification_thread_t *p_notif = &p_aout->sys->notif;
928     mtime_t last_time;
929
930     msg_Dbg( p_aout, "DirectSoundThread ready" );
931
932     /* Wait here until Play() is called */
933     WaitForSingleObject( p_notif->event, INFINITE );
934
935     if( !vlc_atomic_get( &p_notif->abort) )
936     {
937         HRESULT dsresult;
938         mwait( p_notif->start_date - AOUT_MAX_PTS_ADVANCE / 2 );
939
940         /* start playing the buffer */
941         dsresult = IDirectSoundBuffer_Play( p_aout->sys->p_dsbuffer,
942                                         0,                         /* Unused */
943                                         0,                         /* Unused */
944                                         DSBPLAY_LOOPING );          /* Flags */
945         if( dsresult == DSERR_BUFFERLOST )
946         {
947             IDirectSoundBuffer_Restore( p_aout->sys->p_dsbuffer );
948             dsresult = IDirectSoundBuffer_Play(
949                                             p_aout->sys->p_dsbuffer,
950                                             0,                     /* Unused */
951                                             0,                     /* Unused */
952                                             DSBPLAY_LOOPING );      /* Flags */
953         }
954         if( dsresult != DS_OK )
955         {
956             msg_Err( p_aout, "cannot start playing buffer" );
957         }
958     }
959     last_time = mdate();
960
961     while( !vlc_atomic_get( &p_notif->abort ) )
962     {
963         DWORD l_read;
964         int l_queued = 0, l_free_slots;
965         unsigned i_frame_siz = p_aout->sys->packet.samples;
966         mtime_t mtime = mdate();
967         int i;
968
969         /* Update volume if required */
970         LONG volume = InterlockedExchange( &p_aout->sys->volume.volume, -1 );
971         if( unlikely(volume != -1) )
972             IDirectSoundBuffer_SetVolume( p_aout->sys->p_dsbuffer, volume );
973
974         /*
975          * Fill in as much audio data as we can in our circular buffer
976          */
977
978         /* Find out current play position */
979         if FAILED( IDirectSoundBuffer_GetCurrentPosition(
980                    p_aout->sys->p_dsbuffer, &l_read, NULL ) )
981         {
982             msg_Err( p_aout, "GetCurrentPosition() failed!" );
983             l_read = 0;
984         }
985
986         /* Detect underruns */
987         if( l_queued && mtime - last_time >
988             INT64_C(1000000) * l_queued / p_aout->sys->packet.format.i_rate )
989         {
990             msg_Dbg( p_aout, "detected underrun!" );
991         }
992         last_time = mtime;
993
994         /* Try to fill in as many frame buffers as possible */
995         l_read /= (p_aout->sys->packet.format.i_bytes_per_frame /
996             p_aout->sys->packet.format.i_frame_length);
997         l_queued = p_notif->i_write_slot * i_frame_siz - l_read;
998         if( l_queued < 0 ) l_queued += (i_frame_siz * FRAMES_NUM);
999         l_free_slots = (FRAMES_NUM * i_frame_siz - l_queued) / i_frame_siz;
1000
1001         for( i = 0; i < l_free_slots; i++ )
1002         {
1003             block_t *p_buffer = aout_PacketNext( p_aout,
1004                 mtime + INT64_C(1000000) * (i * i_frame_siz + l_queued) /
1005                 p_aout->sys->packet.format.i_rate );
1006
1007             /* If there is no audio data available and we have some buffered
1008              * already, then just wait for the next time */
1009             if( !p_buffer && (i || l_queued / i_frame_siz) ) break;
1010
1011             if( FillBuffer( p_aout, p_notif->i_write_slot % FRAMES_NUM,
1012                             p_buffer ) != VLC_SUCCESS ) break;
1013         }
1014
1015         /* Sleep a reasonable amount of time */
1016         l_queued += (i * i_frame_siz);
1017         msleep( INT64_C(1000000) * l_queued / p_aout->sys->packet.format.i_rate / 2 );
1018     }
1019
1020     /* make sure the buffer isn't playing */
1021     IDirectSoundBuffer_Stop( p_aout->sys->p_dsbuffer );
1022
1023     msg_Dbg( p_aout, "DirectSoundThread exiting" );
1024     return NULL;
1025 }
1026
1027 typedef struct
1028 {
1029     unsigned count;
1030     char **ids;
1031     char **names;
1032 } ds_list_t;
1033
1034 static int CALLBACK DeviceEnumCallback( LPGUID guid, LPCWSTR desc,
1035                                         LPCWSTR mod, LPVOID data )
1036 {
1037     ds_list_t *list = data;
1038     OLECHAR buf[48];
1039
1040     StringFromGUID2( guid, buf, 48 );
1041
1042     list->count++;
1043     list->ids = xrealloc( list->ids, list->count * sizeof(char *) );
1044     list->names = xrealloc( list->names, list->count * sizeof(char *) );
1045     list->ids[list->count - 1] = FromWide( buf );
1046     list->names[list->count - 1] = FromWide( desc );
1047     if( list->ids == NULL || list->names == NULL )
1048         abort();
1049
1050     (void) mod;
1051     return true;
1052 }
1053
1054 /*****************************************************************************
1055  * ReloadDirectXDevices: store the list of devices in preferences
1056  *****************************************************************************/
1057 static int ReloadDirectXDevices( vlc_object_t *p_this, char const *psz_name,
1058                                  char ***values, char ***descs )
1059 {
1060     ds_list_t list = { 0, NULL, NULL };
1061
1062     (void) psz_name;
1063
1064     HANDLE hdsound_dll = LoadLibrary(_T("DSOUND.DLL"));
1065     if( hdsound_dll == NULL )
1066     {
1067         msg_Warn( p_this, "cannot open DSOUND.DLL" );
1068         goto out;
1069     }
1070
1071     /* Get DirectSoundEnumerate */
1072     HRESULT (WINAPI *OurDirectSoundEnumerate)(LPDSENUMCALLBACKW, LPVOID) =
1073             (void *)GetProcAddress( hdsound_dll, _T("DirectSoundEnumerateW") );
1074     if( OurDirectSoundEnumerate != NULL )
1075     {
1076         OurDirectSoundEnumerate( DeviceEnumCallback, &list );
1077         msg_Dbg( p_this, "found %u devices", list.count );
1078     }
1079     FreeLibrary(hdsound_dll);
1080
1081 out:
1082     *values = list.ids;
1083     *descs = list.names;
1084     return list.count;
1085 }
1086
1087 static int Open(vlc_object_t *obj)
1088 {
1089     audio_output_t *aout = (audio_output_t *)obj;
1090     aout_sys_t *sys = calloc(1, sizeof (*sys));
1091     if (unlikely(sys == NULL))
1092         return VLC_ENOMEM;
1093
1094     sys->hdsound_dll = LoadLibrary(_T("DSOUND.DLL"));
1095     if (sys->hdsound_dll == NULL)
1096     {
1097         msg_Warn(aout, "cannot open DSOUND.DLL");
1098         free(sys);
1099         return VLC_EGENERIC;
1100     }
1101
1102     aout->sys = sys;
1103     aout->start = Start;
1104     aout->stop = Stop;
1105     aout->volume_set = VolumeSet;
1106     aout->mute_set = MuteSet;
1107
1108     /* Volume */
1109     LONG mb = var_InheritInteger(aout, "directx-volume");
1110     sys->volume.mb = mb;
1111     aout_VolumeReport(aout, cbrtf(powf(10.f, ((float)mb) / 2000.f)));
1112     MuteSet(aout, var_InheritBool(aout, "mute"));
1113
1114     return VLC_SUCCESS;
1115 }
1116
1117 static void Close(vlc_object_t *obj)
1118 {
1119     audio_output_t *aout = (audio_output_t *)obj;
1120     aout_sys_t *sys = aout->sys;
1121
1122     FreeLibrary(sys->hdsound_dll); /* free DSOUND.DLL */
1123     free(sys);
1124 }