dsound.c 35.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* DirectSound
 *
 * Copyright 1998 Marcus Meissner
 * Copyright 1998 Rob Riggs
 * Copyright 2000-2002 TransGaming Technologies, Inc.
 * Copyright 2004 Robert Reif
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 22
 */

23
#include <assert.h>
24 25 26
#include <stdarg.h>
#include <stdio.h>

27
#define COBJMACROS
28 29 30 31
#define NONAMELESSSTRUCT
#define NONAMELESSUNION
#include "windef.h"
#include "winbase.h"
32
#include "winuser.h"
33 34
#include "winternl.h"
#include "mmddk.h"
35 36 37 38
#include "wingdi.h"
#include "mmreg.h"
#include "ks.h"
#include "ksmedia.h"
39 40 41 42 43 44
#include "wine/debug.h"
#include "dsound.h"
#include "dsound_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(dsound);

45
typedef struct IDirectSoundImpl {
46
    IUnknown            IUnknown_inner;
47
    IDirectSound8       IDirectSound8_iface;
48
    IUnknown           *outer_unk;      /* internal */
49
    LONG                ref, refds, numIfaces;
50
    DirectSoundDevice  *device;
51
    BOOL                has_ds8;
52
} IDirectSoundImpl;
53

54
static const char * dumpCooperativeLevel(DWORD level)
55 56 57 58 59 60 61 62 63
{
#define LE(x) case x: return #x
    switch (level) {
        LE(DSSCL_NORMAL);
        LE(DSSCL_PRIORITY);
        LE(DSSCL_EXCLUSIVE);
        LE(DSSCL_WRITEPRIMARY);
    }
#undef LE
64
    return wine_dbg_sprintf("Unknown(%08x)", level);
65 66
}

67 68 69
static void _dump_DSCAPS(DWORD xmask) {
    struct {
        DWORD   mask;
70
        const char    *name;
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    } flags[] = {
#define FE(x) { x, #x },
        FE(DSCAPS_PRIMARYMONO)
        FE(DSCAPS_PRIMARYSTEREO)
        FE(DSCAPS_PRIMARY8BIT)
        FE(DSCAPS_PRIMARY16BIT)
        FE(DSCAPS_CONTINUOUSRATE)
        FE(DSCAPS_EMULDRIVER)
        FE(DSCAPS_CERTIFIED)
        FE(DSCAPS_SECONDARYMONO)
        FE(DSCAPS_SECONDARYSTEREO)
        FE(DSCAPS_SECONDARY8BIT)
        FE(DSCAPS_SECONDARY16BIT)
#undef FE
    };
86
    unsigned int     i;
87 88 89

    for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
        if ((flags[i].mask & xmask) == flags[i].mask)
90
            TRACE("%s ",flags[i].name);
91 92
}

93 94 95
static void _dump_DSBCAPS(DWORD xmask) {
    struct {
        DWORD   mask;
96
        const char    *name;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    } flags[] = {
#define FE(x) { x, #x },
        FE(DSBCAPS_PRIMARYBUFFER)
        FE(DSBCAPS_STATIC)
        FE(DSBCAPS_LOCHARDWARE)
        FE(DSBCAPS_LOCSOFTWARE)
        FE(DSBCAPS_CTRL3D)
        FE(DSBCAPS_CTRLFREQUENCY)
        FE(DSBCAPS_CTRLPAN)
        FE(DSBCAPS_CTRLVOLUME)
        FE(DSBCAPS_CTRLPOSITIONNOTIFY)
        FE(DSBCAPS_STICKYFOCUS)
        FE(DSBCAPS_GLOBALFOCUS)
        FE(DSBCAPS_GETCURRENTPOSITION2)
        FE(DSBCAPS_MUTE3DATMAXDISTANCE)
#undef FE
    };
114
    unsigned int     i;
115 116 117

    for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
        if ((flags[i].mask & xmask) == flags[i].mask)
118
            TRACE("%s ",flags[i].name);
119 120
}

121
static void directsound_destroy(IDirectSoundImpl *This)
122
{
123 124 125 126
    if (This->device)
        DirectSoundDevice_Release(This->device);
    HeapFree(GetProcessHeap(),0,This);
    TRACE("(%p) released\n", This);
127 128
}

129
/*******************************************************************************
130
 *      IUnknown Implementation for DirectSound
131
 */
132
static inline IDirectSoundImpl *impl_from_IUnknown(IUnknown *iface)
133
{
134
    return CONTAINING_RECORD(iface, IDirectSoundImpl, IUnknown_inner);
135
}
136

137
static HRESULT WINAPI IUnknownImpl_QueryInterface(IUnknown *iface, REFIID riid, void **ppv)
138
{
139
    IDirectSoundImpl *This = impl_from_IUnknown(iface);
140

141
    TRACE("(%p,%s,%p)\n", This, debugstr_guid(riid), ppv);
142 143 144 145 146 147 148 149

    if (!ppv) {
        WARN("invalid parameter\n");
        return E_INVALIDARG;
    }
    *ppv = NULL;

    if (IsEqualIID(riid, &IID_IUnknown))
150
        *ppv = &This->IUnknown_inner;
151 152 153 154 155 156 157 158 159 160
    else if (IsEqualIID(riid, &IID_IDirectSound) ||
            (IsEqualIID(riid, &IID_IDirectSound8) && This->has_ds8))
        *ppv = &This->IDirectSound8_iface;
    else {
        WARN("unknown IID %s\n", debugstr_guid(riid));
        return E_NOINTERFACE;
    }

    IUnknown_AddRef((IUnknown*)*ppv);
    return S_OK;
161
}
162

163
static ULONG WINAPI IUnknownImpl_AddRef(IUnknown *iface)
164
{
165 166
    IDirectSoundImpl *This = impl_from_IUnknown(iface);
    ULONG ref = InterlockedIncrement(&This->ref);
167

168
    TRACE("(%p) ref=%d\n", This, ref);
169

170 171
    if(ref == 1)
        InterlockedIncrement(&This->numIfaces);
172

173 174
    return ref;
}
175

