src/audio/wasapi/SDL_wasapi.c
author Sam Lantinga <slouken@libsdl.org>
Sat, 24 Feb 2018 08:23:44 -0800
changeset 11897 cb9a637278ad
parent 11890 2d6c0c719ced
child 12222 09e314140a28
permissions -rw-r--r--
Fixed MinGW-w64 build
icculus@10888
     1
/*
icculus@10888
     2
  Simple DirectMedia Layer
slouken@11811
     3
  Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org>
icculus@10888
     4
icculus@10888
     5
  This software is provided 'as-is', without any express or implied
icculus@10888
     6
  warranty.  In no event will the authors be held liable for any damages
icculus@10888
     7
  arising from the use of this software.
icculus@10888
     8
icculus@10888
     9
  Permission is granted to anyone to use this software for any purpose,
icculus@10888
    10
  including commercial applications, and to alter it and redistribute it
icculus@10888
    11
  freely, subject to the following restrictions:
icculus@10888
    12
icculus@10888
    13
  1. The origin of this software must not be misrepresented; you must not
icculus@10888
    14
     claim that you wrote the original software. If you use this software
icculus@10888
    15
     in a product, an acknowledgment in the product documentation would be
icculus@10888
    16
     appreciated but is not required.
icculus@10888
    17
  2. Altered source versions must be plainly marked as such, and must not be
icculus@10888
    18
     misrepresented as being the original software.
icculus@10888
    19
  3. This notice may not be removed or altered from any source distribution.
icculus@10888
    20
*/
icculus@10888
    21
icculus@10888
    22
#include "../../SDL_internal.h"
icculus@10888
    23
icculus@10888
    24
#if SDL_AUDIO_DRIVER_WASAPI
icculus@10888
    25
icculus@10888
    26
#include "../../core/windows/SDL_windows.h"
icculus@10888
    27
#include "SDL_audio.h"
icculus@10888
    28
#include "SDL_timer.h"
icculus@10888
    29
#include "../SDL_audio_c.h"
icculus@10888
    30
#include "../SDL_sysaudio.h"
icculus@10888
    31
#include "SDL_assert.h"
icculus@10888
    32
#include "SDL_log.h"
icculus@10888
    33
icculus@10888
    34
#define COBJMACROS
icculus@10888
    35
#include <mmdeviceapi.h>
icculus@10888
    36
#include <audioclient.h>
icculus@10888
    37
icculus@10888
    38
#include "SDL_wasapi.h"
icculus@10888
    39
slouken@11897
    40
/* This constant isn't available on MinGW-w64 */
slouken@11897
    41
#ifndef AUDCLNT_STREAMFLAGS_RATEADJUST
slouken@11897
    42
#define AUDCLNT_STREAMFLAGS_RATEADJUST  0x00100000
slouken@11897
    43
#endif
slouken@11897
    44
icculus@10949
    45
/* these increment as default devices change. Opened default devices pick up changes in their threads. */
icculus@11726
    46
SDL_atomic_t WASAPI_DefaultPlaybackGeneration;
icculus@11726
    47
SDL_atomic_t WASAPI_DefaultCaptureGeneration;
icculus@10949
    48
icculus@10888
    49
/* This is a list of device id strings we have inflight, so we have consistent pointers to the same device. */
icculus@10888
    50
typedef struct DevIdList
icculus@10888
    51
{
icculus@11010
    52
    WCHAR *str;
icculus@11010
    53
    struct DevIdList *next;
icculus@10888
    54
} DevIdList;
icculus@10888
    55
icculus@10888
    56
static DevIdList *deviceid_list = NULL;
icculus@10888
    57
icculus@10888
    58
/* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
icculus@11726
    59
static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,{ 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
icculus@11726
    60
static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0,{ 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } };
icculus@11726
    61
static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
icculus@11726
    62
static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
icculus@10888
    63
icculus@10888
    64
static SDL_bool
icculus@10888
    65
WStrEqual(const WCHAR *a, const WCHAR *b)
icculus@10888
    66
{
icculus@11010
    67
    while (*a) {
icculus@11010
    68
        if (*a != *b) {
icculus@11010
    69
            return SDL_FALSE;
icculus@11010
    70
        }
icculus@11010
    71
        a++;
icculus@11010
    72
        b++;
icculus@11010
    73
    }
icculus@11010
    74
    return *b == 0;
icculus@10888
    75
}
icculus@10888
    76
icculus@11726
    77
static size_t
icculus@11726
    78
WStrLen(const WCHAR *wstr)
icculus@11726
    79
{
icculus@11726
    80
    size_t retval = 0;
icculus@11726
    81
    if (wstr) {
icculus@11726
    82
        while (*(wstr++)) {
icculus@11726
    83
            retval++;
icculus@11726
    84
        }
icculus@11726
    85
    }
icculus@11726
    86
    return retval;
icculus@11726
    87
}
icculus@11726
    88
icculus@10888
    89
static WCHAR *
icculus@10888
    90
WStrDupe(const WCHAR *wstr)
icculus@10888
    91
{
icculus@11793
    92
    const size_t len = (WStrLen(wstr) + 1) * sizeof (WCHAR);
icculus@11010
    93
    WCHAR *retval = (WCHAR *) SDL_malloc(len);
icculus@11010
    94
    if (retval) {
icculus@11010
    95
        SDL_memcpy(retval, wstr, len);
icculus@11010
    96
    }
icculus@11010
    97
    return retval;
icculus@10888
    98
}
icculus@10888
    99
icculus@11726
   100
icculus@11726
   101
void
icculus@11726
   102
WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid)
icculus@10888
   103
{
icculus@11010
   104
    DevIdList *i;
icculus@11010
   105
    DevIdList *next;
icculus@11010
   106
    DevIdList *prev = NULL;
icculus@11010
   107
    for (i = deviceid_list; i; i = next) {
icculus@11010
   108
        next = i->next;
icculus@11010
   109
        if (WStrEqual(i->str, devid)) {
icculus@11010
   110
            if (prev) {
icculus@11010
   111
                prev->next = next;
icculus@11010
   112
            } else {
icculus@11010
   113
                deviceid_list = next;
icculus@11010
   114
            }
icculus@11010
   115
            SDL_RemoveAudioDevice(iscapture, i->str);
icculus@11010
   116
            SDL_free(i->str);
icculus@11010
   117
            SDL_free(i);
icculus@11010
   118
        }
icculus@11010
   119
        prev = i;
icculus@11010
   120
    }
icculus@10888
   121
}
icculus@10888
   122
icculus@11726
   123
void
icculus@11726
   124
WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, LPCWSTR devid)
icculus@10888
   125
{
icculus@11010
   126
    DevIdList *devidlist;
icculus@10888
   127
icculus@11010
   128
    /* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever).
icculus@10888
   129
       In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for
icculus@10888
   130
       phones and tablets, where you might have an internal speaker and a headphone jack and expect both to be
icculus@10888
   131
       available and switch automatically. (!!! FIXME...?) */
