directx.c 45.2 KB
Newer Older
1
/*****************************************************************************
2
 * directx.c: Windows DirectX audio output method
3
 *****************************************************************************
4
 * Copyright (C) 2001-2009 the VideoLAN team
5
 * $Id$
6
 *
7
 * Authors: Gildas Bazin <gbazin@videolan.org>
8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
20 21
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 23 24 25 26 27
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/

28 29 30 31
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

32 33
#include <math.h>

34
#include <vlc_common.h>
35
#include <vlc_plugin.h>
Clément Stenac's avatar
Clément Stenac committed
36
#include <vlc_aout.h>
37
#include <vlc_charset.h>
38
#include <vlc_atomic.h>
39

40 41
#include "windows_audio_common.h"

42
#define FRAME_SIZE ((int)p_aout->format.i_rate/20) /* Size in samples */
43

44 45 46 47 48
/*****************************************************************************
 * notification_thread_t: DirectX event thread
 *****************************************************************************/
typedef struct notification_thread_t
{
49 50
    int i_frame_size;                          /* size in bytes of one frame */
    int i_write_slot;       /* current write position in our circular buffer */
51 52

    mtime_t start_date;
53
    HANDLE event;
54

55 56 57
    vlc_thread_t thread;
    vlc_atomic_t abort;

58 59 60 61 62 63 64 65 66 67
} notification_thread_t;

/*****************************************************************************
 * aout_sys_t: directx audio output method descriptor
 *****************************************************************************
 * This structure is part of the audio output thread descriptor.
 * It describes the direct sound specific properties of an audio device.
 *****************************************************************************/
struct aout_sys_t
{
68
    aout_packet_t       packet;
69
    HINSTANCE           hdsound_dll;      /* handle of the opened dsound dll */
70

71
    char *              psz_device;              /* user defined device name */
72 73
    LPGUID              p_device_guid;

74 75 76 77
    LPDIRECTSOUND       p_dsobject;              /* main Direct Sound object */
    LPDIRECTSOUNDBUFFER p_dsbuffer;   /* the sound buffer we use (direct sound
                                       * takes care of mixing all the
                                       * secondary buffers into the primary) */
78 79 80 81 82 83
    struct
    {
        LONG             volume;
        LONG             mb;
        bool             mute;
    } volume;
84

85
    notification_thread_t notif;                  /* DirectSoundThread id */
86

87
    int      i_frame_size;                     /* Size in bytes of one frame */
88

89
    int      i_speaker_setup;                      /* Speaker setup override */
90

91 92
    bool     b_chan_reorder;                /* do we need channel reordering */
    int      pi_chan_table[AOUT_CHAN_MAX];
93
    uint32_t i_channel_mask;
94 95
    uint32_t i_bits_per_sample;
    uint32_t i_channels;
96 97 98 99 100
};

/*****************************************************************************
 * Local prototypes.
 *****************************************************************************/
101 102
static int  OpenAudio  ( vlc_object_t * );
static void CloseAudio ( vlc_object_t * );
103
static void Play       ( audio_output_t *, block_t *, mtime_t * );
104 105
static int  VolumeSet  ( audio_output_t *, float );
static int  MuteSet    ( audio_output_t *, bool );
106 107

/* local functions */
108 109 110 111 112
static void Probe             ( audio_output_t * );
static int  InitDirectSound   ( audio_output_t * );
static int  CreateDSBuffer    ( audio_output_t *, int, int, int, int, int, bool );
static int  CreateDSBufferPCM ( audio_output_t *, vlc_fourcc_t*, int, int, int, bool );
static void DestroyDSBuffer   ( audio_output_t * );
113
static void* DirectSoundThread( void * );
114
static int  FillBuffer        ( audio_output_t *, int, block_t * );
115

116 117 118
static int ReloadDirectXDevices( vlc_object_t *, char const *,
                                vlc_value_t, vlc_value_t, void * );

119 120 121
/* Speaker setup override options list */
static const char *const speaker_list[] = { "Windows default", "Mono", "Stereo",
                                            "Quad", "5.1", "7.1" };
122 123
static const char *const ppsz_adev[] = {"default",  };
static const char *const ppsz_adev_text[] = {"default", };
124

125 126 127
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
128
#define DEVICE_TEXT N_("Output device")
129
#define DEVICE_LONGTEXT N_("Select your audio output device")
130

131
#define SPEAKER_TEXT N_("Speaker configuration")
132 133
#define SPEAKER_LONGTEXT N_("Select speaker configuration you want to use. " \
    "This option doesn't upmix! So NO e.g. Stereo -> 5.1 conversion." )
134