176 177 178 179
static ULONG WINAPI IUnknownImpl_Release(IUnknown *iface)
{
    IDirectSoundImpl *This = impl_from_IUnknown(iface);
    ULONG ref = InterlockedDecrement(&This->ref);
180

181
    TRACE("(%p) ref=%d\n", This, ref);
182

183 184
    if (!ref && !InterlockedDecrement(&This->numIfaces))
        directsound_destroy(This);
185

186
    return ref;
187
}
188

189 190 191 192 193 194 195
static const IUnknownVtbl unk_vtbl =
{
    IUnknownImpl_QueryInterface,
    IUnknownImpl_AddRef,
    IUnknownImpl_Release
};

196
/*******************************************************************************
197
 *      IDirectSound and IDirectSound8 Implementation
198
 */
199 200 201 202 203
static inline IDirectSoundImpl *impl_from_IDirectSound8(IDirectSound8 *iface)
{
    return CONTAINING_RECORD(iface, IDirectSoundImpl, IDirectSound8_iface);
}

204
static HRESULT WINAPI IDirectSound8Impl_QueryInterface(IDirectSound8 *iface, REFIID riid,
205
        void **ppv)
206
{
207 208
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
    TRACE("(%p,%s,%p)\n", This, debugstr_guid(riid), ppv);
209
    return IUnknown_QueryInterface(This->outer_unk, riid, ppv);
210
}
211

212
static ULONG WINAPI IDirectSound8Impl_AddRef(IDirectSound8 *iface)
213
{
214 215 216 217 218 219 220 221
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
    ULONG ref = InterlockedIncrement(&This->refds);

    TRACE("(%p) refds=%d\n", This, ref);

    if(ref == 1)
        InterlockedIncrement(&This->numIfaces);

222 223 224
    return ref;
}

225
static ULONG WINAPI IDirectSound8Impl_Release(IDirectSound8 *iface)
226
{
227 228 229 230 231 232 233 234
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
    ULONG ref = InterlockedDecrement(&(This->refds));

    TRACE("(%p) refds=%d\n", This, ref);

    if (!ref && !InterlockedDecrement(&This->numIfaces))
        directsound_destroy(This);

235
    return ref;
236
}
237

238 239
static HRESULT WINAPI IDirectSound8Impl_CreateSoundBuffer(IDirectSound8 *iface,
        const DSBUFFERDESC *dsbd, IDirectSoundBuffer **ppdsb, IUnknown *lpunk)
240
{
241 242
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
    TRACE("(%p,%p,%p,%p)\n", This, dsbd, ppdsb, lpunk);
243
    return DirectSoundDevice_CreateSoundBuffer(This->device, dsbd, ppdsb, lpunk, This->has_ds8);
244
}
245

246
static HRESULT WINAPI IDirectSound8Impl_GetCaps(IDirectSound8 *iface, DSCAPS *dscaps)
247
{
248
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

    TRACE("(%p, %p)\n", This, dscaps);

    if (!This->device) {
        WARN("not initialized\n");
        return DSERR_UNINITIALIZED;
    }
    if (!dscaps) {
        WARN("invalid parameter: dscaps = NULL\n");
        return DSERR_INVALIDPARAM;
    }
    if (dscaps->dwSize < sizeof(*dscaps)) {
        WARN("invalid parameter: dscaps->dwSize = %d\n", dscaps->dwSize);
        return DSERR_INVALIDPARAM;
    }

    dscaps->dwFlags                        = This->device->drvcaps.dwFlags;
    dscaps->dwMinSecondarySampleRate       = This->device->drvcaps.dwMinSecondarySampleRate;
    dscaps->dwMaxSecondarySampleRate       = This->device->drvcaps.dwMaxSecondarySampleRate;
    dscaps->dwPrimaryBuffers               = This->device->drvcaps.dwPrimaryBuffers;
    dscaps->dwMaxHwMixingAllBuffers        = This->device->drvcaps.dwMaxHwMixingAllBuffers;
    dscaps->dwMaxHwMixingStaticBuffers     = This->device->drvcaps.dwMaxHwMixingStaticBuffers;
    dscaps->dwMaxHwMixingStreamingBuffers  = This->device->drvcaps.dwMaxHwMixingStreamingBuffers;
    dscaps->dwFreeHwMixingAllBuffers       = This->device->drvcaps.dwFreeHwMixingAllBuffers;
    dscaps->dwFreeHwMixingStaticBuffers    = This->device->drvcaps.dwFreeHwMixingStaticBuffers;
    dscaps->dwFreeHwMixingStreamingBuffers = This->device->drvcaps.dwFreeHwMixingStreamingBuffers;
    dscaps->dwMaxHw3DAllBuffers            = This->device->drvcaps.dwMaxHw3DAllBuffers;
    dscaps->dwMaxHw3DStaticBuffers         = This->device->drvcaps.dwMaxHw3DStaticBuffers;
    dscaps->dwMaxHw3DStreamingBuffers      = This->device->drvcaps.dwMaxHw3DStreamingBuffers;
    dscaps->dwFreeHw3DAllBuffers           = This->device->drvcaps.dwFreeHw3DAllBuffers;
    dscaps->dwFreeHw3DStaticBuffers        = This->device->drvcaps.dwFreeHw3DStaticBuffers;
    dscaps->dwFreeHw3DStreamingBuffers     = This->device->drvcaps.dwFreeHw3DStreamingBuffers;
    dscaps->dwTotalHwMemBytes              = This->device->drvcaps.dwTotalHwMemBytes;
    dscaps->dwFreeHwMemBytes               = This->device->drvcaps.dwFreeHwMemBytes;
    dscaps->dwMaxContigFreeHwMemBytes      = This->device->drvcaps.dwMaxContigFreeHwMemBytes;
    dscaps->dwUnlockTransferRateHwBuffers  = This->device->drvcaps.dwUnlockTransferRateHwBuffers;
    dscaps->dwPlayCpuOverheadSwBuffers     = This->device->drvcaps.dwPlayCpuOverheadSwBuffers;

    if (TRACE_ON(dsound)) {
        TRACE("(flags=0x%08x:\n", dscaps->dwFlags);
        _dump_DSCAPS(dscaps->dwFlags);
        TRACE(")\n");
    }

    return DS_OK;
294
}
295

