]> git.sesse.net Git - vlc/blob - modules/audio_output/directx.c
* src/extras/libc.c, nclude/vlc_common.h, modules/mux/mpeg/ts.c: added atoll() to...
[vlc] / modules / audio_output / directx.c
1 /*****************************************************************************
2  * directx.c: Windows DirectX audio output method
3  *****************************************************************************
4  * Copyright (C) 2001 VideoLAN
5  * $Id: directx.c,v 1.23 2003/08/14 11:47:32 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 <errno.h>                                                 /* ENOMEM */
28 #include <fcntl.h>                                       /* open(), O_WRONLY */
29 #include <string.h>                                            /* strerror() */
30
31 #include <stdlib.h>                            /* calloc(), malloc(), free() */
32
33 #include <vlc/vlc.h>
34 #include <vlc/aout.h>
35 #include "aout_internal.h"
36
37 #include <windows.h>
38 #include <mmsystem.h>
39 #include <dsound.h>
40
41 #define FRAME_SIZE 2048              /* The size is in samples, not in bytes */
42 #define FRAMES_NUM 8
43
44 /* frame buffer status */
45 #define FRAME_QUEUED 0
46 #define FRAME_EMPTY 1
47
48 /*****************************************************************************
49  * DirectSound GUIDs.
50  * Defining them here allows us to get rid of the dxguid library during
51  * the linking stage.
52  *****************************************************************************/
53 #include <initguid.h>
54 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf, 0x8, 0x0, 0xa0, 0xc9, 0x25, 0xcd, 0x16);
55
56 /*****************************************************************************
57  * Useful macros
58  *****************************************************************************/
59 #ifndef WAVE_FORMAT_IEEE_FLOAT
60 #   define WAVE_FORMAT_IEEE_FLOAT 0x0003
61 #endif
62
63 #ifndef WAVE_FORMAT_DOLBY_AC3_SPDIF
64 #   define WAVE_FORMAT_DOLBY_AC3_SPDIF 0x0092
65 #endif
66
67 #ifndef WAVE_FORMAT_EXTENSIBLE
68 #define  WAVE_FORMAT_EXTENSIBLE   0xFFFE
69 #endif
70
71 #ifndef SPEAKER_FRONT_LEFT
72 #   define SPEAKER_FRONT_LEFT             0x1
73 #   define SPEAKER_FRONT_RIGHT            0x2
74 #   define SPEAKER_FRONT_CENTER           0x4
75 #   define SPEAKER_LOW_FREQUENCY          0x8
76 #   define SPEAKER_BACK_LEFT              0x10
77 #   define SPEAKER_BACK_RIGHT             0x20
78 #   define SPEAKER_FRONT_LEFT_OF_CENTER   0x40
79 #   define SPEAKER_FRONT_RIGHT_OF_CENTER  0x80
80 #   define SPEAKER_BACK_CENTER            0x100
81 #   define SPEAKER_SIDE_LEFT              0x200
82 #   define SPEAKER_SIDE_RIGHT             0x400
83 #   define SPEAKER_TOP_CENTER             0x800
84 #   define SPEAKER_TOP_FRONT_LEFT         0x1000
85 #   define SPEAKER_TOP_FRONT_CENTER       0x2000
86 #   define SPEAKER_TOP_FRONT_RIGHT        0x4000
87 #   define SPEAKER_TOP_BACK_LEFT          0x8000
88 #   define SPEAKER_TOP_BACK_CENTER        0x10000
89 #   define SPEAKER_TOP_BACK_RIGHT         0x20000
90 #   define SPEAKER_RESERVED               0x80000000
91 #endif
92
93 #ifndef DSSPEAKER_HEADPHONE
94 #   define DSSPEAKER_HEADPHONE         0x00000001
95 #endif
96 #ifndef DSSPEAKER_MONO
97 #   define DSSPEAKER_MONO              0x00000002
98 #endif
99 #ifndef DSSPEAKER_QUAD
100 #   define DSSPEAKER_QUAD              0x00000003
101 #endif
102 #ifndef DSSPEAKER_STEREO
103 #   define DSSPEAKER_STEREO            0x00000004
104 #endif
105 #ifndef DSSPEAKER_SURROUND
106 #   define DSSPEAKER_SURROUND          0x00000005
107 #endif
108 #ifndef DSSPEAKER_5POINT1
109 #   define DSSPEAKER_5POINT1           0x00000006
110 #endif
111
112 #ifndef _WAVEFORMATEXTENSIBLE_
113 typedef struct {
114     WAVEFORMATEX    Format;
115     union {
116         WORD wValidBitsPerSample;       /* bits of precision  */
117         WORD wSamplesPerBlock;          /* valid if wBitsPerSample==0 */
118         WORD wReserved;                 /* If neither applies, set to zero. */
119     } Samples;
120     DWORD           dwChannelMask;      /* which channels are */
121                                         /* present in stream  */
122     GUID            SubFormat;
123 } WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;
124 #endif
125
126 DEFINE_GUID( _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, WAVE_FORMAT_IEEE_FLOAT, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
127 DEFINE_GUID( _KSDATAFORMAT_SUBTYPE_PCM, WAVE_FORMAT_PCM, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
128 DEFINE_GUID( _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF, WAVE_FORMAT_DOLBY_AC3_SPDIF, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
129
130 /*****************************************************************************
131  * notification_thread_t: DirectX event thread
132  *****************************************************************************/
133 typedef struct notification_thread_t
134 {
135     VLC_COMMON_MEMBERS
136
137     aout_instance_t * p_aout;
138     int i_frame_status[FRAMES_NUM];           /* status of each frame buffer */
139     DSBPOSITIONNOTIFY p_events[FRAMES_NUM];      /* play notification events */
140     int i_frame_size;                         /* Size in bytes of one frame */
141
142     mtime_t start_date;
143
144 } notification_thread_t;
145
146 /*****************************************************************************
147  * aout_sys_t: directx audio output method descriptor
148  *****************************************************************************
149  * This structure is part of the audio output thread descriptor.
150  * It describes the direct sound specific properties of an audio device.
151  *****************************************************************************/
152 struct aout_sys_t
153 {
154     HINSTANCE           hdsound_dll;      /* handle of the opened dsound dll */
155     LPDIRECTSOUND       p_dsobject;              /* main Direct Sound object */
156     LPDIRECTSOUNDBUFFER p_dsbuffer;   /* the sound buffer we use (direct sound
157                                        * takes care of mixing all the
158                                        * secondary buffers into the primary) */
159
160     LPDIRECTSOUNDNOTIFY p_dsnotify;         /* the position notify interface */
161     notification_thread_t *p_notif;                  /* DirectSoundThread id */
162
163     int b_playing;                                         /* playing status */
164
165     int i_frame_size;                         /* Size in bytes of one frame */
166
167     vlc_bool_t b_chan_reorder;              /* do we need channel reordering */
168     int *pi_chan_table;
169     uint32_t i_channel_mask;
170 };
171
172 static const uint32_t pi_channels_in[] =
173     { AOUT_CHAN_LEFT, AOUT_CHAN_RIGHT,
174       AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT,
175       AOUT_CHAN_CENTER, AOUT_CHAN_LFE };
176 static const uint32_t pi_channels_out[] =
177     { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT,
178       SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT,
179       SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY };
180 static const uint32_t pi_channels_ordered[] =
181     { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT, SPEAKER_FRONT_CENTER,
182       SPEAKER_LOW_FREQUENCY,
183       SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT };
184
185 /*****************************************************************************
186  * Local prototypes.
187  *****************************************************************************/
188 static int  OpenAudio  ( vlc_object_t * );
189 static void CloseAudio ( vlc_object_t * );
190 static void Play       ( aout_instance_t * );
191
192 /* local functions */
193 static void Probe             ( aout_instance_t * );
194 static int  InitDirectSound   ( aout_instance_t * );
195 static int  CreateDSBuffer    ( aout_instance_t *, int, int, int, int, int, vlc_bool_t );
196 static int  CreateDSBufferPCM ( aout_instance_t *, int*, int, int, int, vlc_bool_t );
197 static void DestroyDSBuffer   ( aout_instance_t * );
198 static void DirectSoundThread ( notification_thread_t * );
199 static int  FillBuffer        ( aout_instance_t *, int, aout_buffer_t * );
200
201 static void CheckReordering   ( aout_instance_t *, int );
202 static void InterleaveFloat32 ( float *, float *, int *, int );
203 static void InterleaveS16     ( int16_t *, int16_t *, int *, int );
204
205 /*****************************************************************************
206  * Module descriptor
207  *****************************************************************************/
208 vlc_module_begin();
209     set_description( _("DirectX audio output") );
210     set_capability( "audio output", 100 );
211     add_shortcut( "directx" );
212     set_callbacks( OpenAudio, CloseAudio );
213 vlc_module_end();
214
215 /*****************************************************************************
216  * OpenAudio: open the audio device
217  *****************************************************************************
218  * This function opens and setups Direct Sound.
219  *****************************************************************************/
220 static int OpenAudio( vlc_object_t *p_this )
221 {
222     aout_instance_t * p_aout = (aout_instance_t *)p_this;
223     vlc_value_t val;
224     int i;
225
226     msg_Dbg( p_aout, "OpenAudio" );
227
228    /* Allocate structure */
229     p_aout->output.p_sys = malloc( sizeof( aout_sys_t ) );
230     if( p_aout->output.p_sys == NULL )
231     {
232         msg_Err( p_aout, "out of memory" );
233         return VLC_EGENERIC;
234     }
235
236     /* Initialize some variables */
237     p_aout->output.p_sys->p_dsobject = NULL;
238     p_aout->output.p_sys->p_dsbuffer = NULL;
239     p_aout->output.p_sys->p_dsnotify = NULL;
240     p_aout->output.p_sys->p_notif = NULL;
241     p_aout->output.p_sys->b_playing = 0;
242     p_aout->output.p_sys->pi_chan_table = NULL;
243
244     p_aout->output.pf_play = Play;
245     aout_VolumeSoftInit( p_aout );
246
247     /* Initialise DirectSound */
248     if( InitDirectSound( p_aout ) )
249     {
250         msg_Err( p_aout, "cannot initialize DirectSound" );
251         goto error;
252     }
253
254     if( var_Type( p_aout, "audio-device" ) == 0 )
255     {
256         Probe( p_aout );
257     }
258
259     if( var_Get( p_aout, "audio-device", &val ) < 0 )
260     {
261         /* Probe() has failed. */
262         goto error;
263     }
264
265     /* Now we need to setup our DirectSound play notification structure */
266     p_aout->output.p_sys->p_notif =
267         vlc_object_create( p_aout, sizeof(notification_thread_t) );
268     p_aout->output.p_sys->p_notif->p_aout = p_aout;
269
270     /* Then create the notification events */
271     for( i = 0; i < FRAMES_NUM; i++ )
272         p_aout->output.p_sys->p_notif->p_events[i].hEventNotify =
273             CreateEvent( NULL, FALSE, FALSE, NULL );
274
275     /* Open the device */
276     if( val.i_int == AOUT_VAR_SPDIF )
277     {
278         p_aout->output.output.i_format = VLC_FOURCC('s','p','d','i');
279
280         /* Calculate the frame size in bytes */
281         p_aout->output.i_nb_samples = A52_FRAME_NB;
282         p_aout->output.output.i_bytes_per_frame = AOUT_SPDIF_SIZE;
283         p_aout->output.output.i_frame_length = A52_FRAME_NB;
284         p_aout->output.p_sys->i_frame_size =
285             p_aout->output.output.i_bytes_per_frame;
286
287         if( CreateDSBuffer( p_aout, VLC_FOURCC('s','p','d','i'),
288                             p_aout->output.output.i_physical_channels,
289                             aout_FormatNbChannels( &p_aout->output.output ),
290                             p_aout->output.output.i_rate,
291                             p_aout->output.p_sys->i_frame_size, VLC_FALSE )
292             != VLC_SUCCESS )
293         {
294             msg_Err( p_aout, "cannot open directx audio device" );
295             free( p_aout->output.p_sys );
296             return VLC_EGENERIC;
297         }
298
299         aout_VolumeNoneInit( p_aout );
300     }
301     else
302     {
303         if( val.i_int == AOUT_VAR_5_1 )
304         {
305             p_aout->output.output.i_physical_channels
306                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
307                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
308                    | AOUT_CHAN_LFE;
309         }
310         else if( val.i_int == AOUT_VAR_3F2R )
311         {
312             p_aout->output.output.i_physical_channels
313                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
314                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
315         }
316         else if( val.i_int == AOUT_VAR_2F2R )
317         {
318             p_aout->output.output.i_physical_channels
319                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
320                    | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
321         }
322         else if( val.i_int == AOUT_VAR_MONO )
323         {
324             p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
325         }
326         else
327         {
328             p_aout->output.output.i_physical_channels
329                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
330         }
331
332         if( CreateDSBufferPCM( p_aout, &p_aout->output.output.i_format,
333                                p_aout->output.output.i_physical_channels,
334                                aout_FormatNbChannels( &p_aout->output.output ),
335                                p_aout->output.output.i_rate, VLC_FALSE )
336             != VLC_SUCCESS )
337         {
338             msg_Err( p_aout, "cannot open directx audio device" );
339             free( p_aout->output.p_sys );
340             return VLC_EGENERIC;
341         }
342
343         /* Calculate the frame size in bytes */
344         p_aout->output.i_nb_samples = FRAME_SIZE;
345         aout_FormatPrepare( &p_aout->output.output );
346         p_aout->output.p_sys->i_frame_size =
347             FRAME_SIZE * p_aout->output.output.i_bytes_per_frame;
348
349         aout_VolumeSoftInit( p_aout );
350     }
351
352     /* then launch the notification thread */
353     msg_Dbg( p_aout, "creating DirectSoundThread" );
354     if( vlc_thread_create( p_aout->output.p_sys->p_notif,
355                            "DirectSound Notification Thread",
356                            DirectSoundThread,
357                            VLC_THREAD_PRIORITY_HIGHEST, VLC_FALSE ) )
358     {
359         msg_Err( p_aout, "cannot create DirectSoundThread" );
360         goto error;
361     }
362
363     vlc_object_attach( p_aout->output.p_sys->p_notif, p_aout );
364
365     return VLC_SUCCESS;
366
367  error:
368     CloseAudio( VLC_OBJECT(p_aout) );
369     return VLC_EGENERIC;
370 }
371
372 /*****************************************************************************
373  * Probe: probe the audio device for available formats and channels
374  *****************************************************************************/
375 static void Probe( aout_instance_t * p_aout )
376 {
377     vlc_value_t val, text;
378     int i_format;
379     unsigned int i_physical_channels;
380     DWORD ui_speaker_config;
381
382     var_Create( p_aout, "audio-device", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
383     text.psz_string = _("Audio device");
384     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
385
386     /* Test for 5.1 support */
387     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
388                           AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
389                           AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE;
390     if( p_aout->output.output.i_physical_channels == i_physical_channels )
391     {
392         if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 6,
393                                p_aout->output.output.i_rate, VLC_TRUE )
394             == VLC_SUCCESS )
395         {
396             val.i_int = AOUT_VAR_5_1;
397             text.psz_string = N_("5.1");
398             var_Change( p_aout, "audio-device",
399                         VLC_VAR_ADDCHOICE, &val, &text );
400             msg_Dbg( p_aout, "device supports 5.1 channels" );
401         }
402     }
403
404     /* Test for 3 Front 2 Rear support */
405     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
406                           AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
407                           AOUT_CHAN_REARRIGHT;
408     if( p_aout->output.output.i_physical_channels == i_physical_channels )
409     {
410         if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 5,
411                                p_aout->output.output.i_rate, VLC_TRUE )
412             == VLC_SUCCESS )
413         {
414             val.i_int = AOUT_VAR_3F2R;
415             text.psz_string = N_("3 Front 2 Rear");
416             var_Change( p_aout, "audio-device",
417                         VLC_VAR_ADDCHOICE, &val, &text );
418             msg_Dbg( p_aout, "device supports 5 channels" );
419         }
420     }
421
422     /* Test for 2 Front 2 Rear support */
423     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
424                           AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
425     if( ( p_aout->output.output.i_physical_channels & i_physical_channels )
426         == i_physical_channels )
427     {
428         if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 4,
429                                p_aout->output.output.i_rate, VLC_TRUE )
430             == VLC_SUCCESS )
431         {
432             val.i_int = AOUT_VAR_2F2R;
433             text.psz_string = N_("2 Front 2 Rear");
434             var_Change( p_aout, "audio-device",
435                         VLC_VAR_ADDCHOICE, &val, &text );
436             msg_Dbg( p_aout, "device supports 4 channels" );
437         }
438     }
439
440     /* Test for stereo support */
441     i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
442     if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 2,
443                            p_aout->output.output.i_rate, VLC_TRUE )
444         == VLC_SUCCESS )
445     {
446         val.i_int = AOUT_VAR_STEREO;
447         text.psz_string = N_("Stereo");
448         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
449         var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
450         msg_Dbg( p_aout, "device supports 2 channels" );
451     }
452
453     /* Test for mono support */
454     i_physical_channels = AOUT_CHAN_CENTER;
455     if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 1,
456                            p_aout->output.output.i_rate, VLC_TRUE )
457         == VLC_SUCCESS )
458     {
459         val.i_int = AOUT_VAR_MONO;
460         text.psz_string = N_("Mono");
461         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
462         msg_Dbg( p_aout, "device supports 1 channel" );
463     }
464
465     /* Check the speaker configuration to determine which channel config should
466      * be the default */
467     if FAILED( IDirectSound_GetSpeakerConfig( p_aout->output.p_sys->p_dsobject,
468                                               &ui_speaker_config ) )
469     {
470         ui_speaker_config = DSSPEAKER_STEREO;
471     }
472     switch( DSSPEAKER_CONFIG(ui_speaker_config) )
473     {
474     case DSSPEAKER_5POINT1:
475         val.i_int = AOUT_VAR_5_1;
476         break;
477     case DSSPEAKER_QUAD:
478         val.i_int = AOUT_VAR_2F2R;
479         break;
480     case DSSPEAKER_MONO:
481         val.i_int = AOUT_VAR_MONO;
482         break;
483     case DSSPEAKER_SURROUND:
484     case DSSPEAKER_STEREO:
485     default:
486         val.i_int = AOUT_VAR_STEREO;
487         break;
488     }
489     var_Set( p_aout, "audio-device", val );
490
491     /* Test for SPDIF support */
492     if ( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
493     {
494         if( CreateDSBuffer( p_aout, VLC_FOURCC('s','p','d','i'),
495                             p_aout->output.output.i_physical_channels,
496                             aout_FormatNbChannels( &p_aout->output.output ),
497                             p_aout->output.output.i_rate,
498                             AOUT_SPDIF_SIZE, VLC_TRUE )
499             == VLC_SUCCESS )
500         {
501             msg_Dbg( p_aout, "device supports A/52 over S/PDIF" );
502             val.i_int = AOUT_VAR_SPDIF;
503             text.psz_string = N_("A/52 over S/PDIF");
504             var_Change( p_aout, "audio-device",
505                         VLC_VAR_ADDCHOICE, &val, &text );
506             if( config_GetInt( p_aout, "spdif" ) )
507                 var_Set( p_aout, "audio-device", val );
508         }
509     }
510
511     var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
512     if( val.i_int <= 0 )
513     {
514         /* Probe() has failed. */
515         var_Destroy( p_aout, "audio-device" );
516         return;
517     }
518
519     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
520
521     val.b_bool = VLC_TRUE;
522     var_Set( p_aout, "intf-change", val );
523 }
524
525 /*****************************************************************************
526  * Play: we'll start playing the directsound buffer here because at least here
527  *       we know the first buffer has been put in the aout fifo and we also
528  *       know its date.
529  *****************************************************************************/
530 static void Play( aout_instance_t *p_aout )
531 {
532     if( !p_aout->output.p_sys->b_playing )
533     {
534         aout_buffer_t *p_buffer;
535
536         p_aout->output.p_sys->b_playing = 1;
537
538         /* get the playing date of the first aout buffer */
539         p_aout->output.p_sys->p_notif->start_date =
540             aout_FifoFirstDate( p_aout, &p_aout->output.fifo );
541
542         /* fill in the first samples */
543         p_buffer = aout_FifoPop( p_aout, &p_aout->output.fifo );
544         FillBuffer( p_aout, 0, p_buffer );
545
546         /* wake up the audio output thread */
547         SetEvent( p_aout->output.p_sys->p_notif->p_events[0].hEventNotify );
548     }
549 }
550
551 /*****************************************************************************
552  * CloseAudio: close the audio device
553  *****************************************************************************/
554 static void CloseAudio( vlc_object_t *p_this )
555 {
556     aout_instance_t * p_aout = (aout_instance_t *)p_this;
557
558     msg_Dbg( p_aout, "CloseAudio" );
559
560     /* kill the position notification thread, if any */
561     if( p_aout->output.p_sys->p_notif )
562     {
563         vlc_object_detach( p_aout->output.p_sys->p_notif );
564         if( p_aout->output.p_sys->p_notif->b_thread )
565         {
566             p_aout->output.p_sys->p_notif->b_die = 1;
567
568             if( !p_aout->output.p_sys->b_playing )
569                 /* wake up the audio thread */
570                 SetEvent(
571                     p_aout->output.p_sys->p_notif->p_events[0].hEventNotify );
572
573             vlc_thread_join( p_aout->output.p_sys->p_notif );
574         }
575         vlc_object_destroy( p_aout->output.p_sys->p_notif );
576     }
577
578     /* release the secondary buffer */
579     DestroyDSBuffer( p_aout );
580
581     /* finally release the DirectSound object */
582     if( p_aout->output.p_sys->p_dsobject )
583         IDirectSound_Release( p_aout->output.p_sys->p_dsobject );
584     
585     /* free DSOUND.DLL */
586     if( p_aout->output.p_sys->hdsound_dll )
587        FreeLibrary( p_aout->output.p_sys->hdsound_dll );
588
589     if( p_aout->output.p_sys->pi_chan_table )
590         free( p_aout->output.p_sys->pi_chan_table );
591
592     free( p_aout->output.p_sys );
593 }
594
595 /*****************************************************************************
596  * InitDirectSound: handle all the gory details of DirectSound initialisation
597  *****************************************************************************/
598 static int InitDirectSound( aout_instance_t *p_aout )
599 {
600     HRESULT (WINAPI *OurDirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
601
602     p_aout->output.p_sys->hdsound_dll = LoadLibrary("DSOUND.DLL");
603     if( p_aout->output.p_sys->hdsound_dll == NULL )
604     {
605         msg_Warn( p_aout, "cannot open DSOUND.DLL" );
606         goto error;
607     }
608
609     OurDirectSoundCreate = (void *)GetProcAddress(
610                                            p_aout->output.p_sys->hdsound_dll,
611                                            "DirectSoundCreate" );
612     if( OurDirectSoundCreate == NULL )
613     {
614         msg_Warn( p_aout, "GetProcAddress FAILED" );
615         goto error;
616     }
617
618     /* Create the direct sound object */
619     if FAILED( OurDirectSoundCreate( NULL, &p_aout->output.p_sys->p_dsobject,
620                                      NULL ) )
621     {
622         msg_Warn( p_aout, "cannot create a direct sound device" );
623         goto error;
624     }
625
626     /* Set DirectSound Cooperative level, ie what control we want over Windows
627      * sound device. In our case, DSSCL_EXCLUSIVE means that we can modify the
628      * settings of the primary buffer, but also that only the sound of our
629      * application will be hearable when it will have the focus.
630      * !!! (this is not really working as intended yet because to set the
631      * cooperative level you need the window handle of your application, and
632      * I don't know of any easy way to get it. Especially since we might play
633      * sound without any video, and so what window handle should we use ???
634      * The hack for now is to use the Desktop window handle - it seems to be
635      * working */
636     if( IDirectSound_SetCooperativeLevel( p_aout->output.p_sys->p_dsobject,
637                                           GetDesktopWindow(),
638                                           DSSCL_EXCLUSIVE) )
639     {
640         msg_Warn( p_aout, "cannot set direct sound cooperative level" );
641     }
642
643     return VLC_SUCCESS;
644
645  error:
646     p_aout->output.p_sys->p_dsobject = NULL;
647     if( p_aout->output.p_sys->hdsound_dll )
648     {
649         FreeLibrary( p_aout->output.p_sys->hdsound_dll );
650         p_aout->output.p_sys->hdsound_dll = NULL;
651     }
652     return VLC_EGENERIC;
653
654 }
655
656 /*****************************************************************************
657  * CreateDSBuffer: Creates a direct sound buffer of the required format.
658  *****************************************************************************
659  * This function creates the buffer we'll use to play audio.
660  * In DirectSound there are two kinds of buffers:
661  * - the primary buffer: which is the actual buffer that the soundcard plays
662  * - the secondary buffer(s): these buffers are the one actually used by
663  *    applications and DirectSound takes care of mixing them into the primary.
664  *
665  * Once you create a secondary buffer, you cannot change its format anymore so
666  * you have to release the current one and create another.
667  *****************************************************************************/
668 static int CreateDSBuffer( aout_instance_t *p_aout, int i_format,
669                            int i_channels, int i_nb_channels, int i_rate,
670                            int i_bytes_per_frame, vlc_bool_t b_probe )
671 {
672     WAVEFORMATEXTENSIBLE waveformat;
673     DSBUFFERDESC         dsbdesc;
674     unsigned int         i;
675
676     /* First set the sound buffer format */
677     waveformat.dwChannelMask = 0;
678     for( i = 0; i < sizeof(pi_channels_in)/sizeof(uint32_t); i++ )
679     {
680         if( i_channels & pi_channels_in[i] )
681             waveformat.dwChannelMask |= pi_channels_out[i];
682     }
683
684     switch( i_format )
685     {
686     case VLC_FOURCC('s','p','d','i'):
687         i_nb_channels = 2;
688         /* To prevent channel re-ordering */
689         waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
690         waveformat.Format.wBitsPerSample = 16;
691         waveformat.Samples.wValidBitsPerSample =
692             waveformat.Format.wBitsPerSample;
693         waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
694         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
695         break;
696
697     case VLC_FOURCC('f','l','3','2'):
698         waveformat.Format.wBitsPerSample = sizeof(float) * 8;
699         waveformat.Samples.wValidBitsPerSample =
700             waveformat.Format.wBitsPerSample;
701         waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
702         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
703         break;
704
705     case VLC_FOURCC('s','1','6','l'):
706         waveformat.Format.wBitsPerSample = 16;
707         waveformat.Samples.wValidBitsPerSample =
708             waveformat.Format.wBitsPerSample;
709         waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
710         waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_PCM;
711         break;
712     }
713
714     waveformat.Format.nChannels = i_nb_channels;
715     waveformat.Format.nSamplesPerSec = i_rate;
716     waveformat.Format.nBlockAlign =
717         waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
718     waveformat.Format.nAvgBytesPerSec =
719         waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;
720
721     /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
722     if( i_nb_channels <= 2 )
723     {
724         waveformat.Format.cbSize = 0;
725     }
726     else
727     {
728         waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
729         waveformat.Format.cbSize =
730             sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
731     }
732
733
734     /* Then fill in the direct sound descriptor */
735     memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
736     dsbdesc.dwSize = sizeof(DSBUFFERDESC);
737     dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2/* Better position accuracy */
738                     | DSBCAPS_CTRLPOSITIONNOTIFY     /* We need notification */
739                     | DSBCAPS_GLOBALFOCUS       /* Allows background playing */
740                     | DSBCAPS_LOCHARDWARE;      /* Needed for 5.1 on emu101k */
741     dsbdesc.dwBufferBytes = FRAMES_NUM * i_bytes_per_frame;   /* buffer size */
742     dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&waveformat;
743
744     if FAILED( IDirectSound_CreateSoundBuffer(
745                    p_aout->output.p_sys->p_dsobject, &dsbdesc,
746                    &p_aout->output.p_sys->p_dsbuffer, NULL) )
747     {
748         /* Try without DSBCAPS_LOCHARDWARE */
749         dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE;
750         if FAILED( IDirectSound_CreateSoundBuffer(
751                    p_aout->output.p_sys->p_dsobject, &dsbdesc,
752                    &p_aout->output.p_sys->p_dsbuffer, NULL) )
753         {
754             return VLC_EGENERIC;
755         }
756         if( !b_probe ) msg_Dbg( p_aout, "couldn't use hardware sound buffer" );
757     }
758
759     /* Stop here if we were just probing */
760     if( b_probe )
761     {
762         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
763         p_aout->output.p_sys->p_dsbuffer = NULL;
764         return VLC_SUCCESS;
765     }
766
767     /* Backup the size of a frame */
768     p_aout->output.p_sys->p_notif->i_frame_size = i_bytes_per_frame;
769
770     /* Now the secondary buffer is created, we need to setup its position
771      * notification */
772     for( i = 0; i < FRAMES_NUM; i++ )
773     {
774         p_aout->output.p_sys->p_notif->p_events[i].dwOffset = i *
775             p_aout->output.p_sys->p_notif->i_frame_size;
776
777         p_aout->output.p_sys->p_notif->i_frame_status[i] = FRAME_EMPTY;
778     }
779
780     /* Get the IDirectSoundNotify interface */
781     if FAILED( IDirectSoundBuffer_QueryInterface(
782                                 p_aout->output.p_sys->p_dsbuffer,
783                                 &IID_IDirectSoundNotify,
784                                 (LPVOID *)&p_aout->output.p_sys->p_dsnotify ) )
785     {
786         msg_Err( p_aout, "cannot get IDirectSoundNotify interface" );
787         goto error;
788     }
789
790     if FAILED( IDirectSoundNotify_SetNotificationPositions(
791                                     p_aout->output.p_sys->p_dsnotify,
792                                     FRAMES_NUM,
793                                     p_aout->output.p_sys->p_notif->p_events ) )
794     {
795         msg_Err( p_aout, "cannot set position notification" );
796         goto error;
797     }
798
799     p_aout->output.p_sys->i_channel_mask = waveformat.dwChannelMask;
800     CheckReordering( p_aout, i_nb_channels );
801
802     return VLC_SUCCESS;
803
804  error:
805     DestroyDSBuffer( p_aout );
806     return VLC_EGENERIC;
807 }
808
809 /*****************************************************************************
810  * CreateDSBufferPCM: creates a PCM direct sound buffer.
811  *****************************************************************************
812  * We first try to create a WAVE_FORMAT_IEEE_FLOAT buffer if supported by
813  * the hardware, otherwise we create a WAVE_FORMAT_PCM buffer.
814  ****************************************************************************/
815 static int CreateDSBufferPCM( aout_instance_t *p_aout, int *i_format,
816                               int i_channels, int i_nb_channels, int i_rate,
817                               vlc_bool_t b_probe )
818 {
819     /* Float32 audio samples are not supported for 5.1 output on the emu101k */
820
821     if( i_nb_channels > 2 ||
822         CreateDSBuffer( p_aout, VLC_FOURCC('f','l','3','2'),
823                         i_channels, i_nb_channels, i_rate,
824                         FRAME_SIZE * 4 * i_nb_channels, b_probe )
825         != VLC_SUCCESS )
826     {
827         if ( CreateDSBuffer( p_aout, VLC_FOURCC('s','1','6','l'),
828                              i_channels, i_nb_channels, i_rate,
829                              FRAME_SIZE * 2 * i_nb_channels, b_probe )
830              != VLC_SUCCESS )
831         {
832             return VLC_EGENERIC;
833         }
834         else
835         {
836             *i_format = VLC_FOURCC('s','1','6','l');
837             return VLC_SUCCESS;
838         }
839     }
840     else
841     {
842         *i_format = VLC_FOURCC('f','l','3','2');
843         return VLC_SUCCESS;
844     }
845 }
846
847 /*****************************************************************************
848  * DestroyDSBuffer
849  *****************************************************************************
850  * This function destroys the secondary buffer.
851  *****************************************************************************/
852 static void DestroyDSBuffer( aout_instance_t *p_aout )
853 {
854     if( p_aout->output.p_sys->p_dsnotify )
855     {
856         IDirectSoundNotify_Release( p_aout->output.p_sys->p_dsnotify );
857         p_aout->output.p_sys->p_dsnotify = NULL;
858     }
859
860     if( p_aout->output.p_sys->p_dsbuffer )
861     {
862         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
863         p_aout->output.p_sys->p_dsbuffer = NULL;
864     }
865 }
866
867 /*****************************************************************************
868  * FillBuffer: Fill in one of the direct sound frame buffers.
869  *****************************************************************************
870  * Returns VLC_SUCCESS on success.
871  *****************************************************************************/
872 static int FillBuffer( aout_instance_t *p_aout, int i_frame,
873                        aout_buffer_t *p_buffer )
874 {
875     notification_thread_t *p_notif = p_aout->output.p_sys->p_notif;
876     void *p_write_position, *p_wrap_around;
877     long l_bytes1, l_bytes2;
878     HRESULT dsresult;
879
880     /* Before copying anything, we have to lock the buffer */
881     dsresult = IDirectSoundBuffer_Lock(
882                 p_aout->output.p_sys->p_dsbuffer,               /* DS buffer */
883                 i_frame * p_notif->i_frame_size,             /* Start offset */
884                 p_notif->i_frame_size,                    /* Number of bytes */
885                 &p_write_position,                  /* Address of lock start */
886                 &l_bytes1,       /* Count of bytes locked before wrap around */
887                 &p_wrap_around,            /* Buffer adress (if wrap around) */
888                 &l_bytes2,               /* Count of bytes after wrap around */
889                 0 );                                                /* Flags */
890     if( dsresult == DSERR_BUFFERLOST )
891     {
892         IDirectSoundBuffer_Restore( p_aout->output.p_sys->p_dsbuffer );
893         dsresult = IDirectSoundBuffer_Lock(
894                                p_aout->output.p_sys->p_dsbuffer,
895                                i_frame * p_notif->i_frame_size,
896                                p_notif->i_frame_size,
897                                &p_write_position,
898                                &l_bytes1,
899                                &p_wrap_around,
900                                &l_bytes2,
901                                0 );
902     }
903     if( dsresult != DS_OK )
904     {
905         msg_Warn( p_notif, "cannot lock buffer" );
906         if( p_buffer ) aout_BufferFree( p_buffer );
907         return VLC_EGENERIC;
908     }
909
910     if( p_buffer == NULL )
911     {
912         memset( p_write_position, 0, l_bytes1 );
913     }
914     else if( p_aout->output.p_sys->b_chan_reorder )
915     {
916         /* Do the channel reordering here */
917
918         if( p_aout->output.output.i_format ==  VLC_FOURCC('s','1','6','l') )
919           InterleaveS16( (int16_t *)p_buffer->p_buffer,
920                          (int16_t *)p_write_position,
921                          p_aout->output.p_sys->pi_chan_table,
922                          aout_FormatNbChannels( &p_aout->output.output ) );
923         else
924           InterleaveFloat32( (float *)p_buffer->p_buffer,
925                              (float *)p_write_position,
926                              p_aout->output.p_sys->pi_chan_table,
927                              aout_FormatNbChannels( &p_aout->output.output ) );
928
929         aout_BufferFree( p_buffer );
930     }
931     else
932     {
933         p_aout->p_vlc->pf_memcpy( p_write_position, p_buffer->p_buffer,
934                                   l_bytes1 );
935         aout_BufferFree( p_buffer );
936     }
937
938     /* Now the data has been copied, unlock the buffer */
939     IDirectSoundBuffer_Unlock( p_aout->output.p_sys->p_dsbuffer,
940                                p_write_position, l_bytes1,
941                                p_wrap_around, l_bytes2 );
942
943     return VLC_SUCCESS;
944 }
945
946 /*****************************************************************************
947  * DirectSoundThread: this thread will capture play notification events. 
948  *****************************************************************************
949  * We use this thread to emulate a callback mechanism. The thread probes for
950  * event notification and fills up the DS secondary buffer when needed.
951  *****************************************************************************/
952 static void DirectSoundThread( notification_thread_t *p_notif )
953 {
954     HANDLE  notification_events[FRAMES_NUM];
955     HRESULT dsresult;
956     aout_instance_t *p_aout = p_notif->p_aout;
957     int i, i_which_frame, i_last_frame, i_next_frame;
958     mtime_t mtime;
959     vlc_bool_t b_sleek;
960
961     for( i = 0; i < FRAMES_NUM; i++ )
962         notification_events[i] = p_notif->p_events[i].hEventNotify;
963
964     /* We don't want any resampling when using S/PDIF output */
965     b_sleek = p_aout->output.output.i_format == VLC_FOURCC('s','p','d','i');
966
967     /* Tell the main thread that we are ready */
968     vlc_thread_ready( p_notif );
969
970     msg_Dbg( p_notif, "DirectSoundThread ready" );
971
972     /* Wait here until Play() is called */
973     WaitForSingleObject( notification_events[0], INFINITE );
974
975     if( !p_notif->b_die )
976     {
977         mwait( p_notif->start_date - AOUT_PTS_TOLERANCE / 2 );
978
979         /* start playing the buffer */
980         dsresult = IDirectSoundBuffer_Play( p_aout->output.p_sys->p_dsbuffer,
981                                         0,                         /* Unused */
982                                         0,                         /* Unused */
983                                         DSBPLAY_LOOPING );          /* Flags */
984         if( dsresult == DSERR_BUFFERLOST )
985         {
986             IDirectSoundBuffer_Restore( p_aout->output.p_sys->p_dsbuffer );
987             dsresult = IDirectSoundBuffer_Play(
988                                             p_aout->output.p_sys->p_dsbuffer,
989                                             0,                     /* Unused */
990                                             0,                     /* Unused */
991                                             DSBPLAY_LOOPING );      /* Flags */
992         }
993         if( dsresult != DS_OK )
994         {
995             msg_Err( p_aout, "cannot start playing buffer" );
996         }
997     }
998
999     while( !p_notif->b_die )
1000     {
1001         aout_buffer_t *p_buffer;
1002         long l_latency;
1003
1004         /* wait for the position notification */
1005         i_which_frame = WaitForMultipleObjects( FRAMES_NUM,
1006                                                 notification_events, 0,
1007                                                 INFINITE ) - WAIT_OBJECT_0;
1008
1009         if( p_notif->b_die )
1010             break;
1011
1012         mtime = mdate();
1013
1014         /* We take into account the current latency */
1015         if SUCCEEDED( IDirectSoundBuffer_GetCurrentPosition(
1016                         p_aout->output.p_sys->p_dsbuffer,
1017                         &l_latency, NULL ) )
1018         {
1019             if( l_latency > (i_which_frame * FRAME_SIZE)
1020                   && l_latency < ((i_which_frame+1) * FRAME_SIZE) )
1021             {
1022                 l_latency = - ( l_latency /
1023                                 p_aout->output.output.i_bytes_per_frame %
1024                                 FRAME_SIZE );
1025             }
1026             else
1027             {
1028                 l_latency = FRAME_SIZE - ( l_latency /
1029                                       p_aout->output.output.i_bytes_per_frame %
1030                                       FRAME_SIZE );
1031             }
1032         }
1033         else
1034         {
1035             l_latency = 0;
1036         }
1037
1038         /* Mark last frame as empty */
1039         i_last_frame = (i_which_frame + FRAMES_NUM -1) % FRAMES_NUM;
1040         i_next_frame = (i_which_frame + 1) % FRAMES_NUM;
1041         p_notif->i_frame_status[i_last_frame] = FRAME_EMPTY;
1042
1043         /* Try to fill in as many frame buffers as possible */
1044         for( i = i_next_frame; (i % FRAMES_NUM) != i_which_frame; i++ )
1045         {
1046
1047             /* Check if frame buf is already filled */
1048             if( p_notif->i_frame_status[i % FRAMES_NUM] == FRAME_QUEUED )
1049                 continue;
1050
1051             p_buffer = aout_OutputNextBuffer( p_aout,
1052                 mtime + 1000000 / p_aout->output.output.i_rate *
1053                 ((i - i_next_frame + 1) * FRAME_SIZE + l_latency), b_sleek );
1054
1055             /* If there is no audio data available and we have some buffered
1056              * already, then just wait for the next time */
1057             if( !p_buffer && (i != i_next_frame) )
1058             {
1059                 //msg_Err( p_aout, "only %i frame buffers filled!",
1060                 //         i - i_next_frame );
1061                 break;
1062             }
1063
1064             if( FillBuffer( p_aout, (i%FRAMES_NUM), p_buffer )
1065                 != VLC_SUCCESS )
1066                 break;
1067
1068             /* Mark the frame buffer as QUEUED */
1069             p_notif->i_frame_status[i%FRAMES_NUM] = FRAME_QUEUED;
1070         }
1071
1072     }
1073
1074     /* make sure the buffer isn't playing */
1075     IDirectSoundBuffer_Stop( p_aout->output.p_sys->p_dsbuffer );
1076
1077     /* free the events */
1078     for( i = 0; i < FRAMES_NUM; i++ )
1079         CloseHandle( notification_events[i] );
1080
1081     msg_Dbg( p_notif, "DirectSoundThread exiting" );
1082 }
1083
1084 /*****************************************************************************
1085  * CheckReordering: Check if we need to do some channel re-ordering (the ac3
1086  *                  channel order is different from the one chosen by
1087  *                  Microsoft).
1088  *****************************************************************************/
1089 static void CheckReordering( aout_instance_t *p_aout, int i_nb_channels )
1090 {
1091     int i, j, k, l;
1092
1093 #define i_channel_mask p_aout->output.p_sys->i_channel_mask
1094 #define pi_chan_table p_aout->output.p_sys->pi_chan_table
1095
1096     p_aout->output.p_sys->b_chan_reorder = VLC_FALSE;
1097
1098     pi_chan_table = malloc( i_nb_channels * sizeof(int) );
1099     if( !pi_chan_table )
1100     {
1101         return;
1102     }
1103
1104     for( i = 0, j = 0;
1105          i < (int)(sizeof(pi_channels_out)/sizeof(uint32_t)); i++ )
1106     {
1107         if( i_channel_mask & pi_channels_out[i] )
1108         {
1109             for( k = 0, l = 0;
1110                  pi_channels_out[i] != pi_channels_ordered[k]; k++ )
1111             {
1112                 if( i_channel_mask & pi_channels_ordered[k] )
1113                 {
1114                     l++;
1115                 }
1116             }
1117
1118             pi_chan_table[j] = l;
1119
1120             j++;
1121         }
1122     }
1123
1124     for( i = 0; i < i_nb_channels; i++ )
1125     {
1126         if( pi_chan_table[i] != i )
1127         {
1128             p_aout->output.p_sys->b_chan_reorder = VLC_TRUE;
1129         }
1130     }
1131
1132     if( p_aout->output.p_sys->b_chan_reorder )
1133     {
1134         msg_Dbg( p_aout, "channel reordering needed" );
1135     }
1136
1137 #undef pi_chan_table
1138 #undef waveformat
1139 }
1140
1141 /*****************************************************************************
1142  * InterleaveFloat32/S16: change the channel order to the Microsoft one.
1143  *****************************************************************************/
1144 static void InterleaveFloat32( float *p_buf, float *p_buf_out,
1145                                int *pi_chan_table, int i_nb_channels )
1146 {
1147     int i, j;
1148
1149     for( i = 0; i < FRAME_SIZE; i++ )
1150     {
1151         for( j = 0; j < i_nb_channels; j++ )
1152         {
1153             p_buf_out[i*i_nb_channels + pi_chan_table[j]] =
1154                 p_buf[i*i_nb_channels + j];
1155         }
1156     }
1157 }
1158
1159 static void InterleaveS16( int16_t *p_buf, int16_t *p_buf_out,
1160                            int *pi_chan_table, int i_nb_channels )
1161 {
1162     int i, j;
1163
1164     for( i = 0; i < FRAME_SIZE; i++ )
1165     {
1166         for( j = 0; j < i_nb_channels; j++ )
1167         {
1168             p_buf_out[ i*i_nb_channels + pi_chan_table[j]] =
1169                 p_buf[i*i_nb_channels + j];
1170         }
1171     }
1172 }