]> git.sesse.net Git - vlc/blob - modules/audio_output/waveout.c
* modules/audio_output/directx.c, modules/audio_output/waveout.c: we destroy the...
[vlc] / modules / audio_output / waveout.c
1 /*****************************************************************************
2  * waveout.c : Windows waveOut plugin for vlc
3  *****************************************************************************
4  * Copyright (C) 2001 VideoLAN
5  * $Id: waveout.c,v 1.25 2003/05/21 15:54:08 gbazin Exp $
6  *
7  * Authors: Gildas Bazin <gbazin@netcourrier.com>
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 4
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 #include <initguid.h>
96 DEFINE_GUID( __KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, WAVE_FORMAT_IEEE_FLOAT, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
97 DEFINE_GUID( __KSDATAFORMAT_SUBTYPE_PCM, WAVE_FORMAT_PCM, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
98 DEFINE_GUID( __KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF, WAVE_FORMAT_DOLBY_AC3_SPDIF, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
99
100 /*****************************************************************************
101  * Local prototypes
102  *****************************************************************************/
103 static int  Open         ( vlc_object_t * );
104 static void Close        ( vlc_object_t * );
105 static void Play         ( aout_instance_t * );
106
107 /* local functions */
108 static void Probe        ( aout_instance_t * );
109 static int OpenWaveOut   ( aout_instance_t *, int, int, int, int, vlc_bool_t );
110 static int OpenWaveOutPCM( aout_instance_t *, int*, int, int, int, vlc_bool_t );
111 static void CheckReordering( aout_instance_t *, int );
112 static int PlayWaveOut   ( aout_instance_t *, HWAVEOUT, WAVEHDR *,
113                            aout_buffer_t * );
114
115 static void CALLBACK WaveOutCallback ( HWAVEOUT, UINT, DWORD, DWORD, DWORD );
116
117 static void InterleaveFloat32( float *, int *, int );
118 static void InterleaveS16( int16_t *, int *, int );
119
120 /*****************************************************************************
121  * Module descriptor
122  *****************************************************************************/
123 vlc_module_begin();
124     set_description( _("Win32 waveOut extension output") );
125     set_capability( "audio output", 50 );
126     set_callbacks( Open, Close );
127 vlc_module_end();
128
129 /*****************************************************************************
130  * aout_sys_t: waveOut audio output method descriptor
131  *****************************************************************************
132  * This structure is part of the audio output thread descriptor.
133  * It describes the waveOut specific properties of an audio device.
134  *****************************************************************************/
135 struct aout_sys_t
136 {
137     HWAVEOUT h_waveout;                        /* handle to waveout instance */
138
139     WAVEFORMATEXTENSIBLE waveformat;                         /* audio format */
140
141     WAVEHDR waveheader[FRAMES_NUM];
142
143     int i_buffer_size;
144
145     byte_t *p_silence_buffer;               /* buffer we use to play silence */
146
147     vlc_bool_t b_chan_reorder;              /* do we need channel reordering */
148     int *pi_chan_table;
149 };
150
151 static const uint32_t pi_channels_in[] =
152     { AOUT_CHAN_LEFT, AOUT_CHAN_RIGHT,
153       AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT,
154       AOUT_CHAN_CENTER, AOUT_CHAN_LFE };
155 static const uint32_t pi_channels_out[] =
156     { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT,
157       SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT,
158       SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY };
159 static const uint32_t pi_channels_ordered[] =
160     { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT, SPEAKER_FRONT_CENTER,
161       SPEAKER_LOW_FREQUENCY,
162       SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT };
163
164 /*****************************************************************************
165  * Open: open the audio device
166  *****************************************************************************
167  * This function opens and setups Win32 waveOut
168  *****************************************************************************/
169 static int Open( vlc_object_t *p_this )
170 {
171     aout_instance_t *p_aout = (aout_instance_t *)p_this;
172     vlc_value_t val;
173     int i;
174
175     /* Allocate structure */
176     p_aout->output.p_sys = malloc( sizeof( aout_sys_t ) );
177
178     if( p_aout->output.p_sys == NULL )
179     {
180         msg_Err( p_aout, "out of memory" );
181         return VLC_EGENERIC;
182     }
183
184     p_aout->output.pf_play = Play;
185     p_aout->output.p_sys->pi_chan_table = NULL;
186     p_aout->b_die = VLC_FALSE;
187
188     if( var_Type( p_aout, "audio-device" ) == 0 )
189     {
190         Probe( p_aout );
191     }
192
193     if( var_Get( p_aout, "audio-device", &val ) < 0 )
194     {
195         /* Probe() has failed. */
196         free( p_aout->output.p_sys );
197         return VLC_EGENERIC;
198     }
199
200     /* Open the device */
201     if( val.i_int == AOUT_VAR_SPDIF )
202     {
203         p_aout->output.output.i_format = VLC_FOURCC('s','p','d','i');
204
205         if( OpenWaveOut( p_aout, VLC_FOURCC('s','p','d','i'),
206                          p_aout->output.output.i_physical_channels,
207                          aout_FormatNbChannels( &p_aout->output.output ),
208                          p_aout->output.output.i_rate, VLC_FALSE )
209             != VLC_SUCCESS )
210         {
211             msg_Err( p_aout, "cannot open waveout audio device" );
212             free( p_aout->output.p_sys );
213             return VLC_EGENERIC;
214         }
215
216         /* Calculate the frame size in bytes */
217         p_aout->output.i_nb_samples = A52_FRAME_NB;
218         p_aout->output.output.i_bytes_per_frame = AOUT_SPDIF_SIZE;
219         p_aout->output.output.i_frame_length = A52_FRAME_NB;
220         p_aout->output.p_sys->i_buffer_size =
221             p_aout->output.output.i_bytes_per_frame;
222
223         aout_VolumeNoneInit( p_aout );
224     }
225     else
226     {
227         if( val.i_int == AOUT_VAR_5_1 )
228         {
229             p_aout->output.output.i_physical_channels
230                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
231                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
232                    | AOUT_CHAN_LFE;
233         }
234         else if( val.i_int == AOUT_VAR_2F2R )
235         {
236             p_aout->output.output.i_physical_channels
237                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
238                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
239         }
240         else if( val.i_int == AOUT_VAR_MONO )
241         {
242             p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
243         }
244         else
245         {
246             p_aout->output.output.i_physical_channels
247                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
248         }
249
250         if( OpenWaveOutPCM( p_aout, &p_aout->output.output.i_format,
251                             p_aout->output.output.i_physical_channels,
252                             aout_FormatNbChannels( &p_aout->output.output ),
253                             p_aout->output.output.i_rate, VLC_FALSE )
254             != VLC_SUCCESS )
255         {
256             msg_Err( p_aout, "cannot open waveout audio device" );
257             free( p_aout->output.p_sys );
258             return VLC_EGENERIC;
259         }
260
261         /* Calculate the frame size in bytes */
262         p_aout->output.i_nb_samples = FRAME_SIZE;
263         aout_FormatPrepare( &p_aout->output.output );
264         p_aout->output.p_sys->i_buffer_size = FRAME_SIZE *
265             p_aout->output.output.i_bytes_per_frame;
266
267         aout_VolumeSoftInit( p_aout );
268     }
269
270
271     waveOutReset( p_aout->output.p_sys->h_waveout );
272
273     /* Allocate silence buffer */
274     p_aout->output.p_sys->p_silence_buffer =
275         malloc( p_aout->output.p_sys->i_buffer_size );
276     if( p_aout->output.p_sys->p_silence_buffer == NULL )
277     {
278         free( p_aout->output.p_sys );
279         msg_Err( p_aout, "out of memory" );
280         return 1;
281     }
282
283     /* Zero the buffer. WinCE doesn't have calloc(). */
284     memset( p_aout->output.p_sys->p_silence_buffer, 0,
285             p_aout->output.p_sys->i_buffer_size );
286
287     /* We need to kick off the playback in order to have the callback properly
288      * working */
289     for( i = 0; i < FRAMES_NUM; i++ )
290     {
291         p_aout->output.p_sys->waveheader[i].dwFlags = WHDR_DONE;
292     }
293     PlayWaveOut( p_aout, p_aout->output.p_sys->h_waveout,
294                  &p_aout->output.p_sys->waveheader[0], NULL );
295
296     return 0;
297 }
298
299 /*****************************************************************************
300  * Probe: probe the audio device for available formats and channels
301  *****************************************************************************/
302 static void Probe( aout_instance_t * p_aout )
303 {
304     vlc_value_t val, text;
305     int i_format;
306     unsigned int i_physical_channels;
307
308     var_Create( p_aout, "audio-device", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
309     text.psz_string = _("Audio device");
310     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
311
312     /* Test for 5.1 support */
313     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
314                           AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
315                           AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE;
316     if( p_aout->output.output.i_physical_channels == i_physical_channels )
317     {
318         if( OpenWaveOutPCM( p_aout, &i_format,
319                             i_physical_channels, 6,
320                             p_aout->output.output.i_rate, VLC_TRUE )
321             == VLC_SUCCESS )
322         {
323             val.i_int = AOUT_VAR_5_1;
324             text.psz_string = N_("5.1");
325             var_Change( p_aout, "audio-device",
326                         VLC_VAR_ADDCHOICE, &val, &text );
327             msg_Dbg( p_aout, "device supports 5.1 channels" );
328         }
329     }
330
331     /* Test for 2 Front 2 Rear support */
332     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
333                           AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
334     if( ( p_aout->output.output.i_physical_channels & i_physical_channels )
335         == i_physical_channels )
336     {
337         if( OpenWaveOutPCM( p_aout, &i_format,
338                             i_physical_channels, 4,
339                             p_aout->output.output.i_rate, VLC_TRUE )
340             == VLC_SUCCESS )
341         {
342             val.i_int = AOUT_VAR_2F2R;
343             text.psz_string = N_("2 Front 2 Rear");
344             var_Change( p_aout, "audio-device",
345                         VLC_VAR_ADDCHOICE, &val, &text );
346             msg_Dbg( p_aout, "device supports 4 channels" );
347         }
348     }
349
350     /* Test for stereo support */
351     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
352     if( OpenWaveOutPCM( p_aout, &i_format,
353                         i_physical_channels, 2,
354                         p_aout->output.output.i_rate, VLC_TRUE )
355         == VLC_SUCCESS )
356     {
357         val.i_int = AOUT_VAR_STEREO;
358         text.psz_string = N_("Stereo");
359         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
360         msg_Dbg( p_aout, "device supports 2 channels" );
361     }
362
363     /* Test for mono support */
364     i_physical_channels = AOUT_CHAN_CENTER;
365     if( OpenWaveOutPCM( p_aout, &i_format,
366                         i_physical_channels, 1,
367                         p_aout->output.output.i_rate, VLC_TRUE )
368         == VLC_SUCCESS )
369     {
370         val.i_int = AOUT_VAR_MONO;
371         text.psz_string = N_("Mono");
372         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
373         msg_Dbg( p_aout, "device supports 1 channel" );
374     }
375
376     /* Test for SPDIF support */
377     if ( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
378     {
379         if( OpenWaveOut( p_aout, VLC_FOURCC('s','p','d','i'),
380                          p_aout->output.output.i_physical_channels,
381                          aout_FormatNbChannels( &p_aout->output.output ),
382                          p_aout->output.output.i_rate, VLC_TRUE )
383             == VLC_SUCCESS )
384         {
385             msg_Dbg( p_aout, "device supports A/52 over S/PDIF" );
386             val.i_int = AOUT_VAR_SPDIF;
387             text.psz_string = N_("A/52 over S/PDIF");
388             var_Change( p_aout, "audio-device",
389                         VLC_VAR_ADDCHOICE, &val, &text );
390             if( config_GetInt( p_aout, "spdif" ) )
391                 var_Set( p_aout, "audio-device", val );
392         }
393     }
394
395     var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
396     if( val.i_int <= 0 )
397     {
398         /* Probe() has failed. */
399         var_Destroy( p_aout, "audio-device" );
400         return;
401     }
402
403     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
404
405     val.b_bool = VLC_TRUE;
406     var_Set( p_aout, "intf-change", val );
407 }
408
409 /*****************************************************************************
410  * Play: play a sound buffer
411  *****************************************************************************
412  * This doesn't actually play the buffer. This just stores the buffer so it
413  * can be played by the callback thread.
414  *****************************************************************************/
415 static void Play( aout_instance_t *p_aout )
416 {
417 }
418
419 /*****************************************************************************
420  * Close: close the audio device
421  *****************************************************************************/
422 static void Close( vlc_object_t *p_this )
423 {
424     aout_instance_t *p_aout = (aout_instance_t *)p_this;
425
426     /* Before calling waveOutClose we must reset the device */
427     p_aout->b_die = VLC_TRUE;
428
429     /* Wait for the waveout buffers to be freed */
430     while( VLC_TRUE )
431     {
432         int i;
433         vlc_bool_t b_not_done = VLC_FALSE;
434
435         for( i = 0; i < FRAMES_NUM; i++ )
436         {
437            if( !(p_aout->output.p_sys->waveheader[i].dwFlags & WHDR_DONE) )
438                b_not_done = VLC_TRUE;
439         }
440
441         if( !b_not_done )
442             break;
443
444         msleep( 1000 );
445     }
446
447     waveOutReset( p_aout->output.p_sys->h_waveout );
448
449     /* Close the device */
450     if( waveOutClose( p_aout->output.p_sys->h_waveout ) != MMSYSERR_NOERROR )
451     {
452         msg_Err( p_aout, "waveOutClose failed" );
453     }
454
455     free( p_aout->output.p_sys->p_silence_buffer );
456     if( p_aout->output.p_sys->pi_chan_table )
457         free( p_aout->output.p_sys->pi_chan_table );
458     free( p_aout->output.p_sys );
459 }
460
461 /*****************************************************************************
462  * OpenWaveOut: open the waveout sound device
463  ****************************************************************************/
464 static int OpenWaveOut( aout_instance_t *p_aout, int i_format,
465                         int i_channels, int i_nb_channels, int i_rate,
466                         vlc_bool_t b_probe )
467 {
468     MMRESULT result;
469     unsigned int i;
470
471     /* Set sound format */
472
473 #define waveformat p_aout->output.p_sys->waveformat
474
475     waveformat.dwChannelMask = 0;
476     for( i = 0; i < sizeof(pi_channels_in)/sizeof(uint32_t); i++ )
477     {
478         if( i_channels & pi_channels_in[i] )
479             waveformat.dwChannelMask |= pi_channels_out[i];
480     }
481
482     switch( i_format )
483     {
484     case VLC_FOURCC('s','p','d','i'):
485         i_nb_channels = 2;
486         /* To prevent channel re-ordering */
487         waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
488         waveformat.Format.wBitsPerSample = 16;
489         waveformat.Samples.wValidBitsPerSample =
490             waveformat.Format.wBitsPerSample;
491         waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
492         waveformat.SubFormat = __KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
493         break;
494
495     case VLC_FOURCC('f','l','3','2'):
496         waveformat.Format.wBitsPerSample = sizeof(float) * 8;
497         waveformat.Samples.wValidBitsPerSample =
498             waveformat.Format.wBitsPerSample;
499         waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
500         waveformat.SubFormat = __KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
501         break;
502
503     case VLC_FOURCC('s','1','6','l'):
504         waveformat.Format.wBitsPerSample = 16;
505         waveformat.Samples.wValidBitsPerSample =
506             waveformat.Format.wBitsPerSample;
507         waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
508         waveformat.SubFormat = __KSDATAFORMAT_SUBTYPE_PCM;
509         break;
510     }
511
512     waveformat.Format.nChannels = i_nb_channels;
513     waveformat.Format.nSamplesPerSec = i_rate;
514     waveformat.Format.nBlockAlign =
515         waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
516     waveformat.Format.nAvgBytesPerSec =
517         waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;
518
519     /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
520     if( i_nb_channels <= 2 )
521     {
522         waveformat.Format.cbSize = 0;
523     }
524     else
525     {
526         waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
527         waveformat.Format.cbSize =
528             sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
529     }
530
531     /* Open the device */
532     result = waveOutOpen( &p_aout->output.p_sys->h_waveout, WAVE_MAPPER,
533                           (WAVEFORMATEX *)&waveformat,
534                           (DWORD_PTR)WaveOutCallback, (DWORD_PTR)p_aout,
535                           CALLBACK_FUNCTION | (b_probe?WAVE_FORMAT_QUERY:0) );
536     if( result == WAVERR_BADFORMAT )
537     {
538         msg_Warn( p_aout, "waveOutOpen failed WAVERR_BADFORMAT" );
539         return VLC_EGENERIC;
540     }
541     if( result == MMSYSERR_ALLOCATED )
542     {
543         msg_Warn( p_aout, "waveOutOpen failed WAVERR_ALLOCATED" );
544         return VLC_EGENERIC;
545     }
546     if( result != MMSYSERR_NOERROR )
547     {
548         msg_Warn( p_aout, "waveOutOpen failed" );
549         return VLC_EGENERIC;
550     }
551
552     CheckReordering( p_aout, i_nb_channels );
553
554     return VLC_SUCCESS;
555
556 #undef waveformat
557
558 }
559
560 /*****************************************************************************
561  * OpenWaveOutPCM: open a PCM waveout sound device
562  ****************************************************************************/
563 static int OpenWaveOutPCM( aout_instance_t *p_aout, int *i_format,
564                            int i_channels, int i_nb_channels, int i_rate,
565                            vlc_bool_t b_probe )
566 {
567     if( OpenWaveOut( p_aout, VLC_FOURCC('f','l','3','2'),
568                      i_channels, i_nb_channels, i_rate, b_probe )
569         != VLC_SUCCESS )
570     {
571         if ( OpenWaveOut( p_aout, VLC_FOURCC('s','1','6','l'),
572                           i_channels, i_nb_channels, i_rate, b_probe )
573              != VLC_SUCCESS )
574         {
575             return VLC_EGENERIC;
576         }
577         else
578         {
579             *i_format = VLC_FOURCC('s','1','6','l');
580             return VLC_SUCCESS;
581         }
582     }
583     else
584     {
585         *i_format = VLC_FOURCC('f','l','3','2');
586         return VLC_SUCCESS;
587     }
588 }
589
590 /*****************************************************************************
591  * CheckReordering: Check if we need to do some channel re-ordering (the ac3
592  *                  channel order is different from the one chosen by
593  *                  Microsoft).
594  *****************************************************************************/
595 static void CheckReordering( aout_instance_t *p_aout, int i_nb_channels )
596 {
597     int i, j, k, l;
598
599 #define waveformat p_aout->output.p_sys->waveformat
600 #define pi_chan_table p_aout->output.p_sys->pi_chan_table
601
602     p_aout->output.p_sys->b_chan_reorder = VLC_FALSE;
603
604     pi_chan_table = malloc( i_nb_channels * sizeof(int) );
605     if( !pi_chan_table )
606     {
607         return;
608     }
609
610     for( i = 0, j = 0;
611          i < (int)(sizeof(pi_channels_out)/sizeof(uint32_t)); i++ )
612     {
613         if( waveformat.dwChannelMask & pi_channels_out[i] )
614         {
615             for( k = 0, l = 0;
616                  pi_channels_out[i] != pi_channels_ordered[k]; k++ )
617             {
618                 if( waveformat.dwChannelMask & pi_channels_ordered[k] )
619                 {
620                     l++;
621                 }
622             }
623
624             pi_chan_table[j] = l;
625
626             j++;
627         }
628     }
629
630     for( i = 0; i < i_nb_channels; i++ )
631     {
632         if( pi_chan_table[i] != i )
633         {
634             p_aout->output.p_sys->b_chan_reorder = VLC_TRUE;
635         }
636     }
637
638     if( p_aout->output.p_sys->b_chan_reorder )
639     {
640         msg_Dbg( p_aout, "channel reordering needed" );
641     }
642
643 #undef pi_chan_table
644 #undef waveformat
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 = (DWORD_PTR)p_buffer;
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     WAVEHDR *p_waveheader = (WAVEHDR *)dwParam1;
693     aout_buffer_t *p_buffer = NULL;
694     vlc_bool_t b_sleek;
695     int i, i_queued_frames = 0;
696
697     if( uMsg != WOM_DONE ) return;
698
699     /* Unprepare and free the buffer which has just been played */
700     waveOutUnprepareHeader( h_waveout, p_waveheader, sizeof(WAVEHDR) );
701     if( p_waveheader->dwUser )
702         aout_BufferFree( (aout_buffer_t *)p_waveheader->dwUser );
703
704     if( p_aout->b_die ) return;
705
706     /* We don't want any resampling when using S/PDIF */
707     b_sleek = p_aout->output.output.i_format == VLC_FOURCC('s','p','d','i');
708
709     /* Find out the current latency */
710     for( i = 0; i < FRAMES_NUM; i++ )
711     {
712         /* Check if frame buf is available */
713         if( !(p_aout->output.p_sys->waveheader[i].dwFlags & WHDR_DONE) )
714         {
715             i_queued_frames++;
716         }
717     }
718
719     /* Try to fill in as many frame buffers as possible */
720     for( i = 0; i < FRAMES_NUM; i++ )
721     {
722         /* Check if frame buf is available */
723         if( p_aout->output.p_sys->waveheader[i].dwFlags & WHDR_DONE )
724         {
725             /* Take into account the latency */
726             p_buffer = aout_OutputNextBuffer( p_aout,
727                 mdate() + 1000000 * i_queued_frames /
728                     p_aout->output.output.i_rate * p_aout->output.i_nb_samples,
729                 b_sleek );
730
731             if( !p_buffer && i_queued_frames )
732             {
733                 /* We aren't late so no need to play a blank sample */
734                 return;
735             }
736
737             /* Do the channel reordering here */
738             if( p_buffer && p_aout->output.p_sys->b_chan_reorder )
739             {
740                 if( p_aout->output.output.i_format ==
741                         VLC_FOURCC('s','1','6','l') )
742                     InterleaveS16( (int16_t *)p_buffer->p_buffer,
743                         p_aout->output.p_sys->pi_chan_table,
744                         aout_FormatNbChannels( &p_aout->output.output ) );
745                 else
746                     InterleaveFloat32( (float *)p_buffer->p_buffer,
747                         p_aout->output.p_sys->pi_chan_table,
748                         aout_FormatNbChannels( &p_aout->output.output ) );
749             }
750
751             PlayWaveOut( p_aout, h_waveout,
752                          &p_aout->output.p_sys->waveheader[i] , p_buffer );
753
754             i_queued_frames++;
755         }
756     }
757 }
758
759 /*****************************************************************************
760  * InterleaveFloat32/S16: change the channel order to the Microsoft one.
761  *****************************************************************************/
762 static void InterleaveFloat32( float *p_buf, int *pi_chan_table,
763                                int i_nb_channels )
764 {
765     int i, j;
766     float p_tmp[10];
767
768     for( i = 0; i < FRAME_SIZE; i++ )
769     {
770         for( j = 0; j < i_nb_channels; j++ )
771         {
772             p_tmp[pi_chan_table[j]] = p_buf[i*i_nb_channels + j];
773         }
774
775         memcpy( &p_buf[i*i_nb_channels], p_tmp,
776                 i_nb_channels * sizeof(float) );
777     }
778 }
779
780 static void InterleaveS16( int16_t *p_buf, int *pi_chan_table,
781                            int i_nb_channels )
782 {
783     int i, j;
784     int16_t p_tmp[10];
785
786     for( i = 0; i < FRAME_SIZE; i++ )
787     {
788         for( j = 0; j < i_nb_channels; j++ )
789         {
790             p_tmp[pi_chan_table[j]] = p_buf[i*i_nb_channels + j];
791         }
792
793         memcpy( &p_buf[i*i_nb_channels], p_tmp,
794                 i_nb_channels * sizeof(int16_t) );
795     }
796 }