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