icculus@10888
   132
icculus@11010
   133
    /* see if we already have this one. */
icculus@11010
   134
    for (devidlist = deviceid_list; devidlist; devidlist = devidlist->next) {
icculus@11010
   135
        if (WStrEqual(devidlist->str, devid)) {
icculus@11010
   136
            return;  /* we already have this. */
icculus@11010
   137
        }
icculus@11010
   138
    }
icculus@10888
   139
icculus@11010
   140
    devidlist = (DevIdList *) SDL_malloc(sizeof (*devidlist));
icculus@11010
   141
    if (!devidlist) {
icculus@11010
   142
        return;  /* oh well. */
icculus@11010
   143
    }
icculus@10888
   144
icculus@11010
   145
    devid = WStrDupe(devid);
icculus@11010
   146
    if (!devid) {
icculus@11010
   147
        SDL_free(devidlist);
icculus@11010
   148
        return;  /* oh well. */
icculus@11010
   149
    }
icculus@10888
   150
icculus@11010
   151
    devidlist->str = (WCHAR *) devid;
icculus@11010
   152
    devidlist->next = deviceid_list;
icculus@11010
   153
    deviceid_list = devidlist;
icculus@10888
   154
icculus@11726
   155
    SDL_AddAudioDevice(iscapture, devname, (void *) devid);
icculus@10888
   156
}
icculus@10888
   157
icculus@10888
   158
static void
icculus@10888
   159
WASAPI_DetectDevices(void)
icculus@10888
   160
{
icculus@11726
   161
    WASAPI_EnumerateEndpoints();
icculus@10888
   162
}
icculus@10888
   163
icculus@10949
   164
static int
icculus@10949
   165
WASAPI_GetPendingBytes(_THIS)
icculus@10949
   166
{
icculus@10949
   167
    UINT32 frames = 0;
icculus@10949
   168
icculus@10949
   169
    /* it's okay to fail here; we'll deal with failures in the audio thread. */
slouken@11162
   170
    /* FIXME: need a lock around checking this->hidden->client */
icculus@11726
   171
    if (this->hidden->client != NULL) {  /* definitely activated? */
icculus@11726
   172
        if (FAILED(IAudioClient_GetCurrentPadding(this->hidden->client, &frames))) {
icculus@11726
   173
            return 0;  /* oh well. */
icculus@11726
   174
        }
icculus@10949
   175
    }
icculus@10949
   176
    return ((int) frames) * this->hidden->framesize;
icculus@10949
   177
}
icculus@10949
   178
icculus@10949
   179
static SDL_INLINE SDL_bool
icculus@10949
   180
WasapiFailed(_THIS, const HRESULT err)
icculus@10949
   181
{
icculus@10949
   182
    if (err == S_OK) {
icculus@10949
   183
        return SDL_FALSE;
icculus@10949
   184
    }
icculus@10949
   185
icculus@10949
   186
    if (err == AUDCLNT_E_DEVICE_INVALIDATED) {
icculus@10949
   187
        this->hidden->device_lost = SDL_TRUE;
icculus@10949
   188
    } else if (SDL_AtomicGet(&this->enabled)) {
icculus@11010
   189
        IAudioClient_Stop(this->hidden->client);
icculus@11010
   190
        SDL_OpenedAudioDeviceDisconnected(this);
icculus@10949
   191
        SDL_assert(!SDL_AtomicGet(&this->enabled));
icculus@10949
   192
    }
icculus@10949
   193
icculus@10949
   194
    return SDL_TRUE;
icculus@10949
   195
}
icculus@10949
   196
icculus@11726
   197
static int
icculus@11726
   198
