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