135 136 137 138 139 140
vlc_module_begin ()
    set_description( N_("DirectX audio output") )
    set_shortname( "DirectX" )
    set_capability( "audio output", 100 )
    set_category( CAT_AUDIO )
    set_subcategory( SUBCAT_AUDIO_AOUT )
141
    add_shortcut( "directx", "aout_directx" )
142

143
    add_string( "directx-audio-device", "default",
144
             DEVICE_TEXT, DEVICE_LONGTEXT, false )
145 146
        change_string_list( ppsz_adev, ppsz_adev_text, ReloadDirectXDevices )
        change_action_add( ReloadDirectXDevices, N_("Refresh list") )
147
    add_obsolete_string( "directx-audio-device-name")
148
    add_bool( "directx-audio-float32", false, FLOAT_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
149
              FLOAT_LONGTEXT, true )
150
    add_string( "directx-audio-speaker", "Windows default",
151 152
                 SPEAKER_TEXT, SPEAKER_LONGTEXT, true )
        change_string_list( speaker_list, 0, 0 )
153

154 155
    set_callbacks( OpenAudio, CloseAudio )
vlc_module_end ()
156

157 158 159 160 161
/*****************************************************************************
 * OpenAudio: open the audio device
 *****************************************************************************
 * This function opens and setups Direct Sound.
 *****************************************************************************/