296 297
static HRESULT WINAPI IDirectSound8Impl_DuplicateSoundBuffer(IDirectSound8 *iface,
        IDirectSoundBuffer *psb, IDirectSoundBuffer **ppdsb)
298
{
299 300 301
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
    TRACE("(%p,%p,%p)\n", This, psb, ppdsb);
    return DirectSoundDevice_DuplicateSoundBuffer(This->device, psb, ppdsb);
302
}
303

304 305
static HRESULT WINAPI IDirectSound8Impl_SetCooperativeLevel(IDirectSound8 *iface, HWND hwnd,
        DWORD level)
306
{
307
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
308 309 310
    DirectSoundDevice *device = This->device;
    DWORD oldlevel;
    HRESULT hr = S_OK;
311

312
    TRACE("(%p,%p,%s)\n", This, hwnd, dumpCooperativeLevel(level));
313

314
    if (!device) {
315 316 317 318 319 320
        WARN("not initialized\n");
        return DSERR_UNINITIALIZED;
    }

    if (level == DSSCL_PRIORITY || level == DSSCL_EXCLUSIVE) {
        WARN("level=%s not fully supported\n",
321
             level==DSSCL_PRIORITY ? "DSSCL_PRIORITY" : "DSSCL_EXCLUSIVE");
322 323
    }

324 325 326 327 328 329 330 331 332 333 334 335 336 337
    RtlAcquireResourceExclusive(&device->buffer_list_lock, TRUE);
    EnterCriticalSection(&device->mixlock);
    oldlevel = device->priolevel;
    device->priolevel = level;
    if ((level == DSSCL_WRITEPRIMARY) != (oldlevel == DSSCL_WRITEPRIMARY)) {
        hr = DSOUND_ReopenDevice(device, level == DSSCL_WRITEPRIMARY);
        if (FAILED(hr))
            device->priolevel = oldlevel;
        else
            DSOUND_PrimaryOpen(device);
    }
    LeaveCriticalSection(&device->mixlock);
    RtlReleaseResource(&device->buffer_list_lock);
    return hr;
338 339
}

340
static HRESULT WINAPI IDirectSound8Impl_Compact(IDirectSound8 *iface)
341
{
342
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
343

344
    TRACE("(%p)\n", This);
345 346 347 348 349 350 351 352 353 354 355

    if (!This->device) {
        WARN("not initialized\n");
        return DSERR_UNINITIALIZED;
    }

    if (This->device->priolevel < DSSCL_PRIORITY) {
        WARN("incorrect priority level\n");
        return DSERR_PRIOLEVELNEEDED;
    }
    return DS_OK;
356 357
}

358
static HRESULT WINAPI IDirectSound8Impl_GetSpeakerConfig(IDirectSound8 *iface, DWORD *config)
359
{
360
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

    TRACE("(%p, %p)\n", This, config);

    if (!This->device) {
        WARN("not initialized\n");
        return DSERR_UNINITIALIZED;
    }
    if (!config) {
        WARN("invalid parameter: config == NULL\n");
        return DSERR_INVALIDPARAM;
    }

    WARN("not fully functional\n");
    *config = This->device->speaker_config;
    return DS_OK;
376 377
}

378
static HRESULT WINAPI IDirectSound8Impl_SetSpeakerConfig(IDirectSound8 *iface, DWORD config)
379
{
380
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
381

382
    TRACE("(%p,0x%08x)\n", This, config);
383 384 385 386 387 388 389 390 391

    if (!This->device) {
        WARN("not initialized\n");
        return DSERR_UNINITIALIZED;
    }

    This->device->speaker_config = config;
    WARN("not fully functional\n");
    return DS_OK;
392
}
393

394
static HRESULT WINAPI IDirectSound8Impl_Initialize(IDirectSound8 *iface, const GUID *lpcGuid)
395
{
396
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
397
    TRACE("(%p, %s)\n", This, debugstr_guid(lpcGuid));
398
    return DirectSoundDevice_Initialize(&This->device, lpcGuid);
399
}
400

401
static HRESULT WINAPI IDirectSound8Impl_VerifyCertification(IDirectSound8 *iface, DWORD *certified)
402
{
403
    IDirectSoundImpl *This = impl_from_IDirectSound8(iface);
404 405 406 407 408 409 410 411 412 413 414 415 416 417

    TRACE("(%p, %p)\n", This, certified);

    if (!This->device) {
        WARN("not initialized\n");
        return DSERR_UNINITIALIZED;
    }

    if (This->device->drvcaps.dwFlags & DSCAPS_CERTIFIED)
        *certified = DS_CERTIFIED;
    else
        *certified = DS_UNCERTIFIED;

    return DS_OK;
418
}
419

420 421 422 423 424 425 426 427 428 429 430 431 432 433
static const IDirectSound8Vtbl ds8_vtbl =
{
    IDirectSound8Impl_QueryInterface,
    IDirectSound8Impl_AddRef,
    IDirectSound8Impl_Release,
    IDirectSound8Impl_CreateSoundBuffer,
    IDirectSound8Impl_GetCaps,
    IDirectSound8Impl_DuplicateSoundBuffer,
    IDirectSound8Impl_SetCooperativeLevel,
    IDirectSound8Impl_Compact,
    IDirectSound8Impl_GetSpeakerConfig,
    IDirectSound8Impl_SetSpeakerConfig,
    IDirectSound8Impl_Initialize,
    IDirectSound8Impl_VerifyCertification
434 435
};

436
HRESULT IDirectSoundImpl_Create(IUnknown *outer_unk, REFIID riid, void **ppv, BOOL has_ds8)
437 438
{
    IDirectSoundImpl *obj;
439 440 441
    HRESULT hr;

    TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
442 443 444 445 446 447 448 449

    *ppv = NULL;
    obj = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*obj));
    if (!obj) {
        WARN("out of memory\n");
        return DSERR_OUTOFMEMORY;
    }

