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