162
static int OpenAudio( vlc_object_t *p_this )
163
{
164
    audio_output_t * p_aout = (audio_output_t *)p_this;
165
    vlc_value_t val;
166 167 168 169
    char * psz_speaker;
    int i = 0;

    const char * const * ppsz_compare = speaker_list;
170

Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
171
    msg_Dbg( p_aout, "Opening DirectSound Audio Output" );
172 173

   /* Allocate structure */
174 175
    p_aout->sys = calloc( 1, sizeof( aout_sys_t ) );
    if( unlikely( p_aout->sys == NULL ) )
176
        return VLC_ENOMEM;
177

178 179 180
    /* Retrieve config values */
    var_Create( p_aout, "directx-audio-float32",
                VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
181
    psz_speaker = var_CreateGetString( p_aout, "directx-audio-speaker" );
182 183 184 185 186 187 188 189 190 191 192 193

    while ( *ppsz_compare != NULL )
    {
        if ( !strncmp( *ppsz_compare, psz_speaker, strlen(*ppsz_compare) ) )
        {
            break;
        }
        ppsz_compare++; i++;
    }

    if ( *ppsz_compare == NULL )
    {
194
        msg_Err( p_aout, "(%s) isn't valid speaker setup option", psz_speaker );
195 196 197
        msg_Err( p_aout, "Defaulting to Windows default speaker config");
        i = 0;
    }
198
    free( psz_speaker );
199
    p_aout->sys->i_speaker_setup = i;
200

201
    /* Initialise DirectSound */
202
    if( InitDirectSound( p_aout ) )
203
    {
204 205
        msg_Err( p_aout, "cannot initialize DirectSound" );
        goto error;
206 207
    }

208 209 210 211 212 213 214
    if( var_Type( p_aout, "audio-device" ) == 0 )
    {
        Probe( p_aout );
    }

    if( var_Get( p_aout, "audio-device", &val ) < 0 )
    {
215
        msg_Err( p_aout, "DirectSound Probe failed()" );
216
        goto error;
217 218 219
    }

    /* Open the device */
220
    if( val.i_int == AOUT_VAR_SPDIF )
221
    {
222
        p_aout->format.i_format = VLC_CODEC_SPDIFL;
223 224

        /* Calculate the frame size in bytes */
225 226 227
        p_aout->format.i_bytes_per_frame = AOUT_SPDIF_SIZE;
        p_aout->format.i_frame_length = A52_FRAME_NB;
        p_aout->sys->i_frame_size = p_aout->format.i_bytes_per_frame;
228

229
        if( CreateDSBuffer( p_aout, VLC_CODEC_SPDIFL,
230 231 232 233
                            p_aout->format.i_physical_channels,
                            aout_FormatNbChannels( &p_aout->format ),
                            p_aout->format.i_rate,
                            p_aout->sys->i_frame_size, false )
234 235
            != VLC_SUCCESS )
        {
236
            msg_Err( p_aout, "cannot open directx audio device" );
237
            goto error;
238 239
        }

240
        aout_PacketInit( p_aout, &p_aout->sys->packet, A52_FRAME_NB );
241 242 243
    }
    else
    {
244
        if( val.i_int == AOUT_VAR_5_1 )
245
        {
246
            p_aout->format.i_physical_channels
247 248 249 250
                = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
                   | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
                   | AOUT_CHAN_LFE;
        }
251 252
        else if( val.i_int == AOUT_VAR_7_1 )
        {
253
                    p_aout->format.i_physical_channels
254 255 256 257 258
                        = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
                           | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
                           | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
                           | AOUT_CHAN_LFE;
        }
259 260
        else if( val.i_int == AOUT_VAR_3F2R )
        {
261
            p_aout->format.i_physical_channels
262 263 264
                = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
                   | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
        }
265
        else if( val.i_int == AOUT_VAR_2F2R )
266
        {
267
            p_aout->format.i_physical_channels
268 269 270
                = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
                   | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
        }
271
        else if( val.i_int == AOUT_VAR_MONO )
272
        {
273
            p_aout->format.i_physical_channels = AOUT_CHAN_CENTER;
274 275 276
        }
        else
        {
277
            p_aout->format.i_physical_channels
278 279
                = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
        }
280

281 282 283 284
        if( CreateDSBufferPCM( p_aout, &p_aout->format.i_format,
                               p_aout->format.i_physical_channels,
                               aout_FormatNbChannels( &p_aout->format ),
                               p_aout->format.i_rate, false )
285
            != VLC_SUCCESS )
286
        {
287
            msg_Err( p_aout, "cannot open directx audio device" );
288
            goto error;
289
        }
290 291

        /* Calculate the frame size in bytes */
292
        aout_FormatPrepare( &p_aout->format );
293
        aout_PacketInit( p_aout, &p_aout->sys->packet, FRAME_SIZE );
294
    }
295

296 297
    p_aout->sys->volume.volume = -1;

298
    /* Now we need to setup our DirectSound play notification structure */
299 300 301 302 303
    vlc_atomic_set(&p_aout->sys->notif.abort, 0);
    p_aout->sys->notif.event = CreateEvent( 0, FALSE, FALSE, 0 );
    if( unlikely(p_aout->sys->notif.event == NULL) )
        abort();
    p_aout->sys->notif.i_frame_size =  p_aout->sys->i_frame_size;
304

Christophe Massiot's avatar
Christophe Massiot committed
305 306
    /* then launch the notification thread */
    msg_Dbg( p_aout, "creating DirectSoundThread" );
307
    if( vlc_clone( &p_aout->sys->notif.thread, DirectSoundThread, p_aout,
308
                   VLC_THREAD_PRIORITY_HIGHEST ) )
Christophe Massiot's avatar
Christophe Massiot committed
309 310
    {
        msg_Err( p_aout, "cannot create DirectSoundThread" );
311 312
        CloseHandle( p_aout->sys->notif.event );
        p_aout->sys->notif.event = NULL;
313 314
        aout_PacketDestroy( p_aout );
        goto error;
Christophe Massiot's avatar
Christophe Massiot committed
315 316
    }

317 318 319 320
    p_aout->pf_play = Play;
    p_aout->pf_pause = aout_PacketPause;
    p_aout->pf_flush = aout_PacketFlush;

321 322 323 324 325 326 327 328 329 330 331 332 333
    /* Volume */
    if( val.i_int == AOUT_VAR_SPDIF )
    {
        p_aout->volume_set = NULL;
        p_aout->mute_set = NULL;
    }
    else
    {
        p_aout->sys->volume.mb = 0;
        p_aout->sys->volume.mute = false;
        p_aout->volume_set = VolumeSet;
        p_aout->mute_set = MuteSet;
    }
334
    return VLC_SUCCESS;
Christophe Massiot's avatar
Christophe Massiot committed
335 336

 error:
337
    CloseAudio( VLC_OBJECT(p_aout) );
338
    return VLC_EGENERIC;
339 340
}

341 342 343
/*****************************************************************************
 * Probe: probe the audio device for available formats and channels
 *****************************************************************************/
344
static void Probe( audio_output_t * p_aout )
345
{
346
    vlc_value_t val, text;
347
    vlc_fourcc_t i_format;
348 349
    unsigned int i_physical_channels;
    DWORD ui_speaker_config;
350
    bool is_default_output_set = false;
351

352
    var_Create( p_aout, "audio-device", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
353
    text.psz_string = _("Audio Device");
354
    var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
355 356 357 358 359

    /* Test for 5.1 support */
    i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
                          AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
                          AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE;
360
    if( p_aout->format.i_physical_channels == i_physical_channels )
361 362
    {
        if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 6,
363
                               p_aout->format.i_rate, true )
364 365
            == VLC_SUCCESS )
        {
366
            val.i_int = AOUT_VAR_5_1;
367
            text.psz_string = (char*) "5.1";
368 369
            var_Change( p_aout, "audio-device",
                        VLC_VAR_ADDCHOICE, &val, &text );
370 371
            var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
            is_default_output_set = true;
372 373 374 375
            msg_Dbg( p_aout, "device supports 5.1 channels" );
        }
    }

376 377 378 379 380
    /* Test for 7.1 support */
    i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
                             AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
                             AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT |
                             AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE;
381
    if( p_aout->format.i_physical_channels == i_physical_channels )
Rémi Duraffort's avatar
Rémi Duraffort committed
382 383
    {
        if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 8,
384
                                  p_aout->format.i_rate, true )
Rémi Duraffort's avatar
Rémi Duraffort committed
385 386 387 388 389 390 391 392 393 394 395
            == VLC_SUCCESS )
        {
            val.i_int = AOUT_VAR_7_1;
            text.psz_string = (char*) "7.1";
            var_Change( p_aout, "audio-device",
                        VLC_VAR_ADDCHOICE, &val, &text );
            var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
            is_default_output_set = true;
            msg_Dbg( p_aout, "device supports 7.1 channels" );
        }
    }