UpdateAudioStream(_THIS, const SDL_AudioSpec *oldspec)
icculus@10948
   199
{
icculus@10948
   200
    /* Since WASAPI requires us to handle all audio conversion, and our
icculus@10948
   201
       device format might have changed, we might have to add/remove/change
icculus@10948
   202
       the audio stream that the higher level uses to convert data, so
icculus@10948
   203
       SDL keeps firing the callback as if nothing happened here. */
icculus@10948
   204
icculus@10948
   205
    if ( (this->callbackspec.channels == this->spec.channels) &&
icculus@10948
   206
         (this->callbackspec.format == this->spec.format) &&
icculus@10948
   207
         (this->callbackspec.freq == this->spec.freq) &&
icculus@10948
   208
         (this->callbackspec.samples == this->spec.samples) ) {
icculus@10948
   209
        /* no need to buffer/convert in an AudioStream! */
icculus@10948
   210
        SDL_FreeAudioStream(this->stream);
icculus@10948
   211
        this->stream = NULL;
icculus@11726
   212
    } else if ( (oldspec->channels == this->spec.channels) &&
icculus@11726
   213
         (oldspec->format == this->spec.format) &&
icculus@11726
   214
         (oldspec->freq == this->spec.freq) ) {
icculus@10948
   215
        /* The existing audio stream is okay to keep using. */
icculus@10948
   216
    } else {
icculus@10948
   217
        /* replace the audiostream for new format */
icculus@10948
   218
        SDL_FreeAudioStream(this->stream);
icculus@10948
   219
        if (this->iscapture) {
icculus@10948
   220
            this->stream = SDL_NewAudioStream(this->spec.format,
icculus@10948
   221
                                this->spec.channels, this->spec.freq,
icculus@10948
   222
                                this->callbackspec.format,
icculus@10948
   223
                                this->callbackspec.channels,
icculus@10948
   224
                                this->callbackspec.freq);
icculus@10948
   225
        } else {
icculus@10948
   226
            this->stream = SDL_NewAudioStream(this->callbackspec.format,
icculus@10948
   227
                                this->callbackspec.channels,
icculus@10948
   228
                                this->callbackspec.freq, this->spec.format,
icculus@10948
   229
                                this->spec.channels, this->spec.freq);
icculus@10948
   230
        }
icculus@10948
   231
icculus@10948
   232
        if (!this->stream) {
icculus@11726
   233
            return -1;
icculus@10948
   234
        }
icculus@10948
   235
    }
icculus@10948
   236
icculus@10948
   237
    /* make sure our scratch buffer can cover the new device spec. */
icculus@10948
   238
    if (this->spec.size > this->work_buffer_len) {
icculus@10948
   239
        Uint8 *ptr = (Uint8 *) SDL_realloc(this->work_buffer, this->spec.size);
icculus@10948
   240
        if (ptr == NULL) {
icculus@11726
   241
            return SDL_OutOfMemory();
icculus@10948
   242
        }
icculus@10948
   243
        this->work_buffer = ptr;
icculus@10948
   244
        this->work_buffer_len = this->spec.size;
icculus@10948
   245
    }
icculus@10948
   246
icculus@11726
   247
    return 0;
icculus@11726
   248
}
icculus@11726
   249
icculus@11726
   250
icculus@11726
   251
static void ReleaseWasapiDevice(_THIS);
icculus@11726
   252
icculus@11726
   253
static SDL_bool
icculus@11726
   254
RecoverWasapiDevice(_THIS)
icculus@11726
   255
{
icculus@11726
   256
    ReleaseWasapiDevice(this);  /* dump the lost device's handles. */
icculus@11726
   257
icculus@11726
   258
    if (this->hidden->default_device_generation) {
icculus@11726
   259
        this->hidden->default_device_generation = SDL_AtomicGet(this->iscapture ?  &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration);
icculus@11726
   260
    }
icculus@11726
   261
icculus@11726
   262
    /* this can fail for lots of reasons, but the most likely is we had a
icculus@11726
   263
       non-default device that was disconnected, so we can't recover. Default
icculus@11726
   264
       devices try to reinitialize whatever the new default is, so it's more
icculus@11726
   265
       likely to carry on here, but this handles a non-default device that
icculus@11726
   266
       simply had its format changed in the Windows Control Panel. */
icculus@11726
   267
    if (WASAPI_ActivateDevice(this, SDL_TRUE) == -1) {
icculus@11726
   268
        SDL_OpenedAudioDeviceDisconnected(this);
icculus@11726
   269
        return SDL_FALSE;
icculus@11726
   270
    }
icculus@11726
   271
icculus@10949
   272
    this->hidden->device_lost = SDL_FALSE;
icculus@10949
   273
icculus@10948
   274
    return SDL_TRUE;  /* okay, carry on with new device details! */
icculus@10948
   275
}
icculus@10948
   276
icculus@10949
   277
static SDL_bool
icculus@10949
   278
RecoverWasapiIfLost(_THIS)
icculus@10949
   279
{
icculus@10949
   280
    const int generation = this->hidden->default_device_generation;
icculus@10949
   281
    SDL_bool lost = this->hidden->device_lost;
icculus@10948
   282
icculus@10949
   283
    if (!SDL_AtomicGet(&this->enabled)) {
icculus@10949
   284
        return SDL_FALSE;  /* already failed. */
icculus@10949
   285
    }
icculus@10949
   286
icculus@11726
   287
    if (!this->hidden->client) {
icculus@11726
   288
        return SDL_TRUE;  /* still waiting for activation. */
icculus@11726
   289
    }
icculus@11726
   290
icculus@10949
   291
    if (!lost && (generation > 0)) { /* is a default device? */
icculus@11726
   292
        const int newgen = SDL_AtomicGet(this->iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration);
icculus@10949
   293
        if (generation != newgen) {  /* the desired default device was changed, jump over to it. */
icculus@10949
   294
            lost = SDL_TRUE;
icculus@10948
   295
        }
icculus@10948
   296
    }
icculus@10948
   297
icculus@10949
   298
    return lost ? RecoverWasapiDevice(this) : SDL_TRUE;
icculus@10888
   299
}
icculus@10888
   300
icculus@10888
   301
static Uint8 *
icculus@10888
   302
