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