396

397 398 399 400
    /* Test for 3 Front 2 Rear support */
    i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
                          AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT |
                          AOUT_CHAN_REARRIGHT;
401
    if( p_aout->format.i_physical_channels == i_physical_channels )
402 403
    {
        if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 5,
404
                               p_aout->format.i_rate, true )
405 406 407
            == VLC_SUCCESS )
        {
            val.i_int = AOUT_VAR_3F2R;
408
            text.psz_string = _("3 Front 2 Rear");
409 410
            var_Change( p_aout, "audio-device",
                        VLC_VAR_ADDCHOICE, &val, &text );
411 412 413 414 415
            if(!is_default_output_set)
            {
                var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
                is_default_output_set = true;
            }
416 417 418 419
            msg_Dbg( p_aout, "device supports 5 channels" );
        }
    }

420 421 422
    /* Test for 2 Front 2 Rear support */
    i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
                          AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
423
    if( ( p_aout->format.i_physical_channels & i_physical_channels )
424 425 426
        == i_physical_channels )
    {
        if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 4,
427
                               p_aout->format.i_rate, true )
428 429
            == VLC_SUCCESS )
        {
430
            val.i_int = AOUT_VAR_2F2R;
431
            text.psz_string = _("2 Front 2 Rear");
432 433
            var_Change( p_aout, "audio-device",
                        VLC_VAR_ADDCHOICE, &val, &text );
434 435 436 437 438
            if(!is_default_output_set)
            {
                var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
                is_default_output_set = true;
            }
439 440 441 442 443 444 445
            msg_Dbg( p_aout, "device supports 4 channels" );
        }
    }

    /* Test for stereo support */
    i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
    if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 2,
446
                           p_aout->format.i_rate, true )
447 448
        == VLC_SUCCESS )
    {
449
        val.i_int = AOUT_VAR_STEREO;
450
        text.psz_string = _("Stereo");
451
        var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
452 453 454 455 456 457
        if(!is_default_output_set)
        {
            var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
            is_default_output_set = true;
            msg_Dbg( p_aout, "device supports 2 channels (DEFAULT!)" );
        }
458
        else msg_Dbg( p_aout, "device supports 2 channels" );
459 460 461 462 463
    }

    /* Test for mono support */
    i_physical_channels = AOUT_CHAN_CENTER;
    if( CreateDSBufferPCM( p_aout, &i_format, i_physical_channels, 1,
464
                           p_aout->format.i_rate, true )
465 466
        == VLC_SUCCESS )
    {
467
        val.i_int = AOUT_VAR_MONO;
468
        text.psz_string = _("Mono");
469
        var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
470 471 472 473 474
        msg_Dbg( p_aout, "device supports 1 channel" );
    }

    /* Check the speaker configuration to determine which channel config should
     * be the default */
475
    if FAILED( IDirectSound_GetSpeakerConfig( p_aout->sys->p_dsobject,
476 477 478
                                              &ui_speaker_config ) )
    {
        ui_speaker_config = DSSPEAKER_STEREO;
479
        msg_Dbg( p_aout, "GetSpeakerConfig failed" );
480 481 482
    }
    switch( DSSPEAKER_CONFIG(ui_speaker_config) )
    {
483
    case DSSPEAKER_7POINT1:
484
        msg_Dbg( p_aout, "Windows says your SpeakerConfig is 7.1" );
485 486
        val.i_int = AOUT_VAR_7_1;
        break;
487
    case DSSPEAKER_5POINT1:
488
        msg_Dbg( p_aout, "Windows says your SpeakerConfig is 5.1" );
489
        val.i_int = AOUT_VAR_5_1;
490 491
        break;
    case DSSPEAKER_QUAD:
492
        msg_Dbg( p_aout, "Windows says your SpeakerConfig is Quad" );
493
        val.i_int = AOUT_VAR_2F2R;
494
        break;
495 496
#if 0 /* Lots of people just get their settings wrong and complain that
       * this is a problem with VLC so just don't ever set mono by default. */
497
    case DSSPEAKER_MONO:
498
        val.i_int = AOUT_VAR_MONO;
499
        break;
500
#endif
501
    case DSSPEAKER_SURROUND:
502
        msg_Dbg( p_aout, "Windows says your SpeakerConfig is surround" );
503
    case DSSPEAKER_STEREO:
504
        msg_Dbg( p_aout, "Windows says your SpeakerConfig is stereo" );
505
    default:
506
        /* If nothing else is found, choose stereo output */
507
        val.i_int = AOUT_VAR_STEREO;
508 509
        break;
    }