WASAPI_GetDeviceBuf(_THIS)
icculus@10888
   303
{
icculus@10888
   304
    /* get an endpoint buffer from WASAPI. */
icculus@10888
   305
    BYTE *buffer = NULL;
icculus@10948
   306
icculus@11726
   307
    while (RecoverWasapiIfLost(this) && this->hidden->render) {
icculus@10949
   308
        if (!WasapiFailed(this, IAudioRenderClient_GetBuffer(this->hidden->render, this->spec.samples, &buffer))) {
icculus@10949
   309
            return (Uint8 *) buffer;
icculus@10949
   310
        }
icculus@10888
   311
        SDL_assert(buffer == NULL);
icculus@10888
   312
    }
icculus@10949
   313
icculus@10888
   314
    return (Uint8 *) buffer;
icculus@10888
   315
}
icculus@10888
   316
icculus@10888
   317
static void
icculus@10888
   318
WASAPI_PlayDevice(_THIS)
icculus@10888
   319
{
icculus@11726
   320
    if (this->hidden->render != NULL) {  /* definitely activated? */
icculus@11726
   321
        /* WasapiFailed() will mark the device for reacquisition or removal elsewhere. */
icculus@11726
   322
        WasapiFailed(this, IAudioRenderClient_ReleaseBuffer(this->hidden->render, this->spec.samples, 0));
icculus@11726
   323
    }
icculus@10888
   324
}
icculus@10888
   325
icculus@10888
   326
static void
icculus@10888
   327
WASAPI_WaitDevice(_THIS)
icculus@10888
   328
{
icculus@11776
   329
    while (RecoverWasapiIfLost(this) && this->hidden->client && this->hidden->event) {
icculus@11776
   330
        /*SDL_Log("WAITDEVICE");*/
icculus@11793
   331
        if (WaitForSingleObjectEx(this->hidden->event, INFINITE, FALSE) == WAIT_OBJECT_0) {
icculus@11776
   332
            const UINT32 maxpadding = this->spec.samples;
icculus@11776
   333
            UINT32 padding = 0;
icculus@11776
   334
            if (!WasapiFailed(this, IAudioClient_GetCurrentPadding(this->hidden->client, &padding))) {
icculus@11776
   335
                /*SDL_Log("WASAPI EVENT! padding=%u maxpadding=%u", (unsigned int)padding, (unsigned int)maxpadding);*/
icculus@11776
   336
                if (padding <= maxpadding) {
icculus@11776
   337
                    break;
icculus@11776
   338
                }
icculus@10949
   339
            }
icculus@11776
   340
        } else {
icculus@11776
   341
            /*SDL_Log("WASAPI FAILED EVENT!");*/
icculus@11776
   342
            IAudioClient_Stop(this->hidden->client);
icculus@11776
   343
            SDL_OpenedAudioDeviceDisconnected(this);
icculus@10888
   344
        }
icculus@11010
   345
    }
icculus@10888
   346
}
icculus@10888
   347
icculus@10888
   348
static int
icculus@10888
   349
WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen)
icculus@10888
   350
{
icculus@10888
   351
    SDL_AudioStream *stream = this->hidden->capturestream;
icculus@10888
   352
    const int avail = SDL_AudioStreamAvailable(stream);
icculus@10888
   353
    if (avail > 0) {
icculus@10888
   354
        const int cpy = SDL_min(buflen, avail);
icculus@10888
   355
        SDL_AudioStreamGet(stream, buffer, cpy);
icculus@10888
   356
        return cpy;
icculus@10888
   357
    }
icculus@10888
   358
icculus@10949
   359
    while (RecoverWasapiIfLost(this)) {
icculus@10888
   360
        HRESULT ret;
icculus@10888
   361
        BYTE *ptr = NULL;
icculus@10888
   362
        UINT32 frames = 0;
icculus@10888
   363
        DWORD flags = 0;
icculus@10888
   364
icculus@11726
   365
        /* uhoh, client isn't activated yet, just return silence. */
icculus@11726
   366
        if (!this->hidden->capture) {
icculus@11726
   367
            /* Delay so we run at about the speed that audio would be arriving. */
icculus@11726
   368
            SDL_Delay(((this->spec.samples * 1000) / this->spec.freq));
icculus@11726
   369
            SDL_memset(buffer, this->spec.silence, buflen);
icculus@11726
   370
            return buflen;
icculus@11726
   371
        }
icculus@11726
   372
icculus@10949
   373
        ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
icculus@11014
   374
        if (ret != AUDCLNT_S_BUFFER_EMPTY) {
icculus@11014
   375
            WasapiFailed(this, ret); /* mark device lost/failed if necessary. */
icculus@11014
   376
        }
icculus@10948
   377
icculus@10888
   378
        if ((ret == AUDCLNT_S_BUFFER_EMPTY) || !frames) {
icculus@10888
   379
            WASAPI_WaitDevice(this);
icculus@10888
   380
        } else if (ret == S_OK) {
icculus@10888
   381
            const int total = ((int) frames) * this->hidden->framesize;
icculus@10888
   382
            const int cpy = SDL_min(buflen, total);
icculus@10888
   383
            const int leftover = total - cpy;
icculus@10888
   384
            const SDL_bool silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) ? SDL_TRUE : SDL_FALSE;
icculus@10888
   385
icculus@10888
   386
            if (silent) {
icculus@10888
   387
                SDL_memset(buffer, this->spec.silence, cpy);
icculus@10888
   388
            } else {
icculus@10888
   389
                SDL_memcpy(buffer, ptr, cpy);
icculus@10888
   390
            }
icculus@10888
   391
            
icculus@10888
   392
            if (leftover > 0) {
icculus@10888
   393
                ptr += cpy;
icculus@10888
   394
                if (silent) {
icculus@10888
   395
                    SDL_memset(ptr, this->spec.silence, leftover);  /* I guess this is safe? */
icculus@10888
   396
                }
icculus@10888
   397
icculus@10888
   398
                if (SDL_AudioStreamPut(stream, ptr, leftover) == -1) {
icculus@10888
   399
                    return -1;  /* uhoh, out of memory, etc. Kill device.  :( */
icculus@10888
   400
                }
icculus@10888
   401
            }
icculus@10888
   402
icculus@10949
   403
            ret = IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames);
icculus@10949
   404
            WasapiFailed(this, ret); /* mark device lost/failed if necessary. */
icculus@10949
   405
icculus@10888
   406
            return cpy;
icculus@10888
   407
        }
