]> git.sesse.net Git - vlc/blob - modules/audio_output/waveout.c
Use vlc_object_kill(). Needs triple checking.
[vlc] / modules / audio_output / waveout.c
1 /*****************************************************************************
2  * waveout.c : Windows waveOut plugin for vlc
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 #include <stdlib.h>                            /* calloc(), malloc(), free() */
29
30 #include <vlc/vlc.h>
31 #include <vlc_aout.h>
32
33 #include <windows.h>
34 #include <mmsystem.h>
35
36 #define FRAME_SIZE 4096              /* The size is in samples, not in bytes */
37 #define FRAMES_NUM 8
38
39 /*****************************************************************************
40  * Useful macros
41  *****************************************************************************/
42 #ifdef UNDER_CE
43 #   define DWORD_PTR DWORD
44 #   ifdef waveOutGetDevCaps
45 #       undef waveOutGetDevCaps
46         MMRESULT WINAPI waveOutGetDevCaps(UINT, LPWAVEOUTCAPS, UINT);
47 #   endif
48 #endif
49
50 #ifndef WAVE_FORMAT_IEEE_FLOAT
51 #   define WAVE_FORMAT_IEEE_FLOAT 0x0003
52 #endif
53
54 #ifndef WAVE_FORMAT_DOLBY_AC3_SPDIF
55 #   define WAVE_FORMAT_DOLBY_AC3_SPDIF 0x0092
56 #endif
57
58 #ifndef WAVE_FORMAT_EXTENSIBLE
59 #define  WAVE_FORMAT_EXTENSIBLE   0xFFFE
60 #endif
61
62 #ifndef SPEAKER_FRONT_LEFT
63 #   define SPEAKER_FRONT_LEFT             0x1
64 #   define SPEAKER_FRONT_RIGHT            0x2
65 #   define SPEAKER_FRONT_CENTER           0x4
66 #   define SPEAKER_LOW_FREQUENCY          0x8
67 #   define SPEAKER_BACK_LEFT              0x10
68 #   define SPEAKER_BACK_RIGHT             0x20
69 #   define SPEAKER_FRONT_LEFT_OF_CENTER   0x40
70 #   define SPEAKER_FRONT_RIGHT_OF_CENTER  0x80
71 #   define SPEAKER_BACK_CENTER            0x100
72 #   define SPEAKER_SIDE_LEFT              0x200
73 #   define SPEAKER_SIDE_RIGHT             0x400
74 #   define SPEAKER_TOP_CENTER             0x800
75 #   define SPEAKER_TOP_FRONT_LEFT         0x1000
76 #   define SPEAKER_TOP_FRONT_CENTER       0x2000
77 #   define SPEAKER_TOP_FRONT_RIGHT        0x4000
78 #   define SPEAKER_TOP_BACK_LEFT          0x8000
79 #   define SPEAKER_TOP_BACK_CENTER        0x10000
80 #   define SPEAKER_TOP_BACK_RIGHT         0x20000
81 #   define SPEAKER_RESERVED               0x80000000
82 #endif
83
84 #ifndef _WAVEFORMATEXTENSIBLE_
85 typedef struct {
86     WAVEFORMATEX    Format;
87     union {
88         WORD wValidBitsPerSample;       /* bits of precision  */
89         WORD wSamplesPerBlock;          /* valid if wBitsPerSample==0 */
90         WORD wReserved;                 /* If neither applies, set to zero. */
91     } Samples;
92     DWORD           dwChannelMask;      /* which channels are */
93                                         /* present in stream  */
94     GUID            SubFormat;
95 } WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;
96 #endif
97
98 static const GUID __KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = {WAVE_FORMAT_IEEE_FLOAT, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
99 static const GUID __KSDATAFORMAT_SUBTYPE_PCM = {WAVE_FORMAT_PCM, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
100 static const GUID __KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF = {WAVE_FORMAT_DOLBY_AC3_SPDIF, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
101
102 /*****************************************************************************
103  * Local prototypes
104  *****************************************************************************/
105 static int  Open         ( vlc_object_t * );
106 static void Close        ( vlc_object_t * );
107 static void Play         ( aout_instance_t * );
108
109 /*****************************************************************************
110  * notification_thread_t: waveOut event thread
111  *****************************************************************************/
112 typedef struct notification_thread_t
113 {
114     VLC_COMMON_MEMBERS
115     aout_instance_t *p_aout;
116
117 } notification_thread_t;
118
119 /* local functions */
120 static void Probe        ( aout_instance_t * );
121 static int OpenWaveOut   ( aout_instance_t *, int, int, int, int, vlc_bool_t );
122 static int OpenWaveOutPCM( aout_instance_t *, int*, int, int, int, vlc_bool_t );
123 static int PlayWaveOut   ( aout_instance_t *, HWAVEOUT, WAVEHDR *,
124                            aout_buffer_t * );
125
126 static void CALLBACK WaveOutCallback ( HWAVEOUT, UINT, DWORD, DWORD, DWORD );
127 static void WaveOutThread( notification_thread_t * );
128
129 static int VolumeInfos( aout_instance_t *, audio_volume_t * );
130 static int VolumeGet( aout_instance_t *, audio_volume_t * );
131 static int VolumeSet( aout_instance_t *, audio_volume_t );
132
133 /*****************************************************************************
134  * Module descriptor
135  *****************************************************************************/
136 #define FLOAT_TEXT N_("Use float32 output")
137 #define FLOAT_LONGTEXT N_( \
138     "The option allows you to enable or disable the high-quality float32 " \
139     "audio output mode (which is not well supported by some soundcards)." )
140
141 vlc_module_begin();
142     set_shortname( "WaveOut" );
143     set_description( _("Win32 waveOut extension output") );
144     set_capability( "audio output", 50 );
145     set_category( CAT_AUDIO );
146     set_subcategory( SUBCAT_AUDIO_AOUT );
147     add_bool( "waveout-float32", 1, 0, FLOAT_TEXT, FLOAT_LONGTEXT, VLC_TRUE );
148     set_callbacks( Open, Close );
149 vlc_module_end();
150
151 /*****************************************************************************
152  * aout_sys_t: waveOut audio output method descriptor
153  *****************************************************************************
154  * This structure is part of the audio output thread descriptor.
155  * It describes the waveOut specific properties of an audio device.
156  *****************************************************************************/
157 struct aout_sys_t
158 {
159     HWAVEOUT h_waveout;                        /* handle to waveout instance */
160
161     WAVEFORMATEXTENSIBLE waveformat;                         /* audio format */
162
163     WAVEHDR waveheader[FRAMES_NUM];
164
165     notification_thread_t *p_notif;                      /* WaveOutThread id */
166     HANDLE event;
167
168     int i_buffer_size;
169
170     byte_t *p_silence_buffer;               /* buffer we use to play silence */
171
172     vlc_bool_t b_chan_reorder;              /* do we need channel reordering */
173     int pi_chan_table[AOUT_CHAN_MAX];
174 };
175
176 static const uint32_t pi_channels_src[] =
177     { AOUT_CHAN_LEFT, AOUT_CHAN_RIGHT,
178       AOUT_CHAN_MIDDLELEFT, AOUT_CHAN_MIDDLERIGHT,
179       AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT,
180       AOUT_CHAN_CENTER, AOUT_CHAN_LFE, 0 };
181 static const uint32_t pi_channels_in[] =
182     { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT,
183       SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT,
184       SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT,
185       SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY, 0 };
186 static const uint32_t pi_channels_out[] =
187     { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT,
188       SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY,
189       SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT,
190       SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT, 0 };
191
192 /*****************************************************************************
193  * Open: open the audio device
194  *****************************************************************************
195  * This function opens and setups Win32 waveOut
196  *****************************************************************************/
197 static int Open( vlc_object_t *p_this )
198 {
199     aout_instance_t *p_aout = (aout_instance_t *)p_this;
200     vlc_value_t val;
201     int i;
202
203     /* Allocate structure */
204     p_aout->output.p_sys = malloc( sizeof( aout_sys_t ) );
205
206     if( p_aout->output.p_sys == NULL )
207     {
208         msg_Err( p_aout, "out of memory" );
209         return VLC_EGENERIC;
210     }
211
212     p_aout->output.pf_play = Play;
213     p_aout->b_die = VLC_FALSE;
214
215     if( var_Type( p_aout, "audio-device" ) == 0 )
216     {
217         Probe( p_aout );
218     }
219
220     if( var_Get( p_aout, "audio-device", &val ) < 0 )
221     {
222         /* Probe() has failed. */
223         free( p_aout->output.p_sys );
224         return VLC_EGENERIC;
225     }
226
227     var_Create( p_aout, "waveout-float32", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
228
229     /* Open the device */
230     if( val.i_int == AOUT_VAR_SPDIF )
231     {
232         p_aout->output.output.i_format = VLC_FOURCC('s','p','d','i');
233
234         if( OpenWaveOut( p_aout, VLC_FOURCC('s','p','d','i'),
235                          p_aout->output.output.i_physical_channels,
236                          aout_FormatNbChannels( &p_aout->output.output ),
237                          p_aout->output.output.i_rate, VLC_FALSE )
238             != VLC_SUCCESS )
239         {
240             msg_Err( p_aout, "cannot open waveout audio device" );
241             free( p_aout->output.p_sys );
242             return VLC_EGENERIC;
243         }
244
245         /* Calculate the frame size in bytes */
246         p_aout->output.i_nb_samples = A52_FRAME_NB;
247         p_aout->output.output.i_bytes_per_frame = AOUT_SPDIF_SIZE;
248         p_aout->output.output.i_frame_length = A52_FRAME_NB;
249         p_aout->output.p_sys->i_buffer_size =
250             p_aout->output.output.i_bytes_per_frame;
251
252         aout_VolumeNoneInit( p_aout );
253     }
254     else
255     {
256         WAVEOUTCAPS wocaps;
257
258         if( val.i_int == AOUT_VAR_5_1 )
259         {
260             p_aout->output.output.i_physical_channels
261                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
262                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
263                    | AOUT_CHAN_LFE;
264         }
265         else if( val.i_int == AOUT_VAR_2F2R )
266         {
267             p_aout->output.output.i_physical_channels
268                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
269                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
270         }
271         else if( val.i_int == AOUT_VAR_MONO )
272         {
273             p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
274         }
275         else
276         {
277             p_aout->output.output.i_physical_channels
278                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
279         }
280
281         if( OpenWaveOutPCM( p_aout, &p_aout->output.output.i_format,
282                             p_aout->output.output.i_physical_channels,
283                             aout_FormatNbChannels( &p_aout->output.output ),
284                             p_aout->output.output.i_rate, VLC_FALSE )
285             != VLC_SUCCESS )
286         {
287             msg_Err( p_aout, "cannot open waveout audio device" );
288             free( p_aout->output.p_sys );
289             return VLC_EGENERIC;
290         }
291
292         /* Calculate the frame size in bytes */
293         p_aout->output.i_nb_samples = FRAME_SIZE;
294         aout_FormatPrepare( &p_aout->output.output );
295         p_aout->output.p_sys->i_buffer_size = FRAME_SIZE *
296             p_aout->output.output.i_bytes_per_frame;
297
298         aout_VolumeSoftInit( p_aout );
299
300         /* Check for hardware volume support */
301         if( waveOutGetDevCaps( (UINT_PTR)p_aout->output.p_sys->h_waveout,
302                                &wocaps, sizeof(wocaps) ) == MMSYSERR_NOERROR &&
303             wocaps.dwSupport & WAVECAPS_VOLUME )
304         {
305             DWORD i_dummy;
306             if( waveOutGetVolume( p_aout->output.p_sys->h_waveout, &i_dummy )
307                 == MMSYSERR_NOERROR )
308             {
309                 p_aout->output.pf_volume_infos = VolumeInfos;
310                 p_aout->output.pf_volume_get = VolumeGet;
311                 p_aout->output.pf_volume_set = VolumeSet;
312             }
313         }
314     }
315
316
317     waveOutReset( p_aout->output.p_sys->h_waveout );
318
319     /* Allocate silence buffer */
320     p_aout->output.p_sys->p_silence_buffer =
321         malloc( p_aout->output.p_sys->i_buffer_size );
322     if( p_aout->output.p_sys->p_silence_buffer == NULL )
323     {
324         free( p_aout->output.p_sys );
325         msg_Err( p_aout, "out of memory" );
326         return 1;
327     }
328
329     /* Zero the buffer. WinCE doesn't have calloc(). */
330     memset( p_aout->output.p_sys->p_silence_buffer, 0,
331             p_aout->output.p_sys->i_buffer_size );
332
333     /* Now we need to setup our waveOut play notification structure */
334     p_aout->output.p_sys->p_notif =
335         vlc_object_create( p_aout, sizeof(notification_thread_t) );
336     p_aout->output.p_sys->p_notif->p_aout = p_aout;
337     p_aout->output.p_sys->event = CreateEvent( NULL, FALSE, FALSE, NULL );
338
339     /* Then launch the notification thread */
340     if( vlc_thread_create( p_aout->output.p_sys->p_notif,
341                            "waveOut Notification Thread", WaveOutThread,
342                            VLC_THREAD_PRIORITY_HIGHEST, VLC_FALSE ) )
343     {
344         msg_Err( p_aout, "cannot create WaveOutThread" );
345     }
346
347     /* We need to kick off the playback in order to have the callback properly
348      * working */
349     for( i = 0; i < FRAMES_NUM; i++ )
350     {
351         p_aout->output.p_sys->waveheader[i].dwFlags = WHDR_DONE;
352         p_aout->output.p_sys->waveheader[i].dwUser = 0;
353     }
354     PlayWaveOut( p_aout, p_aout->output.p_sys->h_waveout,
355                  &p_aout->output.p_sys->waveheader[0], NULL );
356
357     return 0;
358 }
359
360 /*****************************************************************************
361  * Probe: probe the audio device for available formats and channels
362  *****************************************************************************/
363 static void Probe( aout_instance_t * p_aout )
364 {
365     vlc_value_t val, text;
366     int i_format;
367     unsigned int i_physical_channels;
368
369     var_Create( p_aout, "audio-device", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
370     text.psz_string = _("Audio Device");
371     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
372
373     /* Test for 5.1 support */
374     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
375                           AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
376                           AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE;
377     if( p_aout->output.output.i_physical_channels == i_physical_channels )
378     {
379         if( OpenWaveOutPCM( p_aout, &i_format,
380                             i_physical_channels, 6,
381                             p_aout->output.output.i_rate, VLC_TRUE )
382             == VLC_SUCCESS )
383         {
384             val.i_int = AOUT_VAR_5_1;
385             text.psz_string = N_("5.1");
386             var_Change( p_aout, "audio-device",
387                         VLC_VAR_ADDCHOICE, &val, &text );
388             msg_Dbg( p_aout, "device supports 5.1 channels" );
389         }
390     }
391
392     /* Test for 2 Front 2 Rear support */
393     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
394                           AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
395     if( ( p_aout->output.output.i_physical_channels & i_physical_channels )
396         == i_physical_channels )
397     {
398         if( OpenWaveOutPCM( p_aout, &i_format,
399                             i_physical_channels, 4,
400                             p_aout->output.output.i_rate, VLC_TRUE )
401             == VLC_SUCCESS )
402         {
403             val.i_int = AOUT_VAR_2F2R;
404             text.psz_string = N_("2 Front 2 Rear");
405             var_Change( p_aout, "audio-device",
406                         VLC_VAR_ADDCHOICE, &val, &text );
407             msg_Dbg( p_aout, "device supports 4 channels" );
408         }
409     }
410
411     /* Test for stereo support */
412     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
413     if( OpenWaveOutPCM( p_aout, &i_format,
414                         i_physical_channels, 2,
415                         p_aout->output.output.i_rate, VLC_TRUE )
416         == VLC_SUCCESS )
417     {
418         val.i_int = AOUT_VAR_STEREO;
419         text.psz_string = N_("Stereo");
420         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
421         msg_Dbg( p_aout, "device supports 2 channels" );
422     }
423
424     /* Test for mono support */
425     i_physical_channels = AOUT_CHAN_CENTER;
426     if( OpenWaveOutPCM( p_aout, &i_format,
427                         i_physical_channels, 1,
428                         p_aout->output.output.i_rate, VLC_TRUE )
429         == VLC_SUCCESS )
430     {
431         val.i_int = AOUT_VAR_MONO;
432         text.psz_string = N_("Mono");
433         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
434         msg_Dbg( p_aout, "device supports 1 channel" );
435     }
436
437     /* Test for SPDIF support */
438     if ( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
439     {
440         if( OpenWaveOut( p_aout, VLC_FOURCC('s','p','d','i'),
441                          p_aout->output.output.i_physical_channels,
442                          aout_FormatNbChannels( &p_aout->output.output ),
443                          p_aout->output.output.i_rate, VLC_TRUE )
444             == VLC_SUCCESS )
445         {
446             msg_Dbg( p_aout, "device supports A/52 over S/PDIF" );
447             val.i_int = AOUT_VAR_SPDIF;
448             text.psz_string = N_("A/52 over S/PDIF");
449             var_Change( p_aout, "audio-device",
450                         VLC_VAR_ADDCHOICE, &val, &text );
451             if( config_GetInt( p_aout, "spdif" ) )
452                 var_Set( p_aout, "audio-device", val );
453         }
454     }
455
456     var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
457     if( val.i_int <= 0 )
458     {
459         /* Probe() has failed. */
460         var_Destroy( p_aout, "audio-device" );
461         return;
462     }
463
464     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
465
466     val.b_bool = VLC_TRUE;
467     var_Set( p_aout, "intf-change", val );
468 }
469
470 /*****************************************************************************
471  * Play: play a sound buffer
472  *****************************************************************************
473  * This doesn't actually play the buffer. This just stores the buffer so it
474  * can be played by the callback thread.
475  *****************************************************************************/
476 static void Play( aout_instance_t *_p_aout )
477 {
478 }
479
480 /*****************************************************************************
481  * Close: close the audio device
482  *****************************************************************************/
483 static void Close( vlc_object_t *p_this )
484 {
485     aout_instance_t *p_aout = (aout_instance_t *)p_this;
486     aout_sys_t *p_sys = p_aout->output.p_sys;
487
488     /* Before calling waveOutClose we must reset the device */
489     vlc_object_kill( p_aout );
490
491     waveOutReset( p_sys->h_waveout );
492
493     /* wake up the audio thread */
494     SetEvent( p_sys->event );
495     vlc_thread_join( p_sys->p_notif );
496     vlc_object_destroy( p_sys->p_notif );
497     CloseHandle( p_sys->event );
498
499     /* Close the device */
500     if( waveOutClose( p_sys->h_waveout ) != MMSYSERR_NOERROR )
501     {
502         msg_Err( p_aout, "waveOutClose failed" );
503     }
504
505     free( p_sys->p_silence_buffer );
506     free( p_sys );
507 }
508
509 /*****************************************************************************
510  * OpenWaveOut: open the waveout sound device
511  ****************************************************************************/
512 static int OpenWaveOut( aout_instance_t *p_aout, int i_format,
513                         int i_channels, int i_nb_channels, int i_rate,
514                         vlc_bool_t b_probe )
515 {
516     MMRESULT result;
517     unsigned int i;
518
519     /* Set sound format */
520
521 #define waveformat p_aout->output.p_sys->waveformat
522
523     waveformat.dwChannelMask = 0;
524     for( i = 0; i < sizeof(pi_channels_src)/sizeof(uint32_t); i++ )
525     {
526         if( i_channels & pi_channels_src[i] )
527             waveformat.dwChannelMask |= pi_channels_in[i];
528     }
529
530     switch( i_format )
531     {
532     case VLC_FOURCC('s','p','d','i'):
533         i_nb_channels = 2;
534         /* To prevent channel re-ordering */
535         waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
536         waveformat.Format.wBitsPerSample = 16;
537         waveformat.Samples.wValidBitsPerSample =
538             waveformat.Format.wBitsPerSample;
539         waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
540         waveformat.SubFormat = __KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
541         break;
542
543     case VLC_FOURCC('f','l','3','2'):
544         waveformat.Format.wBitsPerSample = sizeof(float) * 8;
545         waveformat.Samples.wValidBitsPerSample =
546             waveformat.Format.wBitsPerSample;
547         waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
548         waveformat.SubFormat = __KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
549         break;
550
551     case VLC_FOURCC('s','1','6','l'):
552         waveformat.Format.wBitsPerSample = 16;
553         waveformat.Samples.wValidBitsPerSample =
554             waveformat.Format.wBitsPerSample;
555         waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
556         waveformat.SubFormat = __KSDATAFORMAT_SUBTYPE_PCM;
557         break;
558     }
559
560     waveformat.Format.nChannels = i_nb_channels;
561     waveformat.Format.nSamplesPerSec = i_rate;
562     waveformat.Format.nBlockAlign =
563         waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
564     waveformat.Format.nAvgBytesPerSec =
565         waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;
566
567     /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
568     if( i_nb_channels <= 2 )
569     {
570         waveformat.Format.cbSize = 0;
571     }
572     else
573     {
574         waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
575         waveformat.Format.cbSize =
576             sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
577     }
578
579     /* Open the device */
580     result = waveOutOpen( &p_aout->output.p_sys->h_waveout, WAVE_MAPPER,
581                           (WAVEFORMATEX *)&waveformat,
582                           (DWORD_PTR)WaveOutCallback, (DWORD_PTR)p_aout,
583                           CALLBACK_FUNCTION | (b_probe?WAVE_FORMAT_QUERY:0) );
584     if( result == WAVERR_BADFORMAT )
585     {
586         msg_Warn( p_aout, "waveOutOpen failed WAVERR_BADFORMAT" );
587         return VLC_EGENERIC;
588     }
589     if( result == MMSYSERR_ALLOCATED )
590     {
591         msg_Warn( p_aout, "waveOutOpen failed WAVERR_ALLOCATED" );
592         return VLC_EGENERIC;
593     }
594     if( result != MMSYSERR_NOERROR )
595     {
596         msg_Warn( p_aout, "waveOutOpen failed" );
597         return VLC_EGENERIC;
598     }
599
600     p_aout->output.p_sys->b_chan_reorder =
601         aout_CheckChannelReorder( pi_channels_in, pi_channels_out,
602                                   waveformat.dwChannelMask, i_nb_channels,
603                                   p_aout->output.p_sys->pi_chan_table );
604
605     if( p_aout->output.p_sys->b_chan_reorder )
606     {
607         msg_Dbg( p_aout, "channel reordering needed" );
608     }
609
610     return VLC_SUCCESS;
611
612 #undef waveformat
613
614 }
615
616 /*****************************************************************************
617  * OpenWaveOutPCM: open a PCM waveout sound device
618  ****************************************************************************/
619 static int OpenWaveOutPCM( aout_instance_t *p_aout, int *i_format,
620                            int i_channels, int i_nb_channels, int i_rate,
621                            vlc_bool_t b_probe )
622 {
623     vlc_value_t val;
624
625     var_Get( p_aout, "waveout-float32", &val );
626
627     if( !val.b_bool || OpenWaveOut( p_aout, VLC_FOURCC('f','l','3','2'),
628                                    i_channels, i_nb_channels, i_rate, b_probe )
629         != VLC_SUCCESS )
630     {
631         if ( OpenWaveOut( p_aout, VLC_FOURCC('s','1','6','l'),
632                           i_channels, i_nb_channels, i_rate, b_probe )
633              != VLC_SUCCESS )
634         {
635             return VLC_EGENERIC;
636         }
637         else
638         {
639             *i_format = VLC_FOURCC('s','1','6','l');
640             return VLC_SUCCESS;
641         }
642     }
643     else
644     {
645         *i_format = VLC_FOURCC('f','l','3','2');
646         return VLC_SUCCESS;
647     }
648 }
649
650 /*****************************************************************************
651  * PlayWaveOut: play a buffer through the WaveOut device
652  *****************************************************************************/
653 static int PlayWaveOut( aout_instance_t *p_aout, HWAVEOUT h_waveout,
654                         WAVEHDR *p_waveheader, aout_buffer_t *p_buffer )
655 {
656     MMRESULT result;
657
658     /* Prepare the buffer */
659     if( p_buffer != NULL )
660         p_waveheader->lpData = p_buffer->p_buffer;
661     else
662         /* Use silence buffer instead */
663         p_waveheader->lpData = p_aout->output.p_sys->p_silence_buffer;
664
665     p_waveheader->dwUser = p_buffer ? (DWORD_PTR)p_buffer : (DWORD_PTR)1;
666     p_waveheader->dwBufferLength = p_aout->output.p_sys->i_buffer_size;
667     p_waveheader->dwFlags = 0;
668
669     result = waveOutPrepareHeader( h_waveout, p_waveheader, sizeof(WAVEHDR) );
670     if( result != MMSYSERR_NOERROR )
671     {
672         msg_Err( p_aout, "waveOutPrepareHeader failed" );
673         return VLC_EGENERIC;
674     }
675
676     /* Send the buffer to the waveOut queue */
677     result = waveOutWrite( h_waveout, p_waveheader, sizeof(WAVEHDR) );
678     if( result != MMSYSERR_NOERROR )
679     {
680         msg_Err( p_aout, "waveOutWrite failed" );
681         return VLC_EGENERIC;
682     }
683
684     return VLC_SUCCESS;
685 }
686
687 /*****************************************************************************
688  * WaveOutCallback: what to do once WaveOut has played its sound samples
689  *****************************************************************************/
690 static void CALLBACK WaveOutCallback( HWAVEOUT h_waveout, UINT uMsg,
691                                       DWORD _p_aout,
692                                       DWORD dwParam1, DWORD dwParam2 )
693 {
694     aout_instance_t *p_aout = (aout_instance_t *)_p_aout;
695     int i, i_queued_frames = 0;
696
697     if( uMsg != WOM_DONE ) return;
698
699     if( p_aout->b_die ) return;
700
701     /* Find out the current latency */
702     for( i = 0; i < FRAMES_NUM; i++ )
703     {
704         /* Check if frame buf is available */
705         if( !(p_aout->output.p_sys->waveheader[i].dwFlags & WHDR_DONE) )
706         {
707             i_queued_frames++;
708         }
709     }
710
711     /* Don't wake up the thread too much */
712     if( i_queued_frames < FRAMES_NUM / 2 )
713         SetEvent( p_aout->output.p_sys->event );
714 }
715
716 /*****************************************************************************
717  * WaveOutThread: this thread will capture play notification events.
718  *****************************************************************************
719  * We use this thread to feed new audio samples to the sound card because
720  * we are not authorized to use waveOutWrite() directly in the waveout
721  * callback.
722  *****************************************************************************/
723 static void WaveOutThread( notification_thread_t *p_notif )
724 {
725     aout_instance_t *p_aout = p_notif->p_aout;
726     aout_sys_t *p_sys = p_aout->output.p_sys;
727     aout_buffer_t *p_buffer = NULL;
728     WAVEHDR *p_waveheader = p_sys->waveheader;
729     int i, i_queued_frames;
730     vlc_bool_t b_sleek;
731
732     /* We don't want any resampling when using S/PDIF */
733     b_sleek = p_aout->output.output.i_format == VLC_FOURCC('s','p','d','i');
734
735     while( 1 )
736     {
737         WaitForSingleObject( p_sys->event, INFINITE );
738
739         /* Cleanup and find out the current latency */
740         i_queued_frames = 0;
741         for( i = 0; i < FRAMES_NUM; i++ )
742         {
743             if( (p_waveheader[i].dwFlags & WHDR_DONE) &&
744                 p_waveheader[i].dwUser )
745             {
746                 aout_buffer_t *p_buffer =
747                         (aout_buffer_t *)(p_waveheader[i].dwUser);
748                 /* Unprepare and free the buffers which has just been played */
749                 waveOutUnprepareHeader( p_sys->h_waveout, &p_waveheader[i],
750                                         sizeof(WAVEHDR) );
751
752                 if( p_waveheader[i].dwUser != 1 )
753                     aout_BufferFree( p_buffer );
754
755                 p_waveheader[i].dwUser = 0;
756             }
757
758             /* Check if frame buf is available */
759             if( !(p_waveheader[i].dwFlags & WHDR_DONE) )
760             {
761                 i_queued_frames++;
762             }
763         }
764
765         if( p_aout->b_die ) return;
766
767         /* Try to fill in as many frame buffers as possible */
768         for( i = 0; i < FRAMES_NUM; i++ )
769         {
770             /* Check if frame buf is available */
771             if( p_waveheader[i].dwFlags & WHDR_DONE )
772             {
773                 /* Take into account the latency */
774                 p_buffer = aout_OutputNextBuffer( p_aout,
775                     mdate() + 1000000 * i_queued_frames /
776                     p_aout->output.output.i_rate * p_aout->output.i_nb_samples,
777                     b_sleek );
778
779                 if( !p_buffer && i_queued_frames )
780                 {
781                     /* We aren't late so no need to play a blank sample */
782                     break;
783                 }
784
785                 /* Do the channel reordering */
786                 if( p_buffer && p_sys->b_chan_reorder )
787                 {
788                     aout_ChannelReorder( p_buffer->p_buffer,
789                         p_buffer->i_nb_bytes,
790                         p_sys->waveformat.Format.nChannels,
791                         p_sys->pi_chan_table,
792                         p_sys->waveformat.Format.wBitsPerSample );
793                 }
794
795                 PlayWaveOut( p_aout, p_sys->h_waveout,
796                              &p_waveheader[i], p_buffer );
797
798                 i_queued_frames++;
799             }
800         }
801     }
802 }
803
804 static int VolumeInfos( aout_instance_t * p_aout, audio_volume_t * pi_soft )
805 {
806     *pi_soft = AOUT_VOLUME_MAX / 2;
807     return 0;
808 }
809
810 static int VolumeGet( aout_instance_t * p_aout, audio_volume_t * pi_volume )
811 {
812     DWORD i_waveout_vol;
813
814 #ifdef UNDER_CE
815     waveOutGetVolume( 0, &i_waveout_vol );
816 #else
817     waveOutGetVolume( p_aout->output.p_sys->h_waveout, &i_waveout_vol );
818 #endif
819
820     i_waveout_vol &= 0xFFFF;
821     *pi_volume = p_aout->output.i_volume =
822         (i_waveout_vol * AOUT_VOLUME_MAX + 0xFFFF /*rounding*/) / 2 / 0xFFFF;
823     return 0;
824 }
825
826 static int VolumeSet( aout_instance_t * p_aout, audio_volume_t i_volume )
827 {
828     unsigned long i_waveout_vol = i_volume * 0xFFFF * 2 / AOUT_VOLUME_MAX;
829     i_waveout_vol |= (i_waveout_vol << 16);
830
831 #ifdef UNDER_CE
832     waveOutSetVolume( 0, i_waveout_vol );
833 #else
834     waveOutSetVolume( p_aout->output.p_sys->h_waveout, i_waveout_vol );
835 #endif
836
837     p_aout->output.i_volume = i_volume;
838     return 0;
839 }