510 511

    /* Check if we want to override speaker config */
512
    switch( p_aout->sys->i_speaker_setup )
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    {
    case 0: /* Default value aka Windows default speaker setup */
        break;
    case 1: /* Mono */
        msg_Dbg( p_aout, "SpeakerConfig is forced to Mono" );
        val.i_int = AOUT_VAR_MONO;
        break;
    case 2: /* Stereo */
        msg_Dbg( p_aout, "SpeakerConfig is forced to Stereo" );
        val.i_int = AOUT_VAR_STEREO;
        break;
    case 3: /* Quad */
        msg_Dbg( p_aout, "SpeakerConfig is forced to Quad" );
        val.i_int = AOUT_VAR_2F2R;
        break;
    case 4: /* 5.1 */
        msg_Dbg( p_aout, "SpeakerConfig is forced to 5.1" );
        val.i_int = AOUT_VAR_5_1;
        break;
    case 5: /* 7.1 */
        msg_Dbg( p_aout, "SpeakerConfig is forced to 7.1" );
        val.i_int = AOUT_VAR_7_1;
        break;
    default:
        msg_Dbg( p_aout, "SpeakerConfig is forced to non-existing value" );
        break;
    }

541 542
    var_Set( p_aout, "audio-device", val );

543
    /* Test for SPDIF support */
544
    if ( AOUT_FMT_SPDIF( &p_aout->format ) )
545
    {
546
        if( CreateDSBuffer( p_aout, VLC_CODEC_SPDIFL,
547 548 549
                            p_aout->format.i_physical_channels,
                            aout_FormatNbChannels( &p_aout->format ),
                            p_aout->format.i_rate,
550
                            AOUT_SPDIF_SIZE, true )
551 552 553
            == VLC_SUCCESS )
        {
            msg_Dbg( p_aout, "device supports A/52 over S/PDIF" );
554
            val.i_int = AOUT_VAR_SPDIF;
555
            text.psz_string = _("A/52 over S/PDIF");
556 557
            var_Change( p_aout, "audio-device",
                        VLC_VAR_ADDCHOICE, &val, &text );
558
            if( var_InheritBool( p_aout, "spdif" ) )
559 560 561 562
                var_Set( p_aout, "audio-device", val );
        }
    }

563 564 565 566 567 568 569 570
    var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
    if( val.i_int <= 0 )
    {
        /* Probe() has failed. */
        var_Destroy( p_aout, "audio-device" );
        return;
    }

571 572 573
    var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
}

574
/*****************************************************************************
575 576 577
 * Play: we'll start playing the directsound buffer here because at least here
 *       we know the first buffer has been put in the aout fifo and we also
 *       know its date.
578
 *****************************************************************************/
579 580
static void Play( audio_output_t *p_aout, block_t *p_buffer,
                  mtime_t *restrict drift )
581
{
582
    /* get the playing date of the first aout buffer */
583
    p_aout->sys->notif.start_date = p_buffer->i_pts;
584

585 586
    /* fill in the first samples (zeroes) */
    FillBuffer( p_aout, 0, NULL );
587

588
    /* wake up the audio output thread */
589
    SetEvent( p_aout->sys->notif.event );
590

591
    aout_PacketPlay( p_aout, p_buffer, drift );
592
    p_aout->pf_play = aout_PacketPlay;
593 594
}

595
static int VolumeSet( audio_output_t *p_aout, float vol )
596 597
{
    aout_sys_t *sys = p_aout->sys;
598
    int ret = 0;
599

600 601
    /* Convert UI volume to linear factor (cube) */
    vol = vol * vol * vol;
602 603

    /* millibels from linear amplification */
604 605 606 607 608
    LONG mb = lroundf(2000.f * log10f(vol));

    /* Clamp to allowed DirectSound range */
    static_assert( DSBVOLUME_MIN < DSBVOLUME_MAX, "DSBVOLUME_* confused" );
    if( mb >= DSBVOLUME_MAX )
609
    {
610
        mb = DSBVOLUME_MAX;
611 612
        ret = -1;
    }
613 614 615
    if( mb <= DSBVOLUME_MIN )
        mb = DSBVOLUME_MIN;

616 617 618
    sys->volume.mb = mb;
    if (!sys->volume.mute)
        InterlockedExchange(&sys->volume.volume, mb);
619

620 621
    /* Convert back to UI volume */
    vol = cbrtf(powf(10.f, ((float)mb) / -2000.f));
622 623 624 625 626 627 628 629 630 631 632 633 634
    aout_VolumeReport( p_aout, vol );
    return ret;
}