icculus@10888
   408
    }
icculus@10888
   409
icculus@10888
   410
    return -1;  /* unrecoverable error. */
icculus@10888
   411
}
icculus@10888
   412
icculus@10888
   413
static void
icculus@10888
   414
WASAPI_FlushCapture(_THIS)
icculus@10888
   415
{
slouken@11161
   416
    BYTE *ptr = NULL;
slouken@11161
   417
    UINT32 frames = 0;
slouken@11161
   418
    DWORD flags = 0;
icculus@10949
   419
icculus@11726
   420
    if (!this->hidden->capture) {
icculus@11726
   421
        return;  /* not activated yet? */
icculus@11726
   422
    }
icculus@11726
   423
slouken@11161
   424
    /* just read until we stop getting packets, throwing them away. */
slouken@11161
   425
    while (SDL_TRUE) {
slouken@11161
   426
        const HRESULT ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
slouken@11161
   427
        if (ret == AUDCLNT_S_BUFFER_EMPTY) {
slouken@11161
   428
            break;  /* no more buffered data; we're done. */
slouken@11161
   429
        } else if (WasapiFailed(this, ret)) {
slouken@11161
   430
            break;  /* failed for some other reason, abort. */
slouken@11161
   431
        } else if (WasapiFailed(this, IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames))) {
slouken@11161
   432
            break;  /* something broke. */
icculus@10888
   433
        }
icculus@10888
   434
    }
slouken@11161
   435
    SDL_AudioStreamClear(this->hidden->capturestream);
icculus@10888
   436
}
icculus@10888
   437
icculus@10888
   438
static void
icculus@10948
   439
ReleaseWasapiDevice(_THIS)
icculus@10948
   440
{
icculus@11010
   441
    if (this->hidden->client) {
icculus@10948
   442
        IAudioClient_Stop(this->hidden->client);
icculus@11776
   443
        IAudioClient_SetEventHandle(this->hidden->client, NULL);
icculus@11776
   444
        IAudioClient_Release(this->hidden->client);
icculus@10948
   445
        this->hidden->client = NULL;
icculus@10948
   446
    }
icculus@10948
   447
icculus@10948
   448
    if (this->hidden->render) {
icculus@10948
   449
        IAudioRenderClient_Release(this->hidden->render);
icculus@10948
   450
        this->hidden->render = NULL;
icculus@10948
   451
    }
icculus@10948
   452
icculus@10948
   453
    if (this->hidden->capture) {
icculus@10948
   454
        IAudioCaptureClient_Release(this->hidden->capture);
slouken@11160
   455
        this->hidden->capture = NULL;
icculus@10948
   456
    }
icculus@10948
   457
icculus@10948
   458
    if (this->hidden->waveformat) {
icculus@10948
   459
        CoTaskMemFree(this->hidden->waveformat);
icculus@10948
   460
        this->hidden->waveformat = NULL;
icculus@10948
   461
    }
icculus@10948
   462
icculus@10948
   463
    if (this->hidden->capturestream) {
icculus@10948
   464
        SDL_FreeAudioStream(this->hidden->capturestream);
icculus@10948
   465
        this->hidden->capturestream = NULL;
icculus@10948
   466
    }
icculus@11726
   467
icculus@11726
   468
    if (this->hidden->activation_handler) {
icculus@11726
   469
        WASAPI_PlatformDeleteActivationHandler(this->hidden->activation_handler);
icculus@11726
   470
        this->hidden->activation_handler = NULL;
icculus@11726
   471
    }
icculus@11776
   472
icculus@11776
   473
    if (this->hidden->event) {
icculus@11776
   474
        CloseHandle(this->hidden->event);
icculus@11776
   475
        this->hidden->event = NULL;
icculus@11776
   476
    }
icculus@10948
   477
}
icculus@10948
   478
icculus@10948
   479
static void
icculus@10888
   480
WASAPI_CloseDevice(_THIS)
icculus@10888
   481
{
icculus@11726
   482
    WASAPI_UnrefDevice(this);
icculus@11726
   483
}
icculus@11726
   484
icculus@11726
   485
void
icculus@11726
   486
WASAPI_RefDevice(_THIS)
icculus@11726
   487
{
icculus@11726
   488
    SDL_AtomicIncRef(&this->hidden->refcount);
icculus@11726
   489
}
icculus@11726
   490
icculus@11726
   491
void
icculus@11726
   492
WASAPI_UnrefDevice(_THIS)
icculus@11726
   493
{
icculus@11726
   494
    if (!SDL_AtomicDecRef(&this->hidden->refcount)) {
icculus@11726
   495
        return;
icculus@11726
   496
    }
icculus@11726
   497
icculus@11726
   498
    /* actual closing happens here. */
icculus@11726
   499
icculus@10888
   500
    /* don't touch this->hidden->task in here; it has to be reverted from
icculus@11726
   501
       our callback thread. We do that in WASAPI_ThreadDeinit().
icculus@11726
   502
       (likewise for this->hidden->coinitialized). */
icculus@10948
   503
    ReleaseWasapiDevice(this);
icculus@11726
   504
    SDL_free(this->hidden->devid);
icculus@10888
   505
    SDL_free(this->hidden);
icculus@10888
   506
}
icculus@10888
   507