450 451
    setup_dsound_options();

452
    obj->IUnknown_inner.lpVtbl = &unk_vtbl;
453
    obj->IDirectSound8_iface.lpVtbl = &ds8_vtbl;
454
    obj->ref = 1;
455
    obj->refds = 0;
456
    obj->numIfaces = 1;
457 458 459
    obj->device = NULL;
    obj->has_ds8 = has_ds8;

460 461 462 463 464 465 466 467
    /* COM aggregation supported only internally */
    if (outer_unk)
        obj->outer_unk = outer_unk;
    else
        obj->outer_unk = &obj->IUnknown_inner;

    hr = IUnknown_QueryInterface(&obj->IUnknown_inner, riid, ppv);
    IUnknown_Release(&obj->IUnknown_inner);
468 469

    return hr;
470 471
}

472
HRESULT DSOUND_Create(REFIID riid, void **ppv)
473
{
474
    return IDirectSoundImpl_Create(NULL, riid, ppv, FALSE);
475
}
476

477 478
HRESULT DSOUND_Create8(REFIID riid, void **ppv)
{
479
    return IDirectSoundImpl_Create(NULL, riid, ppv, TRUE);
480 481
}

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
/*******************************************************************************
 *		DirectSoundCreate (DSOUND.1)
 *
 *  Creates and initializes a DirectSound interface.
 *
 *  PARAMS
 *     lpcGUID   [I] Address of the GUID that identifies the sound device.
 *     ppDS      [O] Address of a variable to receive the interface pointer.
 *     pUnkOuter [I] Must be NULL.
 *
 *  RETURNS
 *     Success: DS_OK
 *     Failure: DSERR_ALLOCATED, DSERR_INVALIDPARAM, DSERR_NOAGGREGATION,
 *              DSERR_NODRIVER, DSERR_OUTOFMEMORY
 */
HRESULT WINAPI DirectSoundCreate(
    LPCGUID lpcGUID,
    LPDIRECTSOUND *ppDS,
    IUnknown *pUnkOuter)
501
{
502 503
    HRESULT hr;
    LPDIRECTSOUND pDS;
504

505
    TRACE("(%s,%p,%p)\n",debugstr_guid(lpcGUID),ppDS,pUnkOuter);
506

507 508
    if (ppDS == NULL) {
        WARN("invalid parameter: ppDS == NULL\n");
509 510 511
        return DSERR_INVALIDPARAM;
    }

512 513 514 515
    if (pUnkOuter != NULL) {
        WARN("invalid parameter: pUnkOuter != NULL\n");
        *ppDS = 0;
        return DSERR_INVALIDPARAM;
516 517
    }

518
    hr = DSOUND_Create(&IID_IDirectSound, (void **)&pDS);
519 520 521 522 523 524 525 526 527
    if (hr == DS_OK) {
        hr = IDirectSound_Initialize(pDS, lpcGUID);
        if (hr != DS_OK) {
            if (hr != DSERR_ALREADYINITIALIZED) {
                IDirectSound_Release(pDS);
                pDS = 0;
            } else
                hr = DS_OK;
        }
528 529
    }

530
    *ppDS = pDS;
531

532
    return hr;
533 534
}

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
/*******************************************************************************
 *        DirectSoundCreate8 (DSOUND.11)
 *
 *  Creates and initializes a DirectSound8 interface.
 *
 *  PARAMS
 *     lpcGUID   [I] Address of the GUID that identifies the sound device.
 *     ppDS      [O] Address of a variable to receive the interface pointer.
 *     pUnkOuter [I] Must be NULL.
 *
 *  RETURNS
 *     Success: DS_OK
 *     Failure: DSERR_ALLOCATED, DSERR_INVALIDPARAM, DSERR_NOAGGREGATION,
 *              DSERR_NODRIVER, DSERR_OUTOFMEMORY
 */
HRESULT WINAPI DirectSoundCreate8(
    LPCGUID lpcGUID,
    LPDIRECTSOUND8 *ppDS,
    IUnknown *pUnkOuter)
554
{
555 556
    HRESULT hr;
    LPDIRECTSOUND8 pDS;
557

558
    TRACE("(%s,%p,%p)\n",debugstr_guid(lpcGUID),ppDS,pUnkOuter);
559

560 561
    if (ppDS == NULL) {
        WARN("invalid parameter: ppDS == NULL\n");
562 563 564
        return DSERR_INVALIDPARAM;
    }

565 566 567
    if (pUnkOuter != NULL) {
        WARN("invalid parameter: pUnkOuter != NULL\n");
        *ppDS = 0;
568 569 570
        return DSERR_INVALIDPARAM;
    }

571
    hr = DSOUND_Create8(&IID_IDirectSound8, (void **)&pDS);
572 573 574 575 576 577 578 579 580
    if (hr == DS_OK) {
        hr = IDirectSound8_Initialize(pDS, lpcGUID);
        if (hr != DS_OK) {
            if (hr != DSERR_ALREADYINITIALIZED) {
                IDirectSound8_Release(pDS);
                pDS = 0;
            } else
                hr = DS_OK;
        }
581 582
    }

583
    *ppDS = pDS;
584

585
    return hr;
586 587 588
}

/*******************************************************************************
589
 *        DirectSoundDevice
590
 */
591
static HRESULT DirectSoundDevice_Create(DirectSoundDevice ** ppDevice)
592
{
593 594
    DirectSoundDevice * device;
    TRACE("(%p)\n", ppDevice);
595

596 597 598 599 600 601
    /* Allocate memory */
    device = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(DirectSoundDevice));
    if (device == NULL) {
        WARN("out of memory\n");
        return DSERR_OUTOFMEMORY;
    }
602

603 604 605
    device->ref            = 1;
    device->priolevel      = DSSCL_NORMAL;
    device->state          = STATE_STOPPED;