static int MuteSet( audio_output_t *p_aout, bool mute )
{
    aout_sys_t *sys = p_aout->sys;

    sys->volume.mute = mute;
    InterlockedExchange(&sys->volume.volume,
                        mute ? DSBVOLUME_MIN : sys->volume.mb);

    aout_MuteReport( p_aout, mute );
635 636 637
    return 0;
}

638 639 640
/*****************************************************************************
 * CloseAudio: close the audio device
 *****************************************************************************/
641
static void CloseAudio( vlc_object_t *p_this )
642
{
643
    audio_output_t * p_aout = (audio_output_t *)p_this;
644
    aout_sys_t *p_sys = p_aout->sys;
645

646
    msg_Dbg( p_aout, "closing audio device" );
647 648

    /* kill the position notification thread, if any */
649
    if( p_sys->notif.event != NULL )
650
    {
651
        vlc_atomic_set(&p_aout->sys->notif.abort, 1);
652
        /* wake up the audio thread if needed */
653
        if( p_aout->pf_play == Play )
654
            SetEvent( p_sys->notif.event );
655

656 657
        vlc_join( p_sys->notif.thread, NULL );
        CloseHandle( p_sys->notif.event );
658
        aout_PacketDestroy( p_aout );
659 660 661
    }

    /* release the secondary buffer */
662
    DestroyDSBuffer( p_aout );
663 664

    /* finally release the DirectSound object */
665
    if( p_sys->p_dsobject ) IDirectSound_Release( p_sys->p_dsobject );
666

667
    /* free DSOUND.DLL */
668
    if( p_sys->hdsound_dll ) FreeLibrary( p_sys->hdsound_dll );
669

670
    free( p_aout->sys->p_device_guid );
671
    free( p_sys );
672 673
}

674 675 676
/*****************************************************************************
 * CallBackDirectSoundEnum: callback to enumerate available devices
 *****************************************************************************/
677 678
static int CALLBACK CallBackDirectSoundEnum( LPGUID p_guid, LPCWSTR psz_desc,
                                             LPCWSTR psz_mod, LPVOID _p_aout )
679
{
680 681
    VLC_UNUSED( psz_mod );

682
    audio_output_t *p_aout = (audio_output_t *)_p_aout;
683

684 685
    char *psz_device = FromWide( psz_desc );
    msg_Dbg( p_aout, "found device: %s", psz_device );
686

687 688
    if( p_aout->sys->psz_device &&
        !strcmp(p_aout->sys->psz_device, psz_device) && p_guid )
689
    {
690
        /* Use the device corresponding to psz_device */
691 692
        p_aout->sys->p_device_guid = malloc( sizeof( GUID ) );
        *p_aout->sys->p_device_guid = *p_guid;
693
        msg_Dbg( p_aout, "using device: %s", psz_device );
694
    }
695 696 697
    else
    {
        /* If no default device has been selected, chose the first one */
698
        if( !p_aout->sys->psz_device && p_guid )
699
        {
700 701 702
            p_aout->sys->psz_device = strdup( psz_device );
            p_aout->sys->p_device_guid = malloc( sizeof( GUID ) );
            *p_aout->sys->p_device_guid = *p_guid;
703
            msg_Dbg( p_aout, "using device: %s", psz_device );
704 705
        }
    }
706 707

    free( psz_device );
708
    return true;
709 710
}

711
/*****************************************************************************
712
 * InitDirectSound: handle all the gory details of DirectSound initialisation
713
 *****************************************************************************/