icculus@11726
   508
/* This is called once a device is activated, possibly asynchronously. */
icculus@11726
   509
int
icculus@11726
   510
WASAPI_PrepDevice(_THIS, const SDL_bool updatestream)
icculus@10888
   511
{
icculus@10888
   512
    /* !!! FIXME: we could request an exclusive mode stream, which is lower latency;
icculus@10888
   513
       !!!  it will write into the kernel's audio buffer directly instead of
icculus@10888
   514
       !!!  shared memory that a user-mode mixer then writes to the kernel with
icculus@10888
   515
       !!!  everything else. Doing this means any other sound using this device will
icculus@10888
   516
       !!!  stop playing, including the user's MP3 player and system notification
icculus@10888
   517
       !!!  sounds. You'd probably need to release the device when the app isn't in
icculus@10888
   518
       !!!  the foreground, to be a good citizen of the system. It's doable, but it's
icculus@10888
   519
       !!!  more work and causes some annoyances, and I don't know what the latency
icculus@10888
   520
       !!!  wins actually look like. Maybe add a hint to force exclusive mode at
icculus@10888
   521
       !!!  some point. To be sure, defaulting to shared mode is the right thing to
icculus@10888
   522
       !!!  do in any case. */
icculus@11726
   523
    const SDL_AudioSpec oldspec = this->spec;
icculus@10888
   524
    const AUDCLNT_SHAREMODE sharemode = AUDCLNT_SHAREMODE_SHARED;
icculus@10888
   525
    UINT32 bufsize = 0;  /* this is in sample frames, not samples, not bytes. */
icculus@10888
   526
    REFERENCE_TIME duration = 0;
icculus@11726
   527
    IAudioClient *client = this->hidden->client;
icculus@10888
   528
    IAudioRenderClient *render = NULL;
icculus@10888
   529
    IAudioCaptureClient *capture = NULL;
icculus@10888
   530
    WAVEFORMATEX *waveformat = NULL;
icculus@10888
   531
    SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
icculus@10888
   532
    SDL_AudioFormat wasapi_format = 0;
icculus@10888
   533
    SDL_bool valid_format = SDL_FALSE;
icculus@10888
   534
    HRESULT ret = S_OK;
icculus@11890
   535
    DWORD streamflags = 0;
icculus@10888
   536
icculus@10888
   537
    SDL_assert(client != NULL);
icculus@10888
   538
icculus@11793
   539
#ifdef __WINRT__  /* CreateEventEx() arrived in Vista, so we need an #ifdef for XP. */
icculus@11793
   540
    this->hidden->event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
icculus@11793
   541
#else
icculus@11776
   542
    this->hidden->event = CreateEventW(NULL, 0, 0, NULL);
icculus@11793
   543
#endif
icculus@11793
   544
icculus@11776
   545
    if (this->hidden->event == NULL) {
icculus@11776
   546
        return WIN_SetError("WASAPI can't create an event handle");
icculus@11776
   547
    }
icculus@11776
   548
icculus@10888
   549
    ret = IAudioClient_GetMixFormat(client, &waveformat);
icculus@10888
   550
    if (FAILED(ret)) {
icculus@10888
   551
        return WIN_SetErrorFromHRESULT("WASAPI can't determine mix format", ret);
icculus@10888
   552
    }
icculus@10888
   553
icculus@10888
   554
    SDL_assert(waveformat != NULL);
icculus@10888
   555
    this->hidden->waveformat = waveformat;
icculus@10888
   556
icculus@10888
   557
    this->spec.channels = (Uint8) waveformat->nChannels;
icculus@10888
   558
icculus@10888
   559
    /* Make sure we have a valid format that we can convert to whatever WASAPI wants. */
icculus@10888
   560
    if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) {
icculus@10888
   561
        wasapi_format = AUDIO_F32SYS;
icculus@10888
   562
    } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) {
icculus@10888
   563
        wasapi_format = AUDIO_S16SYS;
icculus@10888
   564
    } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) {
icculus@10888
   565
        wasapi_format = AUDIO_S32SYS;
icculus@10888
   566
    } else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
icculus@10888
   567
        const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *) waveformat;
icculus@10888
   568
        if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
icculus@10888
   569
            wasapi_format = AUDIO_F32SYS;
icculus@10888
   570
        } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 16)) {
icculus@10888
   571
            wasapi_format = AUDIO_S16SYS;
icculus@10888
   572
        } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
icculus@10888
   573
            wasapi_format = AUDIO_S32SYS;
icculus@10888
   574
        }
icculus@10888
   575
    }
icculus@10888
   576
icculus@10888
   577
    while ((!valid_format) && (test_format)) {
icculus@10888
   578
        if (test_format == wasapi_format) {
icculus@10888
   579
            this->spec.format = test_format;
icculus@10888
   580
            valid_format = SDL_TRUE;
icculus@10888
   581
            break;
icculus@10888
   582
        }
icculus@10888
   583
        test_format = SDL_NextAudioFormat();
icculus@10888
   584
    }
icculus@10888
   585
icculus@10888
   586
    if (!valid_format) {
icculus@10888
   587
        return SDL_SetError("WASAPI: Unsupported audio format");
icculus@10888
   588
    }
icculus@10888
   589
icculus@10888
   590
    ret = IAudioClient_GetDevicePeriod(client, NULL, &duration);
icculus@10888
   591
    if (FAILED(ret)) {
icculus@10888
   592
        return WIN_SetErrorFromHRESULT("WASAPI can't determine minimum device period", ret);
icculus@10888
   593
    }
icculus@10888
   594