606
    device->speaker_config = DSSPEAKER_COMBINED(DSSPEAKER_STEREO, DSSPEAKER_GEOMETRY_WIDE);
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625

    /* 3D listener initial parameters */
    device->ds3dl.dwSize   = sizeof(DS3DLISTENER);
    device->ds3dl.vPosition.x = 0.0;
    device->ds3dl.vPosition.y = 0.0;
    device->ds3dl.vPosition.z = 0.0;
    device->ds3dl.vVelocity.x = 0.0;
    device->ds3dl.vVelocity.y = 0.0;
    device->ds3dl.vVelocity.z = 0.0;
    device->ds3dl.vOrientFront.x = 0.0;
    device->ds3dl.vOrientFront.y = 0.0;
    device->ds3dl.vOrientFront.z = 1.0;
    device->ds3dl.vOrientTop.x = 0.0;
    device->ds3dl.vOrientTop.y = 1.0;
    device->ds3dl.vOrientTop.z = 0.0;
    device->ds3dl.flDistanceFactor = DS3D_DEFAULTDISTANCEFACTOR;
    device->ds3dl.flRolloffFactor = DS3D_DEFAULTROLLOFFFACTOR;
    device->ds3dl.flDopplerFactor = DS3D_DEFAULTDOPPLERFACTOR;

626 627
    device->prebuf = ds_snd_queue_max;
    device->guid = GUID_NULL;
628 629

    /* Set default wave format (may need it for waveOutOpen) */
630 631 632
    device->pwfx = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(WAVEFORMATEXTENSIBLE));
    device->primary_pwfx = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(WAVEFORMATEXTENSIBLE));
    if (!device->pwfx || !device->primary_pwfx) {
633
        WARN("out of memory\n");
634 635
        HeapFree(GetProcessHeap(),0,device->primary_pwfx);
        HeapFree(GetProcessHeap(),0,device->pwfx);
636 637
        HeapFree(GetProcessHeap(),0,device);
        return DSERR_OUTOFMEMORY;
638 639
    }

640
    device->pwfx->wFormatTag = WAVE_FORMAT_PCM;
641 642
    device->pwfx->nSamplesPerSec = 22050;
    device->pwfx->wBitsPerSample = 8;
643 644 645 646
    device->pwfx->nChannels = 2;
    device->pwfx->nBlockAlign = device->pwfx->wBitsPerSample * device->pwfx->nChannels / 8;
    device->pwfx->nAvgBytesPerSec = device->pwfx->nSamplesPerSec * device->pwfx->nBlockAlign;
    device->pwfx->cbSize = 0;
647
    memcpy(device->primary_pwfx, device->pwfx, sizeof(*device->pwfx));
648

649
    InitializeCriticalSection(&(device->mixlock));
650
    device->mixlock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": DirectSoundDevice.mixlock");
651

652 653 654 655 656
    RtlInitializeResource(&(device->buffer_list_lock));

   *ppDevice = device;

    return DS_OK;
657 658
}

659
static ULONG DirectSoundDevice_AddRef(DirectSoundDevice * device)
660
{
661
    ULONG ref = InterlockedIncrement(&(device->ref));
662
    TRACE("(%p) ref was %d\n", device, ref - 1);
663
    return ref;
664 665
}

666
ULONG DirectSoundDevice_Release(DirectSoundDevice * device)
667
{
668 669
    HRESULT hr;
    ULONG ref = InterlockedDecrement(&(device->ref));
670
    TRACE("(%p) ref was %u\n", device, ref + 1);
671 672 673
    if (!ref) {
        int i;

674 675 676 677 678 679
        SetEvent(device->sleepev);
        if (device->thread) {
            WaitForSingleObject(device->thread, INFINITE);
            CloseHandle(device->thread);
        }
        CloseHandle(device->sleepev);
680

681 682 683 684
        EnterCriticalSection(&DSOUND_renderers_lock);
        list_remove(&device->entry);
        LeaveCriticalSection(&DSOUND_renderers_lock);

685 686 687 688
        /* It is allowed to release this object even when buffers are playing */
        if (device->buffers) {
            WARN("%d secondary buffers not released\n", device->nrofbuffers);
            for( i=0;i<device->nrofbuffers;i++)
689
                secondarybuffer_destroy(device->buffers[i]);
690 691 692 693 694 695
        }

        hr = DSOUND_PrimaryDestroy(device);
        if (hr != DS_OK)
            WARN("DSOUND_PrimaryDestroy failed\n");

696 697 698 699 700 701 702 703
        if(device->client)
            IAudioClient_Release(device->client);
        if(device->render)
            IAudioRenderClient_Release(device->render);
        if(device->clock)
            IAudioClock_Release(device->clock);
        if(device->volume)
            IAudioStreamVolume_Release(device->volume);
704

705 706
        HeapFree(GetProcessHeap(), 0, device->tmp_buffer);
        HeapFree(GetProcessHeap(), 0, device->mix_buffer);
707
        HeapFree(GetProcessHeap(), 0, device->buffer);
708 709 710 711 712 713 714
        RtlDeleteResource(&device->buffer_list_lock);
        device->mixlock.DebugInfo->Spare[0] = 0;
        DeleteCriticalSection(&device->mixlock);
        HeapFree(GetProcessHeap(),0,device);
        TRACE("(%p) released\n", device);
    }
    return ref;
715 716
}

717
BOOL DSOUND_check_supported(IAudioClient *client, DWORD rate,
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
        DWORD depth, WORD channels)
{
    WAVEFORMATEX fmt, *junk;
    HRESULT hr;

    fmt.wFormatTag = WAVE_FORMAT_PCM;
    fmt.nChannels = channels;
    fmt.nSamplesPerSec = rate;
    fmt.wBitsPerSample = depth;
    fmt.nBlockAlign = (channels * depth) / 8;
    fmt.nAvgBytesPerSec = rate * fmt.nBlockAlign;
    fmt.cbSize = 0;

    hr = IAudioClient_IsFormatSupported(client, AUDCLNT_SHAREMODE_SHARED, &fmt, &junk);
    if(SUCCEEDED(hr))
        CoTaskMemFree(junk);

    return hr == S_OK;
}

