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