icculus@11890
   595
    /* favor WASAPI's resampler over our own, in Win7+. */
icculus@11890
   596
    if (this->spec.freq != waveformat->nSamplesPerSec) {
icculus@11890
   597
        /* RATEADJUST only works with output devices in share mode, and is available in Win7 and later.*/
icculus@11890
   598
        if (WIN_IsWindows7OrGreater() && !this->iscapture && (sharemode == AUDCLNT_SHAREMODE_SHARED)) {
icculus@11890
   599
            streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST;
icculus@11890
   600
            waveformat->nSamplesPerSec = this->spec.freq;
icculus@11890
   601
            waveformat->nAvgBytesPerSec = waveformat->nSamplesPerSec * waveformat->nChannels * (waveformat->wBitsPerSample / 8);
icculus@11890
   602
        }
icculus@11890
   603
        else {
icculus@11890
   604
            this->spec.freq = waveformat->nSamplesPerSec;  /* force sampling rate so our resampler kicks in. */
icculus@11890
   605
        }
icculus@11890
   606
    }
icculus@11890
   607
icculus@11890
   608
    streamflags |= AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
icculus@11890
   609
    ret = IAudioClient_Initialize(client, sharemode, streamflags, duration, sharemode == AUDCLNT_SHAREMODE_SHARED ? 0 : duration, waveformat, NULL);
icculus@10888
   610
    if (FAILED(ret)) {
icculus@10888
   611
        return WIN_SetErrorFromHRESULT("WASAPI can't initialize audio client", ret);
icculus@10888
   612
    }
icculus@10888
   613
icculus@11776
   614
    ret = IAudioClient_SetEventHandle(client, this->hidden->event);
icculus@11776
   615
    if (FAILED(ret)) {
icculus@11776
   616
        return WIN_SetErrorFromHRESULT("WASAPI can't set event handle", ret);
icculus@11776
   617
    }
icculus@11776
   618
icculus@11010
   619
    ret = IAudioClient_GetBufferSize(client, &bufsize);
icculus@10888
   620
    if (FAILED(ret)) {
icculus@10888
   621
        return WIN_SetErrorFromHRESULT("WASAPI can't determine buffer size", ret);
icculus@10888
   622
    }
icculus@10888
   623
icculus@10888
   624
    this->spec.samples = (Uint16) bufsize;
icculus@11726
   625
    if (!this->iscapture) {
icculus@11010
   626
        this->spec.samples /= 2;  /* fill half of the DMA buffer on each run. */
icculus@11010
   627
    }
icculus@10888
   628
icculus@10888
   629
    /* Update the fragment size as size in bytes */
icculus@10888
   630
    SDL_CalculateAudioSpec(&this->spec);
icculus@10888
   631
icculus@10888
   632
    this->hidden->framesize = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels;
icculus@10888
   633
icculus@11726
   634
    if (this->iscapture) {
icculus@10888
   635
        this->hidden->capturestream = SDL_NewAudioStream(this->spec.format, this->spec.channels, this->spec.freq, this->spec.format, this->spec.channels, this->spec.freq);
icculus@10888
   636
        if (!this->hidden->capturestream) {
icculus@10888
   637
            return -1;  /* already set SDL_Error */
icculus@10888
   638
        }
icculus@10888
   639
icculus@10888
   640
        ret = IAudioClient_GetService(client, &SDL_IID_IAudioCaptureClient, (void**) &capture);
icculus@10888
   641
        if (FAILED(ret)) {
icculus@10888
   642
            return WIN_SetErrorFromHRESULT("WASAPI can't get capture client service", ret);
icculus@10888
   643
        }
icculus@10888
   644
icculus@10888
   645
        SDL_assert(capture != NULL);
icculus@10888
   646
        this->hidden->capture = capture;
icculus@10888
   647
        ret = IAudioClient_Start(client);
icculus@10888
   648
        if (FAILED(ret)) {
icculus@10888
   649
            return WIN_SetErrorFromHRESULT("WASAPI can't start capture", ret);
icculus@10888
   650
        }
icculus@10888
   651
icculus@10888
   652
        WASAPI_FlushCapture(this);  /* MSDN says you should flush capture endpoint right after startup. */
icculus@10888
   653
    } else {
icculus@10888
   654
        ret = IAudioClient_GetService(client, &SDL_IID_IAudioRenderClient, (void**) &render);
icculus@10888
   655
        if (FAILED(ret)) {
icculus@10888
   656
            return WIN_SetErrorFromHRESULT("WASAPI can't get render client service", ret);
icculus@10888
   657
        }
icculus@10888
   658
icculus@10888
   659
        SDL_assert(render != NULL);
icculus@10888
   660
        this->hidden->render = render;
icculus@10888
   661
        ret = IAudioClient_Start(client);
icculus@10888
   662
        if (FAILED(ret)) {
icculus@10888
   663
            return WIN_SetErrorFromHRESULT("WASAPI can't start playback", ret);
icculus@10888
   664
        }
icculus@10888
   665
    }
icculus@10888
   666
icculus@11726
   667
    if (updatestream) {
icculus@11726
   668
        if (UpdateAudioStream(this, &oldspec) == -1) {
icculus@11726
   669
            return -1;
icculus@11726
   670
        }
icculus@11726
   671
    }
icculus@11726
   672
icculus@10888
   673
    return 0;  /* good to go. */
icculus@10888
   674
}
icculus@10888
   675
icculus@11726
   676
icculus@10948
   677
static int
icculus@10948
   678