738
HRESULT DirectSoundDevice_Initialize(DirectSoundDevice ** ppDevice, LPCGUID lpcGUID)
739
{
740 741
    HRESULT hr = DS_OK;
    GUID devGUID;
742 743
    DirectSoundDevice *device;
    IMMDevice *mmdevice;
744

745 746 747 748 749 750 751 752 753 754 755
    TRACE("(%p,%s)\n",ppDevice,debugstr_guid(lpcGUID));

    if (*ppDevice != NULL) {
        WARN("already initialized\n");
        return DSERR_ALREADYINITIALIZED;
    }

    /* Default device? */
    if (!lpcGUID || IsEqualGUID(lpcGUID, &GUID_NULL))
        lpcGUID = &DSDEVID_DefaultPlayback;

756 757 758 759
    if(IsEqualGUID(lpcGUID, &DSDEVID_DefaultCapture) ||
            IsEqualGUID(lpcGUID, &DSDEVID_DefaultVoiceCapture))
        return DSERR_NODRIVER;

760 761 762 763 764
    if (GetDeviceID(lpcGUID, &devGUID) != DS_OK) {
        WARN("invalid parameter: lpcGUID\n");
        return DSERR_INVALIDPARAM;
    }

765 766 767
    hr = get_mmdevice(eRender, &devGUID, &mmdevice);
    if(FAILED(hr))
        return hr;
768

769
    EnterCriticalSection(&DSOUND_renderers_lock);
770

771 772 773
    LIST_FOR_EACH_ENTRY(device, &DSOUND_renderers, DirectSoundDevice, entry){
        if(IsEqualGUID(&device->guid, &devGUID)){
            IMMDevice_Release(mmdevice);
774 775
            DirectSoundDevice_AddRef(device);
            *ppDevice = device;
776
            LeaveCriticalSection(&DSOUND_renderers_lock);
777 778 779 780
            return DS_OK;
        }
    }

781 782 783 784 785 786 787 788 789
    hr = DirectSoundDevice_Create(&device);
    if(FAILED(hr)){
        WARN("DirectSoundDevice_Create failed\n");
        IMMDevice_Release(mmdevice);
        LeaveCriticalSection(&DSOUND_renderers_lock);
        return hr;
    }

    device->mmdevice = mmdevice;
790
    device->guid = devGUID;
791
    device->sleepev = CreateEventW(0, 0, 0, 0);
792

793 794
    hr = DSOUND_ReopenDevice(device, FALSE);
    if (FAILED(hr))
795
    {
796 797 798
        HeapFree(GetProcessHeap(), 0, device);
        LeaveCriticalSection(&DSOUND_renderers_lock);
        IMMDevice_Release(mmdevice);
799 800
        WARN("DSOUND_ReopenDevice failed: %08x\n", hr);
        return hr;
801 802
    }

803 804
    ZeroMemory(&device->drvcaps, sizeof(device->drvcaps));

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
    if(DSOUND_check_supported(device->client, 11025, 8, 1) ||
            DSOUND_check_supported(device->client, 22050, 8, 1) ||
            DSOUND_check_supported(device->client, 44100, 8, 1) ||
            DSOUND_check_supported(device->client, 48000, 8, 1) ||
            DSOUND_check_supported(device->client, 96000, 8, 1))
        device->drvcaps.dwFlags |= DSCAPS_PRIMARY8BIT | DSCAPS_PRIMARYMONO;

    if(DSOUND_check_supported(device->client, 11025, 16, 1) ||
            DSOUND_check_supported(device->client, 22050, 16, 1) ||
            DSOUND_check_supported(device->client, 44100, 16, 1) ||
            DSOUND_check_supported(device->client, 48000, 16, 1) ||
            DSOUND_check_supported(device->client, 96000, 16, 1))
        device->drvcaps.dwFlags |= DSCAPS_PRIMARY16BIT | DSCAPS_PRIMARYMONO;

    if(DSOUND_check_supported(device->client, 11025, 8, 2) ||
            DSOUND_check_supported(device->client, 22050, 8, 2) ||
            DSOUND_check_supported(device->client, 44100, 8, 2) ||
            DSOUND_check_supported(device->client, 48000, 8, 2) ||
            DSOUND_check_supported(device->client, 96000, 8, 2))
        device->drvcaps.dwFlags |= DSCAPS_PRIMARY8BIT | DSCAPS_PRIMARYSTEREO;

    if(DSOUND_check_supported(device->client, 11025, 16, 2) ||
            DSOUND_check_supported(device->client, 22050, 16, 2) ||
            DSOUND_check_supported(device->client, 44100, 16, 2) ||
            DSOUND_check_supported(device->client, 48000, 16, 2) ||
            DSOUND_check_supported(device->client, 96000, 16, 2))
        device->drvcaps.dwFlags |= DSCAPS_PRIMARY16BIT | DSCAPS_PRIMARYSTEREO;

833 834 835 836 837
    /* the dsound mixer supports all of the following */
    device->drvcaps.dwFlags |= DSCAPS_SECONDARY8BIT | DSCAPS_SECONDARY16BIT;
    device->drvcaps.dwFlags |= DSCAPS_SECONDARYMONO | DSCAPS_SECONDARYSTEREO;
    device->drvcaps.dwFlags |= DSCAPS_CONTINUOUSRATE;

838
    device->drvcaps.dwPrimaryBuffers = 1;
839 840
    device->drvcaps.dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
    device->drvcaps.dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
841 842 843
    device->drvcaps.dwMaxHwMixingAllBuffers = 1;
    device->drvcaps.dwMaxHwMixingStaticBuffers = 1;
    device->drvcaps.dwMaxHwMixingStreamingBuffers = 1;
844

845
    ZeroMemory(&device->volpan, sizeof(device->volpan));
846 847

    hr = DSOUND_PrimaryCreate(device);
848 849 850 851
    if (hr == DS_OK) {
        device->thread = CreateThread(0, 0, DSOUND_mixthread, device, 0, 0);
        SetThreadPriority(device->thread, THREAD_PRIORITY_TIME_CRITICAL);
    } else
852 853 854 855 856 857
        WARN("DSOUND_PrimaryCreate failed: %08x\n", hr);

    *ppDevice = device;
    list_add_tail(&DSOUND_renderers, &device->entry);

    LeaveCriticalSection(&DSOUND_renderers_lock);
858 859

    return hr;
860 861
}