714
static int InitDirectSound( audio_output_t *p_aout )
715 716
{
    HRESULT (WINAPI *OurDirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
717
    HRESULT (WINAPI *OurDirectSoundEnumerate)(LPDSENUMCALLBACKW, LPVOID);
718

719 720
    p_aout->sys->hdsound_dll = LoadLibrary("DSOUND.DLL");
    if( p_aout->sys->hdsound_dll == NULL )
721
    {
722 723
        msg_Warn( p_aout, "cannot open DSOUND.DLL" );
        goto error;
724 725
    }

726
    OurDirectSoundCreate = (void *)
727
        GetProcAddress( p_aout->sys->hdsound_dll,
728
                        "DirectSoundCreate" );
729 730
    if( OurDirectSoundCreate == NULL )
    {
731 732
        msg_Warn( p_aout, "GetProcAddress FAILED" );
        goto error;
733 734
    }

735 736
    /* Get DirectSoundEnumerate */
    OurDirectSoundEnumerate = (void *)
737
       GetProcAddress( p_aout->sys->hdsound_dll,
738
                       "DirectSoundEnumerateW" );
739 740
    if( OurDirectSoundEnumerate )
    {
741
        p_aout->sys->psz_device = var_InheritString(p_aout, "directx-audio-device");
742
        /* Attempt enumeration */
743
        if( FAILED( OurDirectSoundEnumerate( CallBackDirectSoundEnum,
744 745 746 747 748 749
                                             p_aout ) ) )
        {
            msg_Dbg( p_aout, "enumeration of DirectSound devices failed" );
        }
    }

750
    /* Create the direct sound object */
751 752
    if FAILED( OurDirectSoundCreate( p_aout->sys->p_device_guid,
                                     &p_aout->sys->p_dsobject,
753
                                     NULL ) )
754 755
    {
        msg_Warn( p_aout, "cannot create a direct sound device" );
756
        goto error;
757 758 759 760 761 762 763 764 765 766 767 768
    }

    /* Set DirectSound Cooperative level, ie what control we want over Windows
     * sound device. In our case, DSSCL_EXCLUSIVE means that we can modify the
     * settings of the primary buffer, but also that only the sound of our
     * application will be hearable when it will have the focus.
     * !!! (this is not really working as intended yet because to set the
     * cooperative level you need the window handle of your application, and
     * I don't know of any easy way to get it. Especially since we might play
     * sound without any video, and so what window handle should we use ???
     * The hack for now is to use the Desktop window handle - it seems to be
     * working */
769
    if( IDirectSound_SetCooperativeLevel( p_aout->sys->p_dsobject,
770 771
                                          GetDesktopWindow(),
                                          DSSCL_EXCLUSIVE) )
772 773 774 775
    {
        msg_Warn( p_aout, "cannot set direct sound cooperative level" );
    }

776
    return VLC_SUCCESS;
777 778

 error:
779 780
    p_aout->sys->p_dsobject = NULL;
    if( p_aout->sys->hdsound_dll )
781
    {
782 783
        FreeLibrary( p_aout->sys->hdsound_dll );
        p_aout->sys->hdsound_dll = NULL;
784
    }
785
    return VLC_EGENERIC;
786

787 788 789
}

/*****************************************************************************
790
 * CreateDSBuffer: Creates a direct sound buffer of the required format.
791 792 793 794 795 796 797 798
 *****************************************************************************
 * This function creates the buffer we'll use to play audio.
 * In DirectSound there are two kinds of buffers:
 * - the primary buffer: which is the actual buffer that the soundcard plays
 * - the secondary buffer(s): these buffers are the one actually used by
 *    applications and DirectSound takes care of mixing them into the primary.
 *
 * Once you create a secondary buffer, you cannot change its format anymore so
799
 * you have to release the current one and create another.
800
 *****************************************************************************/
801
static int CreateDSBuffer( audio_output_t *p_aout, int i_format,
802
                           int i_channels, int i_nb_channels, int i_rate,
803
                           int i_bytes_per_frame, bool b_probe )
804
{
805
    WAVEFORMATEXTENSIBLE waveformat;
806
    DSBUFFERDESC         dsbdesc;
807
    unsigned int         i;
808

809 810
    /* First set the sound buffer format */
    waveformat.dwChannelMask = 0;
811
    for( i = 0; i < sizeof(pi_channels_src)/sizeof(uint32_t); i++ )
812
    {
813 814
        if( i_channels & pi_channels_src[i] )
            waveformat.dwChannelMask |= pi_channels_in[i];
815
    }
816

817
    switch( i_format )
818
    {
819
    case VLC_CODEC_SPDIFL:
820
        i_nb_channels = 2;
821 822
        /* To prevent channel re-ordering */
        waveformat.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
823 824 825 826
        waveformat.Format.wBitsPerSample = 16;
        waveformat.Samples.wValidBitsPerSample =
            waveformat.Format.wBitsPerSample;
        waveformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
827
        waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
828
        break;
829

830
    case VLC_CODEC_FL32:
831 832 833 834
        waveformat.Format.wBitsPerSample = sizeof(float) * 8;
        waveformat.Samples.wValidBitsPerSample =
            waveformat.Format.wBitsPerSample;
        waveformat.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
835
        waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
836 837
        break;

838
    case VLC_CODEC_S16L:
839 840 841 842
        waveformat.Format.wBitsPerSample = 16;
        waveformat.Samples.wValidBitsPerSample =
            waveformat.Format.wBitsPerSample;
        waveformat.Format.wFormatTag = WAVE_FORMAT_PCM;
843
        waveformat.SubFormat = _KSDATAFORMAT_SUBTYPE_PCM;
844 845
        break;
    }
846

847 848 849 850 851 852 853
    waveformat.Format.nChannels = i_nb_channels;
    waveformat.Format.nSamplesPerSec = i_rate;
    waveformat.Format.nBlockAlign =
        waveformat.Format.wBitsPerSample / 8 * i_nb_channels;
    waveformat.Format.nAvgBytesPerSec =
        waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;

854 855
    p_aout->sys->i_bits_per_sample = waveformat.Format.wBitsPerSample;
    p_aout->sys->i_channels = i_nb_channels;
856

857 858 859 860
    /* Then fill in the direct sound descriptor */
    memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
    dsbdesc.dwSize = sizeof(DSBUFFERDESC);
    dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2/* Better position accuracy */
861 862
                    | DSBCAPS_GLOBALFOCUS       /* Allows background playing */
                    | DSBCAPS_CTRLVOLUME;       /* Allows volume control */
863

864 865 866 867 868 869 870 871 872 873
    /* Only use the new WAVE_FORMAT_EXTENSIBLE format for multichannel audio */
    if( i_nb_channels <= 2 )
    {
        waveformat.Format.cbSize = 0;
    }
    else
    {
        waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
        waveformat.Format.cbSize =
            sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
874

875 876 877
        /* Needed for 5.1 on emu101k */
        dsbdesc.dwFlags |= DSBCAPS_LOCHARDWARE;
    }
878 879 880 881 882

    dsbdesc.dwBufferBytes = FRAMES_NUM * i_bytes_per_frame;   /* buffer size */
    dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&waveformat;

    if FAILED( IDirectSound_CreateSoundBuffer(
883 884
                   p_aout->sys->p_dsobject, &dsbdesc,
                   &p_aout->sys->p_dsbuffer, NULL) )
885
    {
886 887 888 889 890
        if( dsbdesc.dwFlags & DSBCAPS_LOCHARDWARE )
        {
            /* Try without DSBCAPS_LOCHARDWARE */
            dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE;
            if FAILED( IDirectSound_CreateSoundBuffer(
891 892
                   p_aout->sys->p_dsobject, &dsbdesc,
                   &p_aout->sys->p_dsbuffer, NULL) )
893 894 895 896 897 898 899
            {
                return VLC_EGENERIC;
            }
            if( !b_probe )
                msg_Dbg( p_aout, "couldn't use hardware sound buffer" );
        }
        else
900 901 902
        {
            return VLC_EGENERIC;
        }
903 904
    }

905 906 907
    /* Stop here if we were just probing */
    if( b_probe )
    {
908 909
        IDirectSoundBuffer_Release( p_aout->sys->p_dsbuffer );
        p_aout->sys->p_dsbuffer = NULL;
910 911
        return VLC_SUCCESS;
    }
912

913 914 915
    p_aout->sys->i_frame_size = i_bytes_per_frame;
    p_aout->sys->i_channel_mask = waveformat.dwChannelMask;
    p_aout->sys->b_chan_reorder =
916 917
        aout_CheckChannelReorder( pi_channels_in, pi_channels_out,
                                  waveformat.dwChannelMask, i_nb_channels,
918
                                  p_aout->sys->pi_chan_table );
919

920
    if( p_aout->sys->b_chan_reorder )
921 922 923
    {
        msg_Dbg( p_aout, "channel reordering needed" );
    }
924

925
    return VLC_SUCCESS;
926 927 928
}

/*****************************************************************************
929 930 931 932 933
 * CreateDSBufferPCM: creates a PCM direct sound buffer.
 *****************************************************************************
 * We first try to create a WAVE_FORMAT_IEEE_FLOAT buffer if supported by
 * the hardware, otherwise we create a WAVE_FORMAT_PCM buffer.
 ****************************************************************************/
934
static int CreateDSBufferPCM( audio_output_t *p_aout, vlc_fourcc_t *i_format,
935
                              int i_channels, int i_nb_channels, int i_rate,
936
                              bool b_probe )
937
{
938
    /* Float32 audio samples are not supported for 5.1 output on the emu101k */
939 940
    if( !var_GetBool( p_aout, "directx-audio-float32" ) ||
        i_nb_channels > 2 ||
941
        CreateDSBuffer( p_aout, VLC_CODEC_FL32,
942 943 944 945
                        i_channels, i_nb_channels, i_rate,
                        FRAME_SIZE * 4 * i_nb_channels, b_probe )
        != VLC_SUCCESS )
    {
946
        if ( CreateDSBuffer( p_aout, VLC_CODEC_S16L,