WASAPI_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
icculus@10948
   679
{
icculus@11726
   680
    LPCWSTR devid = (LPCWSTR) handle;
icculus@10948
   681
icculus@10948
   682
    /* Initialize all variables that we clean on shutdown */
icculus@10948
   683
    this->hidden = (struct SDL_PrivateAudioData *)
icculus@10948
   684
        SDL_malloc((sizeof *this->hidden));
icculus@10948
   685
    if (this->hidden == NULL) {
icculus@10948
   686
        return SDL_OutOfMemory();
icculus@10948
   687
    }
icculus@10948
   688
    SDL_zerop(this->hidden);
icculus@10948
   689
icculus@11726
   690
    WASAPI_RefDevice(this);   /* so CloseDevice() will unref to zero. */
icculus@11726
   691
icculus@11726
   692
    if (!devid) {  /* is default device? */
icculus@11726
   693
        this->hidden->default_device_generation = SDL_AtomicGet(iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration);
icculus@11010
   694
    } else {
icculus@11726
   695
        this->hidden->devid = WStrDupe(devid);
icculus@11726
   696
        if (!this->hidden->devid) {
icculus@11726
   697
            return SDL_OutOfMemory();
icculus@11726
   698
        }
icculus@10948
   699
    }
icculus@10948
   700
icculus@11726
   701
    if (WASAPI_ActivateDevice(this, SDL_FALSE) == -1) {
icculus@11726
   702
        return -1;  /* already set error. */
icculus@10948
   703
    }
icculus@10948
   704
icculus@11726
   705
    /* Ready, but waiting for async device activation.
icculus@11726
   706
       Until activation is successful, we will report silence from capture
icculus@11726
   707
       devices and ignore data on playback devices.
icculus@11726
   708
       Also, since we don't know the _actual_ device format until after
icculus@11726
   709
       activation, we let the app have whatever it asks for. We set up
icculus@11726
   710
       an SDL_AudioStream to convert, if necessary, once the activation
icculus@11726
   711
       completes. */
icculus@11726
   712
icculus@11726
   713
    return 0;
icculus@10948
   714
}
icculus@10948
   715
icculus@10888
   716
static void
icculus@10888
   717
WASAPI_ThreadInit(_THIS)
icculus@10888
   718
{
icculus@11726
   719
    WASAPI_PlatformThreadInit(this);
icculus@10888
   720
}
icculus@10888
   721
icculus@10888
   722
static void
icculus@10888
   723
WASAPI_ThreadDeinit(_THIS)
icculus@10888
   724
{
icculus@11726
   725
    WASAPI_PlatformThreadDeinit(this);
icculus@10888
   726
}
icculus@10888
   727
icculus@10888
   728
static void
icculus@10888
   729
WASAPI_Deinitialize(void)
icculus@10888
   730
{
icculus@11010
   731
    DevIdList *devidlist;
icculus@11010
   732
    DevIdList *next;
icculus@10888
   733
icculus@11726
   734
    WASAPI_PlatformDeinit();
icculus@10888
   735
icculus@11010
   736
    for (devidlist = deviceid_list; devidlist; devidlist = next) {
icculus@11010
   737
        next = devidlist->next;
icculus@11010
   738
        SDL_free(devidlist->str);
icculus@11010
   739
        SDL_free(devidlist);
icculus@11010
   740
    }
icculus@11010
   741
    deviceid_list = NULL;
icculus@10888
   742
}
icculus@10888
   743
icculus@10888
   744
static int
icculus@10888
   745
WASAPI_Init(SDL_AudioDriverImpl * impl)
icculus@10888
   746
{
icculus@11726
   747
    SDL_AtomicSet(&WASAPI_DefaultPlaybackGeneration, 1);
icculus@11726
   748
    SDL_AtomicSet(&WASAPI_DefaultCaptureGeneration, 1);
icculus@10888
   749
icculus@11726
   750
    if (WASAPI_PlatformInit() == -1) {
icculus@11040
   751
        return 0;
icculus@11010
   752
    }
icculus@10888
   753
icculus@10888
   754
    /* Set the function pointers */
icculus@10888
   755
    impl->DetectDevices = WASAPI_DetectDevices;
icculus@10888
   756
    impl->ThreadInit = WASAPI_ThreadInit;
icculus@10888
   757
    impl->ThreadDeinit = WASAPI_ThreadDeinit;
icculus@11726
   758
    impl->BeginLoopIteration = WASAPI_BeginLoopIteration;
icculus@10888
   759
    impl->OpenDevice = WASAPI_OpenDevice;
icculus@10888
   760
    impl->PlayDevice = WASAPI_PlayDevice;
icculus@10888
   761
    impl->WaitDevice = WASAPI_WaitDevice;
icculus@10888
   762
    impl->GetPendingBytes = WASAPI_GetPendingBytes;
icculus@10888
   763
    impl->GetDeviceBuf = WASAPI_GetDeviceBuf;
icculus@10888
   764
    impl->CaptureFromDevice = WASAPI_CaptureFromDevice;
icculus@10888
   765
    impl->FlushCapture = WASAPI_FlushCapture;
icculus@10888
   766
    impl->CloseDevice = WASAPI_CloseDevice;
icculus@10888
   767
    impl->Deinitialize = WASAPI_Deinitialize;
icculus@10888
   768
    impl->HasCaptureSupport = 1;
icculus@10888
   769
icculus@10888
   770
    return 1;   /* this audio target is available. */
icculus@10888
   771
}
icculus@10888
   772
icculus@10888
   773
AudioBootStrap WASAPI_bootstrap = {
icculus@10888
   774
    "wasapi", "WASAPI", WASAPI_Init, 0
icculus@10888
   775
};
icculus@10888
   776
icculus@10888
   777
#endif  /* SDL_AUDIO_DRIVER_WASAPI */
icculus@10888
   778
icculus@10888
   779
/* vi: set ts=4 sw=4 expandtab: */