862 863 864 865 866 867
HRESULT DirectSoundDevice_CreateSoundBuffer(
    DirectSoundDevice * device,
    LPCDSBUFFERDESC dsbd,
    LPLPDIRECTSOUNDBUFFER ppdsb,
    LPUNKNOWN lpunk,
    BOOL from8)
868
{
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
    HRESULT hres = DS_OK;
    TRACE("(%p,%p,%p,%p)\n",device,dsbd,ppdsb,lpunk);

    if (device == NULL) {
        WARN("not initialized\n");
        return DSERR_UNINITIALIZED;
    }

    if (dsbd == NULL) {
        WARN("invalid parameter: dsbd == NULL\n");
        return DSERR_INVALIDPARAM;
    }

    if (dsbd->dwSize != sizeof(DSBUFFERDESC) &&
        dsbd->dwSize != sizeof(DSBUFFERDESC1)) {
        WARN("invalid parameter: dsbd\n");
        return DSERR_INVALIDPARAM;
    }

    if (ppdsb == NULL) {
        WARN("invalid parameter: ppdsb == NULL\n");
        return DSERR_INVALIDPARAM;
    }
892
    *ppdsb = NULL;
893 894

    if (TRACE_ON(dsound)) {
895 896
        TRACE("(structsize=%d)\n",dsbd->dwSize);
        TRACE("(flags=0x%08x:\n",dsbd->dwFlags);
897
        _dump_DSBCAPS(dsbd->dwFlags);
Andrew Riedi's avatar
Andrew Riedi committed
898
        TRACE(")\n");
899
        TRACE("(bufferbytes=%d)\n",dsbd->dwBufferBytes);
900 901 902
        TRACE("(lpwfxFormat=%p)\n",dsbd->lpwfxFormat);
    }

903 904 905 906 907 908
    if (dsbd->dwFlags & DSBCAPS_LOCHARDWARE &&
            !(dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)) {
        TRACE("LOCHARDWARE is not supported, returning E_NOTIMPL\n");
        return E_NOTIMPL;
    }

909 910 911 912 913 914 915 916 917 918 919 920
    if (dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER) {
        if (dsbd->lpwfxFormat != NULL) {
            WARN("invalid parameter: dsbd->lpwfxFormat must be NULL for "
                 "primary buffer\n");
            return DSERR_INVALIDPARAM;
        }

        if (device->primary) {
            WARN("Primary Buffer already created\n");
            IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER8)(device->primary));
            *ppdsb = (LPDIRECTSOUNDBUFFER)(device->primary);
        } else {
921 922 923 924
            hres = primarybuffer_create(device, &device->primary, dsbd);
            if (device->primary) {
                *ppdsb = (IDirectSoundBuffer*)&device->primary->IDirectSoundBuffer8_iface;
                device->primary->dsbd.dwFlags &= ~(DSBCAPS_LOCHARDWARE | DSBCAPS_LOCSOFTWARE);
925
                device->primary->dsbd.dwFlags |= DSBCAPS_LOCSOFTWARE;
926 927
            } else
                WARN("primarybuffer_create() failed\n");
928 929 930
        }
    } else {
        IDirectSoundBufferImpl * dsb;
931
        WAVEFORMATEXTENSIBLE *pwfxe;
932 933 934 935 936 937

        if (dsbd->lpwfxFormat == NULL) {
            WARN("invalid parameter: dsbd->lpwfxFormat can't be NULL for "
                 "secondary buffer\n");
            return DSERR_INVALIDPARAM;
        }
938 939 940 941
        pwfxe = (WAVEFORMATEXTENSIBLE*)dsbd->lpwfxFormat;

        if (pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
        {
942
            /* check if cbSize is at least 22 bytes */
943 944
            if (pwfxe->Format.cbSize < (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)))
            {
945
                WARN("Too small a cbSize %u\n", pwfxe->Format.cbSize);
946 947 948
                return DSERR_INVALIDPARAM;
            }

949 950
            /* cbSize should be 22 bytes, with one possible exception */
            if (pwfxe->Format.cbSize > (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)) &&
951
                !((IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM) || IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) &&
952
                pwfxe->Format.cbSize == sizeof(WAVEFORMATEXTENSIBLE)))
953
            {
954
                WARN("Too big a cbSize %u\n", pwfxe->Format.cbSize);
955 956 957
                return DSERR_CONTROLUNAVAIL;
            }

958
            if ((!IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) && (!IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)))
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
            {
                if (!IsEqualGUID(&pwfxe->SubFormat, &GUID_NULL))
                    FIXME("SubFormat %s not supported right now.\n", debugstr_guid(&pwfxe->SubFormat));
                return DSERR_INVALIDPARAM;
            }
            if (pwfxe->Samples.wValidBitsPerSample > dsbd->lpwfxFormat->wBitsPerSample)
            {
                WARN("Samples.wValidBitsPerSample(%d) > Format.wBitsPerSample (%d)\n", pwfxe->Samples.wValidBitsPerSample, pwfxe->Format.wBitsPerSample);
                return DSERR_INVALIDPARAM;
            }
            if (pwfxe->Samples.wValidBitsPerSample && pwfxe->Samples.wValidBitsPerSample < dsbd->lpwfxFormat->wBitsPerSample)
            {
                FIXME("Non-packed formats not supported right now: %d/%d\n", pwfxe->Samples.wValidBitsPerSample, dsbd->lpwfxFormat->wBitsPerSample);
                return DSERR_CONTROLUNAVAIL;
            }
        }
975

976 977
        TRACE("(formattag=0x%04x,chans=%d,samplerate=%d,"
              "bytespersec=%d,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
978 979 980 981 982 983 984 985 986 987
              dsbd->lpwfxFormat->wFormatTag, dsbd->lpwfxFormat->nChannels,
              dsbd->lpwfxFormat->nSamplesPerSec,
              dsbd->lpwfxFormat->nAvgBytesPerSec,
              dsbd->lpwfxFormat->nBlockAlign,
              dsbd->lpwfxFormat->wBitsPerSample, dsbd->lpwfxFormat->cbSize);

        if (from8 && (dsbd->dwFlags & DSBCAPS_CTRL3D) && (dsbd->lpwfxFormat->nChannels != 1)) {
            WARN("invalid parameter: 3D buffer format must be mono\n");
            return DSERR_INVALIDPARAM;
        }
988

989
        hres = IDirectSoundBufferImpl_Create(device, &dsb, dsbd);
990 991 992 993
        if (dsb)
            *ppdsb = (IDirectSoundBuffer*)&dsb->IDirectSoundBuffer8_iface;
        else
            WARN("IDirectSoundBufferImpl_Create failed\n");
994 995 996
   }

   return hres;
997 998
}

999 1000 1001 1002
HRESULT DirectSoundDevice_DuplicateSoundBuffer(
    DirectSoundDevice * device,
    LPDIRECTSOUNDBUFFER psb,
    LPLPDIRECTSOUNDBUFFER ppdsb)
1003
{
1004 1005 1006
    HRESULT hres = DS_OK;
    IDirectSoundBufferImpl* dsb;
    TRACE("(%p,%p,%p)\n",device,psb,ppdsb);
1007

1008 1009 1010 1011
    if (device == NULL) {
        WARN("not initialized\n");
        return DSERR_UNINITIALIZED;
    }
1012

1013 1014
    if (psb == NULL) {
        WARN("invalid parameter: psb == NULL\n");
1015 1016 1017
        return DSERR_INVALIDPARAM;
    }

1018 1019
    if (ppdsb == NULL) {
        WARN("invalid parameter: ppdsb == NULL\n");
1020 1021 1022
        return DSERR_INVALIDPARAM;
    }

1023
    /* make sure we have a secondary buffer */
1024
    if (psb == (IDirectSoundBuffer *)&device->primary->IDirectSoundBuffer8_iface) {
1025 1026 1027
        WARN("trying to duplicate primary buffer\n");
        *ppdsb = NULL;
        return DSERR_INVALIDCALL;
1028 1029
    }

1030
    /* duplicate the actual buffer implementation */
1031 1032 1033 1034 1035
    hres = IDirectSoundBufferImpl_Duplicate(device, &dsb, (IDirectSoundBufferImpl*)psb);
    if (hres == DS_OK)
        *ppdsb = (IDirectSoundBuffer*)&dsb->IDirectSoundBuffer8_iface;
    else
        WARN("IDirectSoundBufferImpl_Duplicate failed\n");
1036

1037
    return hres;
1038 1039
}

1040 1041 1042 1043
/*
 * Add secondary buffer to buffer list.
 * Gets exclusive access to buffer for writing.
 */
1044
HRESULT DirectSoundDevice_AddBuffer(
Robert Reif's avatar
Robert Reif committed
1045
    DirectSoundDevice * device,
1046 1047 1048 1049 1050
    IDirectSoundBufferImpl * pDSB)
{
    IDirectSoundBufferImpl **newbuffers;
    HRESULT hr = DS_OK;

Robert Reif's avatar
Robert Reif committed
1051
    TRACE("(%p, %p)\n", device, pDSB);
1052

Robert Reif's avatar
Robert Reif committed
1053
    RtlAcquireResourceExclusive(&(device->buffer_list_lock), TRUE);
1054

Robert Reif's avatar
Robert Reif committed
1055 1056
    if (device->buffers)
        newbuffers = HeapReAlloc(GetProcessHeap(),0,device->buffers,sizeof(IDirectSoundBufferImpl*)*(device->nrofbuffers+1));
1057
    else
Robert Reif's avatar
Robert Reif committed
1058
        newbuffers = HeapAlloc(GetProcessHeap(),0,sizeof(IDirectSoundBufferImpl*)*(device->nrofbuffers+1));
1059 1060

    if (newbuffers) {
Robert Reif's avatar
Robert Reif committed
1061 1062 1063 1064
        device->buffers = newbuffers;
        device->buffers[device->nrofbuffers] = pDSB;
        device->nrofbuffers++;
        TRACE("buffer count is now %d\n", device->nrofbuffers);
1065
    } else {
Robert Reif's avatar
Robert Reif committed
1066
        ERR("out of memory for buffer list! Current buffer count is %d\n", device->nrofbuffers);
1067 1068 1069
        hr = DSERR_OUTOFMEMORY;
    }

Robert Reif's avatar
Robert Reif committed
1070
    RtlReleaseResource(&(device->buffer_list_lock));
1071 1072 1073 1074 1075 1076 1077 1078

    return hr;
}

/*
 * Remove secondary buffer from buffer list.
 * Gets exclusive access to buffer for writing.
 */
1079
void DirectSoundDevice_RemoveBuffer(DirectSoundDevice * device, IDirectSoundBufferImpl * pDSB)
1080 1081 1082
{
    int i;

Robert Reif's avatar
Robert Reif committed
1083
    TRACE("(%p, %p)\n", device, pDSB);
1084

Robert Reif's avatar
Robert Reif committed
1085
    RtlAcquireResourceExclusive(&(device->buffer_list_lock), TRUE);
1086

1087 1088 1089
    if (device->nrofbuffers == 1) {
        assert(device->buffers[0] == pDSB);
        HeapFree(GetProcessHeap(), 0, device->buffers);
Robert Reif's avatar
Robert Reif committed
1090
        device->buffers = NULL;
1091 1092 1093 1094 1095 1096 1097 1098
    } else {
        for (i = 0; i < device->nrofbuffers; i++) {
            if (device->buffers[i] == pDSB) {
                /* Put the last buffer of the list in the (now empty) position */
                device->buffers[i] = device->buffers[device->nrofbuffers - 1];
                break;
            }
        }
1099
    }
1100 1101
    device->nrofbuffers--;
    TRACE("buffer count is now %d\n", device->nrofbuffers);
1102

Robert Reif's avatar
Robert Reif committed
1103
    RtlReleaseResource(&(device->buffer_list_lock));
1104
}