dsoundrender.c 41.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Direct Sound Audio Renderer
 *
 * Copyright 2004 Christian Costa
 *
 * 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
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 */

#include "config.h"

#include "quartz_private.h"
#include "pin.h"

#include "uuids.h"
#include "vfwmsgs.h"
#include "windef.h"
#include "winbase.h"
#include "dshow.h"
#include "evcode.h"
#include "strmif.h"
#include "dsound.h"
34
#include "amaudio.h"
35 36 37 38 39 40

#include "wine/unicode.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(quartz);

41 42 43 44 45
/* NOTE: buffer can still be filled completely,
 * but we start waiting until only this amount is buffered
 */
static const REFERENCE_TIME DSoundRenderer_Max_Fill = 150 * 10000;

46 47
static const IBaseFilterVtbl DSoundRender_Vtbl;
static const IBasicAudioVtbl IBasicAudio_Vtbl;
48
static const IReferenceClockVtbl IReferenceClock_Vtbl;
49
static const IMediaSeekingVtbl IMediaSeeking_Vtbl;
50
static const IAMDirectSoundVtbl IAMDirectSound_Vtbl;
51
static const IAMFilterMiscFlagsVtbl IAMFilterMiscFlags_Vtbl;
52 53 54

typedef struct DSoundRenderImpl
{
55
    BaseRenderer renderer;
56
    BasicAudio basicAudio;
57

58 59 60
    IReferenceClock IReferenceClock_iface;
    IAMDirectSound IAMDirectSound_iface;
    IAMFilterMiscFlags IAMFilterMiscFlags_iface;
61

62
    IDirectSound8 *dsound;
63
    LPDIRECTSOUNDBUFFER dsbuffer;
64
    DWORD buf_size;
65
    DWORD in_loop;
66
    DWORD last_playpos, writepos;
67

68 69
    REFERENCE_TIME play_time;

70
    HANDLE blocked;
71

72 73
    LONG volume;
    LONG pan;
74 75 76

    DWORD threadid;
    HANDLE advisethread, thread_wait;
77 78
} DSoundRenderImpl;

79 80 81 82 83 84 85 86 87 88
static inline DSoundRenderImpl *impl_from_BaseRenderer(BaseRenderer *iface)
{
    return CONTAINING_RECORD(iface, DSoundRenderImpl, renderer);
}

static inline DSoundRenderImpl *impl_from_IBaseFilter(IBaseFilter *iface)
{
    return CONTAINING_RECORD(iface, DSoundRenderImpl, renderer.filter.IBaseFilter_iface);
}

89 90
static inline DSoundRenderImpl *impl_from_IBasicAudio(IBasicAudio *iface)
{
91
    return CONTAINING_RECORD(iface, DSoundRenderImpl, basicAudio.IBasicAudio_iface);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
}

static inline DSoundRenderImpl *impl_from_IReferenceClock(IReferenceClock *iface)
{
    return CONTAINING_RECORD(iface, DSoundRenderImpl, IReferenceClock_iface);
}

static inline DSoundRenderImpl *impl_from_IAMDirectSound(IAMDirectSound *iface)
{
    return CONTAINING_RECORD(iface, DSoundRenderImpl, IAMDirectSound_iface);
}

static inline DSoundRenderImpl *impl_from_IAMFilterMiscFlags(IAMFilterMiscFlags *iface)
{
    return CONTAINING_RECORD(iface, DSoundRenderImpl, IAMFilterMiscFlags_iface);
}

109
static REFERENCE_TIME time_from_pos(DSoundRenderImpl *This, DWORD pos) {
110
    WAVEFORMATEX *wfx = (WAVEFORMATEX*)This->renderer.pInputPin->pin.mtCurrent.pbFormat;
111 112 113 114
    REFERENCE_TIME ret = 10000000;
    ret = ret * pos / wfx->nAvgBytesPerSec;
    return ret;
}
115

116
static DWORD pos_from_time(DSoundRenderImpl *This, REFERENCE_TIME time) {
117
    WAVEFORMATEX *wfx = (WAVEFORMATEX*)This->renderer.pInputPin->pin.mtCurrent.pbFormat;
118 119 120 121 122 123
    REFERENCE_TIME ret = time;
    ret *= wfx->nSamplesPerSec;
    ret /= 10000000;
    ret *= wfx->nBlockAlign;
    return ret;
}
124

125
static void DSoundRender_UpdatePositions(DSoundRenderImpl *This, DWORD *seqwritepos, DWORD *minwritepos) {
126
    WAVEFORMATEX *wfx = (WAVEFORMATEX*)This->renderer.pInputPin->pin.mtCurrent.pbFormat;
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    BYTE *buf1, *buf2;
    DWORD size1, size2, playpos, writepos, old_writepos, old_playpos, adv;
    BOOL writepos_set = This->writepos < This->buf_size;

    /* Update position and zero */
    old_writepos = This->writepos;
    old_playpos = This->last_playpos;
    if (old_writepos <= old_playpos)
        old_writepos += This->buf_size;

    IDirectSoundBuffer_GetCurrentPosition(This->dsbuffer, &playpos, &writepos);
    if (old_playpos > playpos) {
        adv = This->buf_size + playpos - old_playpos;
        This->play_time += time_from_pos(This, This->buf_size);
    } else
        adv = playpos - old_playpos;
    This->last_playpos = playpos;
    if (adv) {
        TRACE("Moving from %u to %u: clearing %u bytes\n", old_playpos, playpos, adv);
        IDirectSoundBuffer_Lock(This->dsbuffer, old_playpos, adv, (void**)&buf1, &size1, (void**)&buf2, &size2, 0);
        memset(buf1, wfx->wBitsPerSample == 8 ? 128  : 0, size1);
        memset(buf2, wfx->wBitsPerSample == 8 ? 128  : 0, size2);
        IDirectSoundBuffer_Unlock(This->dsbuffer, buf1, size1, buf2, size2);
    }
    *minwritepos = writepos;
    if (!writepos_set || old_writepos < writepos) {
        if (writepos_set) {
            This->writepos = This->buf_size;
155
            FIXME("Underrun of data occurred!\n");
156
        }
157 158 159 160
        *seqwritepos = writepos;
    } else
        *seqwritepos = This->writepos;
}
161

162 163
static HRESULT DSoundRender_GetWritePos(DSoundRenderImpl *This, DWORD *ret_writepos, REFERENCE_TIME write_at, DWORD *pfree, DWORD *skip)
{
164
    WAVEFORMATEX *wfx = (WAVEFORMATEX*)This->renderer.pInputPin->pin.mtCurrent.pbFormat;
165 166
    DWORD writepos, min_writepos, playpos;
    REFERENCE_TIME max_lag = 50 * 10000;
167
    REFERENCE_TIME min_lag = 25 * 10000;
168 169 170 171
    REFERENCE_TIME cur, writepos_t, delta_t;

    DSoundRender_UpdatePositions(This, &writepos, &min_writepos);
    playpos = This->last_playpos;
172
    if (This->renderer.filter.pClock == &This->IReferenceClock_iface) {
173 174
        max_lag = min_lag;
        cur = This->play_time + time_from_pos(This, playpos);
175 176 177 178
        cur -= This->renderer.filter.rtStreamStart;
    } else if (This->renderer.filter.pClock) {
        IReferenceClock_GetTime(This->renderer.filter.pClock, &cur);
        cur -= This->renderer.filter.rtStreamStart;
179
    } else
180
        write_at = -1;
181 182

    if (writepos == min_writepos)
183
        max_lag = 0;
184 185

    *skip = 0;
186
    if (write_at < 0) {
187 188 189
        *ret_writepos = writepos;
        goto end;
    }
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204
    if (writepos >= playpos)
        writepos_t = cur + time_from_pos(This, writepos - playpos);
    else
        writepos_t = cur + time_from_pos(This, This->buf_size + writepos - playpos);

    /* write_at: Starting time of sample */
    /* cur: current time of play position */
    /* writepos_t: current time of our pointer play position */
    delta_t = write_at - writepos_t;
    if (delta_t >= -max_lag && delta_t <= max_lag) {
        TRACE("Continuing from old position\n");
        *ret_writepos = writepos;
    } else if (delta_t < 0) {
        REFERENCE_TIME past, min_writepos_t;
205
        WARN("Delta too big %i/%i, overwriting old data or even skipping\n", (int)delta_t / 10000, (int)max_lag / 10000);
206 207 208 209 210 211 212
        if (min_writepos >= playpos)
            min_writepos_t = cur + time_from_pos(This, min_writepos - playpos);
        else
            min_writepos_t = cur + time_from_pos(This, This->buf_size - playpos + min_writepos);
        past = min_writepos_t - write_at;
        if (past >= 0) {
            DWORD skipbytes = pos_from_time(This, past);
213
            WARN("Skipping %u bytes\n", skipbytes);
214 215 216 217
            *skip = skipbytes;
            *ret_writepos = min_writepos;
        } else {
            DWORD aheadbytes = pos_from_time(This, -past);
218
            WARN("Advancing %u bytes\n", aheadbytes);
219
            *ret_writepos = (min_writepos + aheadbytes) % This->buf_size;
220
        }
221 222
    } else /* delta_t > 0 */ {
        DWORD aheadbytes;
223
        WARN("Delta too big %i/%i, too far ahead\n", (int)delta_t / 10000, (int)max_lag / 10000);
224
        aheadbytes = pos_from_time(This, delta_t);
225
        WARN("Advancing %u bytes\n", aheadbytes);
226 227 228
        if (delta_t >= DSoundRenderer_Max_Fill)
            return S_FALSE;
        *ret_writepos = (min_writepos + aheadbytes) % This->buf_size;
229
    }
230 231 232 233 234 235 236 237 238 239 240 241
end:
    if (playpos > *ret_writepos)
        *pfree = playpos - *ret_writepos;
    else if (playpos == *ret_writepos)
        *pfree = This->buf_size - wfx->nBlockAlign;
    else
        *pfree = This->buf_size + playpos - *ret_writepos;
    if (time_from_pos(This, This->buf_size - *pfree) >= DSoundRenderer_Max_Fill) {
        TRACE("Blocked: too full %i / %i\n", (int)(time_from_pos(This, This->buf_size - *pfree)/10000), (int)(DSoundRenderer_Max_Fill / 10000));
        return S_FALSE;
    }
    return S_OK;
242 243
}

244 245 246 247 248 249 250 251 252 253
static HRESULT DSoundRender_HandleEndOfStream(DSoundRenderImpl *This)
{
    while (1)
    {
        DWORD pos1, pos2;
        DSoundRender_UpdatePositions(This, &pos1, &pos2);
        if (pos1 == pos2)
            break;

        This->in_loop = 1;
254 255
        LeaveCriticalSection(&This->renderer.filter.csFilter);
        LeaveCriticalSection(&This->renderer.csRenderLock);
256
        WaitForSingleObject(This->blocked, 10);
257 258
        EnterCriticalSection(&This->renderer.filter.csFilter);
        EnterCriticalSection(&This->renderer.csRenderLock);
259 260 261
        This->in_loop = 0;
    }

262
    return S_OK;
263 264
}

265
static HRESULT DSoundRender_SendSampleData(DSoundRenderImpl* This, REFERENCE_TIME tStart, REFERENCE_TIME tStop, const BYTE *data, DWORD size)
266
{
267
    HRESULT hr;
268

269
    while (size && This->renderer.filter.state != State_Stopped) {
270 271
        DWORD writepos, skip = 0, free, size1, size2, ret;
        BYTE *buf1, *buf2;
272

273
        if (This->renderer.filter.state == State_Running)
274 275 276
            hr = DSoundRender_GetWritePos(This, &writepos, tStart, &free, &skip);
        else
            hr = S_FALSE;
277

278
        if (hr != S_OK) {
279
            This->in_loop = 1;
280
            LeaveCriticalSection(&This->renderer.csRenderLock);
281
            ret = WaitForSingleObject(This->blocked, 10);
282
            EnterCriticalSection(&This->renderer.csRenderLock);
283
            This->in_loop = 0;
284 285 286
            if (This->renderer.pInputPin->flushing ||
                This->renderer.filter.state == State_Stopped) {
                return This->renderer.filter.state == State_Paused ? S_OK : VFW_E_WRONG_STATE;
287 288 289
            }
            if (ret != WAIT_TIMEOUT)
                ERR("%x\n", ret);
290 291
            continue;
        }
292 293 294 295 296
        tStart = -1;

        if (skip)
            FIXME("Sample dropped %u of %u bytes\n", skip, size);
        if (skip >= size)
297
            return S_OK;
298 299
        data += skip;
        size -= skip;
300

301
        hr = IDirectSoundBuffer_Lock(This->dsbuffer, writepos, min(free, size), (void**)&buf1, &size1, (void**)&buf2, &size2, 0);
302
        if (hr != DS_OK) {
303
            ERR("Unable to lock sound buffer! (%x)\n", hr);
304
            break;
305
        }
306 307 308 309 310 311 312 313 314 315
        memcpy(buf1, data, size1);
        if (size2)
            memcpy(buf2, data+size1, size2);
        IDirectSoundBuffer_Unlock(This->dsbuffer, buf1, size1, buf2, size2);
        This->writepos = (writepos + size1 + size2) % This->buf_size;
        TRACE("Wrote %u bytes at %u, next at %u - (%u/%u)\n", size1+size2, writepos, This->writepos, free, size);
        data += size1 + size2;
        size -= size1 + size2;
    }
    return S_OK;
316 317
}

318 319 320 321 322 323 324
static HRESULT WINAPI DSoundRender_ShouldDrawSampleNow(BaseRenderer *This, IMediaSample *pMediaSample, REFERENCE_TIME *pStartTime, REFERENCE_TIME *pEndTime)
{
    /* We time ourselves do not use the base renderers timing */
    return S_OK;
}


325
static HRESULT WINAPI DSoundRender_PrepareReceive(BaseRenderer *iface, IMediaSample *pSample)
326
{
327
    DSoundRenderImpl *This = impl_from_BaseRenderer(iface);
328
    HRESULT hr;
329
    AM_MEDIA_TYPE *amt;
330

331 332
    if (IMediaSample_GetMediaType(pSample, &amt) == S_OK)
    {
333
        AM_MEDIA_TYPE *orig = &This->renderer.pInputPin->pin.mtCurrent;
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
        WAVEFORMATEX *origfmt = (WAVEFORMATEX *)orig->pbFormat;
        WAVEFORMATEX *newfmt = (WAVEFORMATEX *)amt->pbFormat;

        if (origfmt->wFormatTag == newfmt->wFormatTag &&
            origfmt->nChannels == newfmt->nChannels &&
            origfmt->nBlockAlign == newfmt->nBlockAlign &&
            origfmt->wBitsPerSample == newfmt->wBitsPerSample &&
            origfmt->cbSize ==  newfmt->cbSize)
        {
            if (origfmt->nSamplesPerSec != newfmt->nSamplesPerSec)
            {
                hr = IDirectSoundBuffer_SetFrequency(This->dsbuffer,
                                                     newfmt->nSamplesPerSec);
                if (FAILED(hr))
                    return VFW_E_TYPE_NOT_ACCEPTED;
                FreeMediaType(orig);
                CopyMediaType(orig, amt);
                IMediaSample_SetMediaType(pSample, NULL);
            }
        }
        else
            return VFW_E_TYPE_NOT_ACCEPTED;
    }
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    return S_OK;
}

static HRESULT WINAPI DSoundRender_DoRenderSample(BaseRenderer *iface, IMediaSample * pSample)
{
    DSoundRenderImpl *This = impl_from_BaseRenderer(iface);
    LPBYTE pbSrcStream = NULL;
    LONG cbSrcStream = 0;
    REFERENCE_TIME tStart, tStop;
    HRESULT hr;

    TRACE("%p %p\n", iface, pSample);

    /* Slightly incorrect, Pause completes when a frame is received so we should signal
     * pause completion here, but for sound playing a single frame doesn't make sense
     */
373

374 375 376
    hr = IMediaSample_GetPointer(pSample, &pbSrcStream);
    if (FAILED(hr))
    {
377
        ERR("Cannot get pointer to sample data (%x)\n", hr);
378
        return hr;
379 380 381
    }

    hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
382
    if (FAILED(hr)) {
383
        ERR("Cannot get sample time (%x)\n", hr);
384 385
        tStart = tStop = -1;
    }
386

387
    IMediaSample_IsDiscontinuity(pSample);
388

389 390 391 392 393 394
    if (IMediaSample_IsPreroll(pSample) == S_OK)
    {
        TRACE("Preroll!\n");
        return S_OK;
    }

395
    cbSrcStream = IMediaSample_GetActualDataLength(pSample);
396
    TRACE("Sample data ptr = %p, size = %d\n", pbSrcStream, cbSrcStream);
397

398
    hr = DSoundRender_SendSampleData(This, tStart, tStop, pbSrcStream, cbSrcStream);
399
    if (This->renderer.filter.state == State_Running && This->renderer.filter.pClock && tStart >= 0) {
400 401
        REFERENCE_TIME jitter, now = 0;
        Quality q;
402 403
        IReferenceClock_GetTime(This->renderer.filter.pClock, &now);
        jitter = now - This->renderer.filter.rtStreamStart - tStart;
404 405 406 407 408 409 410 411
        if (jitter <= -DSoundRenderer_Max_Fill)
            jitter += DSoundRenderer_Max_Fill;
        else if (jitter < 0)
            jitter = 0;
        q.Type = (jitter > 0 ? Famine : Flood);
        q.Proportion = 1.;
        q.Late = jitter;
        q.TimeStamp = tStart;
412
        IQualityControl_Notify((IQualityControl *)This->renderer.qcimpl, (IBaseFilter*)This, q);
413
    }
414
    return hr;
415 416
}

417
static HRESULT WINAPI DSoundRender_CheckMediaType(BaseRenderer *iface, const AM_MEDIA_TYPE * pmt)
418
{
419 420 421 422 423 424 425
    WAVEFORMATEX* format;

    if (!IsEqualIID(&pmt->majortype, &MEDIATYPE_Audio))
        return S_FALSE;

    format =  (WAVEFORMATEX*)pmt->pbFormat;
    TRACE("Format = %p\n", format);
426 427
    TRACE("wFormatTag = %x %x\n", format->wFormatTag, WAVE_FORMAT_PCM);
    TRACE("nChannels = %d\n", format->nChannels);
428 429
    TRACE("nSamplesPerSec = %d\n", format->nAvgBytesPerSec);
    TRACE("nAvgBytesPerSec = %d\n", format->nAvgBytesPerSec);
430 431 432
    TRACE("nBlockAlign = %d\n", format->nBlockAlign);
    TRACE("wBitsPerSample = %d\n", format->wBitsPerSample);

433 434 435 436
    if (!IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_PCM))
        return S_FALSE;

    return S_OK;
437 438
}

439
static VOID WINAPI DSoundRender_OnStopStreaming(BaseRenderer * iface)
440
{
441
    DSoundRenderImpl *This = impl_from_BaseRenderer(iface);
442

443
    TRACE("(%p/%p)->()\n", This, iface);
444

445 446 447
    IDirectSoundBuffer_Stop(This->dsbuffer);
    This->writepos = This->buf_size;
    SetEvent(This->blocked);
448 449
}

450
static VOID WINAPI DSoundRender_OnStartStreaming(BaseRenderer * iface)
451
{
452 453 454 455 456 457 458 459 460 461 462 463 464 465
    DSoundRenderImpl *This = impl_from_BaseRenderer(iface);

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

    if (This->renderer.pInputPin->pin.pConnectedTo)
    {
        if (This->renderer.filter.state == State_Paused)
        {
            /* Unblock our thread, state changing from paused to running doesn't need a reset for state change */
            SetEvent(This->blocked);
        }
        IDirectSoundBuffer_Play(This->dsbuffer, 0, 0, DSBPLAY_LOOPING);
        ResetEvent(This->blocked);
    }
466 467
}

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
static HRESULT WINAPI DSoundRender_CompleteConnect(BaseRenderer * iface, IPin * pReceivePin)
{
    DSoundRenderImpl *This = impl_from_BaseRenderer(iface);
    const AM_MEDIA_TYPE * pmt = &This->renderer.pInputPin->pin.mtCurrent;
    HRESULT hr = S_OK;
    WAVEFORMATEX *format;
    DSBUFFERDESC buf_desc;

    TRACE("(%p)->(%p)\n", This, pReceivePin);
    dump_AM_MEDIA_TYPE(pmt);

    TRACE("MajorType %s\n", debugstr_guid(&pmt->majortype));
    TRACE("SubType %s\n", debugstr_guid(&pmt->subtype));
    TRACE("Format %s\n", debugstr_guid(&pmt->formattype));
    TRACE("Size %d\n", pmt->cbFormat);

    format = (WAVEFORMATEX*)pmt->pbFormat;

    This->buf_size = format->nAvgBytesPerSec;
487

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    memset(&buf_desc,0,sizeof(DSBUFFERDESC));
    buf_desc.dwSize = sizeof(DSBUFFERDESC);
    buf_desc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPAN |
                       DSBCAPS_CTRLFREQUENCY | DSBCAPS_GLOBALFOCUS |
                       DSBCAPS_GETCURRENTPOSITION2;
    buf_desc.dwBufferBytes = This->buf_size;
    buf_desc.lpwfxFormat = format;
    hr = IDirectSound_CreateSoundBuffer(This->dsound, &buf_desc, &This->dsbuffer, NULL);
    This->writepos = This->buf_size;
    if (FAILED(hr))
        ERR("Can't create sound buffer (%x)\n", hr);

    if (SUCCEEDED(hr))
    {
        hr = IDirectSoundBuffer_SetVolume(This->dsbuffer, This->volume);
        if (FAILED(hr))
            ERR("Can't set volume to %d (%x)\n", This->volume, hr);

        hr = IDirectSoundBuffer_SetPan(This->dsbuffer, This->pan);
        if (FAILED(hr))
            ERR("Can't set pan to %d (%x)\n", This->pan, hr);
        hr = S_OK;
    }

    if (FAILED(hr) && hr != VFW_E_ALREADY_CONNECTED)
    {
        if (This->dsbuffer)
            IDirectSoundBuffer_Release(This->dsbuffer);
        This->dsbuffer = NULL;
    }

    return hr;
}

static HRESULT WINAPI DSoundRender_BreakConnect(BaseRenderer* iface)
{
    DSoundRenderImpl *This = impl_from_BaseRenderer(iface);

    TRACE("(%p)->()\n", iface);

    if (This->threadid) {
        PostThreadMessageW(This->threadid, WM_APP, 0, 0);
530
        LeaveCriticalSection(This->renderer.pInputPin->pin.pCritSec);
531
        WaitForSingleObject(This->advisethread, INFINITE);
532
        EnterCriticalSection(This->renderer.pInputPin->pin.pCritSec);
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        CloseHandle(This->advisethread);
    }
    if (This->dsbuffer)
        IDirectSoundBuffer_Release(This->dsbuffer);
    This->dsbuffer = NULL;

    return S_OK;
}

static HRESULT WINAPI DSoundRender_EndOfStream(BaseRenderer* iface)
{
    DSoundRenderImpl *This = impl_from_BaseRenderer(iface);
    HRESULT hr;

    TRACE("(%p)->()\n",iface);

    hr = BaseRendererImpl_EndOfStream(iface);
    if (hr != S_OK)
    {
        ERR("%08x\n", hr);
        return hr;
    }

    hr = DSoundRender_HandleEndOfStream(This);

    return hr;
}

static HRESULT WINAPI DSoundRender_BeginFlush(BaseRenderer* iface)
{
    DSoundRenderImpl *This = impl_from_BaseRenderer(iface);

    TRACE("\n");
    BaseRendererImpl_BeginFlush(iface);
    SetEvent(This->blocked);

    return S_OK;
}

static HRESULT WINAPI DSoundRender_EndFlush(BaseRenderer* iface)
{
    DSoundRenderImpl *This = impl_from_BaseRenderer(iface);

    TRACE("\n");

    BaseRendererImpl_EndFlush(iface);
    if (This->renderer.filter.state != State_Stopped)
        ResetEvent(This->blocked);

    if (This->dsbuffer)
    {
        LPBYTE buffer;
        DWORD size;

        /* Force a reset */
        IDirectSoundBuffer_Lock(This->dsbuffer, 0, 0, (LPVOID *)&buffer, &size, NULL, NULL, DSBLOCK_ENTIREBUFFER);
        memset(buffer, 0, size);
        IDirectSoundBuffer_Unlock(This->dsbuffer, buffer, size, NULL, 0);
        This->writepos = This->buf_size;
    }

    return S_OK;
}

static const BaseRendererFuncTable BaseFuncTable = {
598
    DSoundRender_CheckMediaType,
599 600
    DSoundRender_DoRenderSample,
    /**/
601
    NULL,
602 603 604 605 606 607 608
    NULL,
    NULL,
    DSoundRender_OnStartStreaming,
    DSoundRender_OnStopStreaming,
    NULL,
    NULL,
    NULL,
609
    DSoundRender_ShouldDrawSampleNow,
610 611 612 613 614 615 616
    DSoundRender_PrepareReceive,
    /**/
    DSoundRender_CompleteConnect,
    DSoundRender_BreakConnect,
    DSoundRender_EndOfStream,
    DSoundRender_BeginFlush,
    DSoundRender_EndFlush,
617 618
};

619 620 621 622 623 624 625 626 627 628 629
HRESULT DSoundRender_create(IUnknown * pUnkOuter, LPVOID * ppv)
{
    HRESULT hr;
    DSoundRenderImpl * pDSoundRender;

    TRACE("(%p, %p)\n", pUnkOuter, ppv);

    *ppv = NULL;

    if (pUnkOuter)
        return CLASS_E_NOAGGREGATION;
630

631
    pDSoundRender = CoTaskMemAlloc(sizeof(DSoundRenderImpl));
632 633 634
    if (!pDSoundRender)
        return E_OUTOFMEMORY;
    ZeroMemory(pDSoundRender, sizeof(DSoundRenderImpl));
635

636
    hr = BaseRenderer_Init(&pDSoundRender->renderer, &DSoundRender_Vtbl, (IUnknown*)pDSoundRender, &CLSID_DSoundRender, (DWORD_PTR)(__FILE__ ": DSoundRenderImpl.csFilter"), &BaseFuncTable);
637

638
    BasicAudio_Init(&pDSoundRender->basicAudio,&IBasicAudio_Vtbl);
639 640 641
    pDSoundRender->IReferenceClock_iface.lpVtbl = &IReferenceClock_Vtbl;
    pDSoundRender->IAMDirectSound_iface.lpVtbl = &IAMDirectSound_Vtbl;
    pDSoundRender->IAMFilterMiscFlags_iface.lpVtbl = &IAMFilterMiscFlags_Vtbl;
642

643 644
    if (SUCCEEDED(hr))
    {
645
        hr = DirectSoundCreate8(NULL, &pDSoundRender->dsound, NULL);
646 647
        if (FAILED(hr))
            ERR("Cannot create Direct Sound object (%x)\n", hr);
648
        else
649
            hr = IDirectSound_SetCooperativeLevel(pDSoundRender->dsound, GetDesktopWindow(), DSSCL_PRIORITY);
650 651 652 653 654 655 656 657 658
        if (SUCCEEDED(hr)) {
            IDirectSoundBuffer *buf;
            DSBUFFERDESC buf_desc;
            memset(&buf_desc,0,sizeof(DSBUFFERDESC));
            buf_desc.dwSize = sizeof(DSBUFFERDESC);
            buf_desc.dwFlags = DSBCAPS_PRIMARYBUFFER;
            hr = IDirectSound_CreateSoundBuffer(pDSoundRender->dsound, &buf_desc, &buf, NULL);
            if (SUCCEEDED(hr)) {
                IDirectSoundBuffer_Play(buf, 0, 0, DSBPLAY_LOOPING);
659
                IDirectSoundBuffer_Release(buf);
660 661 662
            }
            hr = S_OK;
        }
663 664
    }

665 666
    if (SUCCEEDED(hr))
    {
667
        pDSoundRender->blocked = CreateEventW(NULL, TRUE, TRUE, NULL);
668

669
        if (!pDSoundRender->blocked || FAILED(hr))
670 671 672 673 674
        {
            IUnknown_Release((IUnknown *)pDSoundRender);
            return HRESULT_FROM_WIN32(GetLastError());
        }

675
        *ppv = pDSoundRender;
676 677 678
    }
    else
    {
679
        BaseRendererImpl_Release(&pDSoundRender->renderer.filter.IBaseFilter_iface);
680 681 682 683 684 685 686 687
        CoTaskMemFree(pDSoundRender);
    }

    return hr;
}

static HRESULT WINAPI DSoundRender_QueryInterface(IBaseFilter * iface, REFIID riid, LPVOID * ppv)
{
688
    DSoundRenderImpl *This = impl_from_IBaseFilter(iface);
689 690 691 692
    TRACE("(%p, %p)->(%s, %p)\n", This, iface, qzdebugstr_guid(riid), ppv);

    *ppv = NULL;

693
    if (IsEqualIID(riid, &IID_IBasicAudio))
694
        *ppv = &This->basicAudio.IBasicAudio_iface;
695
    else if (IsEqualIID(riid, &IID_IReferenceClock))
696
        *ppv = &This->IReferenceClock_iface;
697
    else if (IsEqualIID(riid, &IID_IAMDirectSound))
698
        *ppv = &This->IAMDirectSound_iface;
699
    else if (IsEqualIID(riid, &IID_IAMFilterMiscFlags))
700
        *ppv = &This->IAMFilterMiscFlags_iface;
701 702 703 704 705 706 707
    else
    {
        HRESULT hr;
        hr = BaseRendererImpl_QueryInterface(iface, riid, ppv);
        if (SUCCEEDED(hr))
            return hr;
    }
708 709 710 711 712 713 714

    if (*ppv)
    {
        IUnknown_AddRef((IUnknown *)(*ppv));
        return S_OK;
    }

715
    if (!IsEqualIID(riid, &IID_IPin) && !IsEqualIID(riid, &IID_IVideoWindow))
716
        FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
717 718 719 720 721 722

    return E_NOINTERFACE;
}

static ULONG WINAPI DSoundRender_Release(IBaseFilter * iface)
{
723 724
    DSoundRenderImpl *This = impl_from_IBaseFilter(iface);
    ULONG refCount = BaseRendererImpl_Release(iface);
725

726
    TRACE("(%p)->() Release from %d\n", This, refCount + 1);
727

728
    if (!refCount)
729
    {
730 731 732 733 734 735
        if (This->threadid) {
            PostThreadMessageW(This->threadid, WM_APP, 0, 0);
            WaitForSingleObject(This->advisethread, INFINITE);
            CloseHandle(This->advisethread);
        }

736 737 738 739 740 741
        if (This->dsbuffer)
            IDirectSoundBuffer_Release(This->dsbuffer);
        This->dsbuffer = NULL;
        if (This->dsound)
            IDirectSound_Release(This->dsound);
        This->dsound = NULL;
742

743
        BasicAudio_Destroy(&This->basicAudio);
744 745
        CloseHandle(This->blocked);

746 747
        TRACE("Destroying Audio Renderer\n");
        CoTaskMemFree(This);
748

749 750 751
        return 0;
    }
    else
752
        return refCount;
753 754
}

755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
static HRESULT WINAPI DSoundRender_Pause(IBaseFilter * iface)
{
    HRESULT hr = S_OK;
    DSoundRenderImpl *This = (DSoundRenderImpl *)iface;

    TRACE("(%p/%p)->()\n", This, iface);

    EnterCriticalSection(&This->renderer.csRenderLock);
    if (This->renderer.filter.state != State_Paused)
    {
        if (This->renderer.filter.state == State_Stopped)
        {
            if (This->renderer.pInputPin->pin.pConnectedTo)
                ResetEvent(This->renderer.evComplete);
            This->renderer.pInputPin->end_of_stream = 0;
        }

        hr = IDirectSoundBuffer_Stop(This->dsbuffer);
        if (SUCCEEDED(hr))
            This->renderer.filter.state = State_Paused;

        ResetEvent(This->blocked);
        ResetEvent(This->renderer.RenderEvent);
    }
    ResetEvent(This->renderer.ThreadSignal);
    LeaveCriticalSection(&This->renderer.csRenderLock);

    return hr;
}

785 786 787
static const IBaseFilterVtbl DSoundRender_Vtbl =
{
    DSoundRender_QueryInterface,
788
    BaseFilterImpl_AddRef,
789
    DSoundRender_Release,
790
    BaseFilterImpl_GetClassID,
791
    BaseRendererImpl_Stop,
792
    DSoundRender_Pause,
793 794
    BaseRendererImpl_Run,
    BaseRendererImpl_GetState,
795
    BaseRendererImpl_SetSyncSource,
796
    BaseFilterImpl_GetSyncSource,
797
    BaseFilterImpl_EnumPins,
798
    BaseRendererImpl_FindPin,
799 800 801
    BaseFilterImpl_QueryFilterInfo,
    BaseFilterImpl_JoinFilterGraph,
    BaseFilterImpl_QueryVendorInfo
802 803 804 805 806 807
};

/*** IUnknown methods ***/
static HRESULT WINAPI Basicaudio_QueryInterface(IBasicAudio *iface,
						REFIID riid,
						LPVOID*ppvObj) {
808
    DSoundRenderImpl *This = impl_from_IBasicAudio(iface);
809 810 811

    TRACE("(%p/%p)->(%s (%p), %p)\n", This, iface, debugstr_guid(riid), riid, ppvObj);

812
    return DSoundRender_QueryInterface(&This->renderer.filter.IBaseFilter_iface, riid, ppvObj);
813 814 815
}

static ULONG WINAPI Basicaudio_AddRef(IBasicAudio *iface) {
816
    DSoundRenderImpl *This = impl_from_IBasicAudio(iface);
817 818 819

    TRACE("(%p/%p)->()\n", This, iface);

820
    return BaseFilterImpl_AddRef(&This->renderer.filter.IBaseFilter_iface);
821 822 823
}

static ULONG WINAPI Basicaudio_Release(IBasicAudio *iface) {
824
    DSoundRenderImpl *This = impl_from_IBasicAudio(iface);
825 826 827

    TRACE("(%p/%p)->()\n", This, iface);

828
    return DSoundRender_Release(&This->renderer.filter.IBaseFilter_iface);
829 830 831 832
}

/*** IBasicAudio methods ***/
static HRESULT WINAPI Basicaudio_put_Volume(IBasicAudio *iface,
833
                                            LONG lVolume) {
834
    DSoundRenderImpl *This = impl_from_IBasicAudio(iface);
835

836
    TRACE("(%p/%p)->(%d)\n", This, iface, lVolume);
837 838 839 840 841 842 843 844

    if (lVolume > DSBVOLUME_MAX || lVolume < DSBVOLUME_MIN)
        return E_INVALIDARG;

    if (This->dsbuffer) {
        if (FAILED(IDirectSoundBuffer_SetVolume(This->dsbuffer, lVolume)))
            return E_FAIL;
    }
845

846
    This->volume = lVolume;
847 848 849 850
    return S_OK;
}

static HRESULT WINAPI Basicaudio_get_Volume(IBasicAudio *iface,
851
                                            LONG *plVolume) {
852
    DSoundRenderImpl *This = impl_from_IBasicAudio(iface);
853

854
    TRACE("(%p/%p)->(%p)\n", This, iface, plVolume);
855

856 857 858 859
    if (!plVolume)
        return E_POINTER;

    *plVolume = This->volume;
860 861 862 863
    return S_OK;
}

static HRESULT WINAPI Basicaudio_put_Balance(IBasicAudio *iface,
864
                                             LONG lBalance) {
865
    DSoundRenderImpl *This = impl_from_IBasicAudio(iface);
866

867
    TRACE("(%p/%p)->(%d)\n", This, iface, lBalance);
868 869 870 871 872 873 874 875

    if (lBalance < DSBPAN_LEFT || lBalance > DSBPAN_RIGHT)
        return E_INVALIDARG;

    if (This->dsbuffer) {
        if (FAILED(IDirectSoundBuffer_SetPan(This->dsbuffer, lBalance)))
            return E_FAIL;
    }
876

877
    This->pan = lBalance;
878 879 880 881
    return S_OK;
}

static HRESULT WINAPI Basicaudio_get_Balance(IBasicAudio *iface,
882
                                             LONG *plBalance) {
883
    DSoundRenderImpl *This = impl_from_IBasicAudio(iface);
884

885 886 887 888
    TRACE("(%p/%p)->(%p)\n", This, iface, plBalance);

    if (!plBalance)
        return E_POINTER;
889

890
    *plBalance = This->pan;
891 892 893 894 895 896 897 898
    return S_OK;
}

static const IBasicAudioVtbl IBasicAudio_Vtbl =
{
    Basicaudio_QueryInterface,
    Basicaudio_AddRef,
    Basicaudio_Release,
899 900 901 902
    BasicAudioImpl_GetTypeInfoCount,
    BasicAudioImpl_GetTypeInfo,
    BasicAudioImpl_GetIDsOfNames,
    BasicAudioImpl_Invoke,
903 904 905 906 907
    Basicaudio_put_Volume,
    Basicaudio_get_Volume,
    Basicaudio_put_Balance,
    Basicaudio_get_Balance
};
908

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
struct dsoundrender_timer {
    struct dsoundrender_timer *next;
    REFERENCE_TIME start;
    REFERENCE_TIME periodicity;
    HANDLE handle;
    DWORD cookie;
};
static LONG cookie_counter = 1;

static DWORD WINAPI DSoundAdviseThread(LPVOID lpParam) {
    DSoundRenderImpl *This = lpParam;
    struct dsoundrender_timer head = { };
    MSG msg;

    TRACE("(%p): Main Loop\n", This);

    PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
    SetEvent(This->thread_wait);

    while (1)
    {
        HRESULT hr;
        REFERENCE_TIME curtime = 0;
        BOOL ret;
        struct dsoundrender_timer *prev = &head, *cur;

935
        hr = IReferenceClock_GetTime(&This->IReferenceClock_iface, &curtime);
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
        if (SUCCEEDED(hr)) {
            TRACE("Time: %s\n", wine_dbgstr_longlong(curtime));
            while (prev->next) {
                cur = prev->next;
                if (cur->start > curtime) {
                    TRACE("Skipping %p\n", cur);
                    prev = cur;
                } else if (cur->periodicity) {
                    while (cur->start <= curtime) {
                        cur->start += cur->periodicity;
                        ReleaseSemaphore(cur->handle, 1, NULL);
                    }
                    prev = cur;
                } else {
                    struct dsoundrender_timer *next = cur->next;
                    TRACE("Firing %p %s < %s\n", cur, wine_dbgstr_longlong(cur->start), wine_dbgstr_longlong(curtime));
                    SetEvent(cur->handle);
                    HeapFree(GetProcessHeap(), 0, cur);
                    prev->next = next;
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
                }
            }
        }
        if (!head.next)
            ret = GetMessageW(&msg, INVALID_HANDLE_VALUE, WM_APP, WM_APP + 4);
        else
            ret = PeekMessageW(&msg, INVALID_HANDLE_VALUE, WM_APP, WM_APP + 4, PM_REMOVE);
        while (ret) {
            switch (LOWORD(msg.message) - WM_APP) {
                case 0: TRACE("Exiting\n"); return 0;
                case 1:
                case 2: {
                    struct dsoundrender_timer *t = (struct dsoundrender_timer *)msg.wParam;
                    if (LOWORD(msg.message) - WM_APP == 1)
                        TRACE("Adding one-shot timer %p\n", t);
                    else
                        TRACE("Adding periodic timer %p\n", t);
                    t->next = head.next;
                    head.next = t;
                    break;
                }
                case 3:
                    prev = &head;
                    while (prev->next) {
                        cur = prev->next;
                        if (cur->cookie == msg.wParam) {
                            struct dsoundrender_timer *next = cur->next;
                            HeapFree(GetProcessHeap(), 0, cur);
                            prev->next = next;
                            break;
                        }
                        prev = cur;
                    }
                    break;
            }
            ret = PeekMessageW(&msg, INVALID_HANDLE_VALUE, WM_APP, WM_APP + 4, PM_REMOVE);
        }
        MsgWaitForMultipleObjects(0, NULL, 5, QS_POSTMESSAGE, 0);
    }
    return 0;
}
996 997 998 999 1000 1001

/*** IUnknown methods ***/
static HRESULT WINAPI ReferenceClock_QueryInterface(IReferenceClock *iface,
						REFIID riid,
						LPVOID*ppvObj)
{
1002
    DSoundRenderImpl *This = impl_from_IReferenceClock(iface);
1003 1004 1005

    TRACE("(%p/%p)->(%s (%p), %p)\n", This, iface, debugstr_guid(riid), riid, ppvObj);

1006
    return DSoundRender_QueryInterface(&This->renderer.filter.IBaseFilter_iface, riid, ppvObj);
1007 1008 1009 1010
}

static ULONG WINAPI ReferenceClock_AddRef(IReferenceClock *iface)
{
1011
    DSoundRenderImpl *This = impl_from_IReferenceClock(iface);
1012 1013 1014

    TRACE("(%p/%p)->()\n", This, iface);

1015
    return BaseFilterImpl_AddRef(&This->renderer.filter.IBaseFilter_iface);
1016 1017 1018 1019
}

static ULONG WINAPI ReferenceClock_Release(IReferenceClock *iface)
{
1020
    DSoundRenderImpl *This = impl_from_IReferenceClock(iface);
1021 1022 1023

    TRACE("(%p/%p)->()\n", This, iface);

1024
    return DSoundRender_Release(&This->renderer.filter.IBaseFilter_iface);
1025 1026 1027 1028 1029 1030
}

/*** IReferenceClock methods ***/
static HRESULT WINAPI ReferenceClock_GetTime(IReferenceClock *iface,
                                             REFERENCE_TIME *pTime)
{
1031
    DSoundRenderImpl *This = impl_from_IReferenceClock(iface);
1032 1033 1034
    HRESULT hr = E_FAIL;

    TRACE("(%p/%p)->(%p)\n", This, iface, pTime);
1035 1036
    if (!pTime)
        return E_POINTER;
1037

1038 1039
    if (This->dsbuffer) {
        DWORD writepos1, writepos2;
1040
        EnterCriticalSection(&This->renderer.filter.csFilter);
1041
        DSoundRender_UpdatePositions(This, &writepos1, &writepos2);
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
        if (This->renderer.pInputPin && This->renderer.pInputPin->pin.mtCurrent.pbFormat)
        {
            *pTime = This->play_time + time_from_pos(This, This->last_playpos);
            hr = S_OK;
        }
        else
        {
            ERR("pInputPin Disconncted\n");
            hr = E_FAIL;
        }
1052
        LeaveCriticalSection(&This->renderer.filter.csFilter);
1053
    }
1054
    if (FAILED(hr))
1055
        WARN("Could not get reference time (%x)!\n", hr);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

    return hr;
}

static HRESULT WINAPI ReferenceClock_AdviseTime(IReferenceClock *iface,
                                                REFERENCE_TIME rtBaseTime,
                                                REFERENCE_TIME rtStreamTime,
                                                HEVENT hEvent,
                                                DWORD_PTR *pdwAdviseCookie)
{
1066
    DSoundRenderImpl *This = impl_from_IReferenceClock(iface);
1067 1068 1069
    REFERENCE_TIME when = rtBaseTime + rtStreamTime;
    REFERENCE_TIME future;
    TRACE("(%p/%p)->(%s, %s, %p, %p)\n", This, iface, wine_dbgstr_longlong(rtBaseTime), wine_dbgstr_longlong(rtStreamTime), (void*)hEvent, pdwAdviseCookie);
1070

1071 1072
    if (when <= 0)
        return E_INVALIDARG;
1073

1074 1075 1076
    if (!pdwAdviseCookie)
        return E_POINTER;

1077
    EnterCriticalSection(&This->renderer.filter.csFilter);
1078 1079 1080 1081 1082 1083 1084
    future = when - This->play_time;
    if (!This->threadid && This->dsbuffer) {
        This->thread_wait = CreateEventW(0, 0, 0, 0);
        This->advisethread = CreateThread(NULL, 0, DSoundAdviseThread, This, 0, &This->threadid);
        WaitForSingleObject(This->thread_wait, INFINITE);
        CloseHandle(This->thread_wait);
    }
1085
    LeaveCriticalSection(&This->renderer.filter.csFilter);
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    /* If it's in the past or the next millisecond, trigger immediately  */
    if (future <= 10000) {
        SetEvent((HANDLE)hEvent);
        *pdwAdviseCookie = 0;
    } else {
        struct dsoundrender_timer *t = HeapAlloc(GetProcessHeap(), 0, sizeof(*t));
        t->next = NULL;
        t->start = when;
        t->periodicity = 0;
        t->handle = (HANDLE)hEvent;
        t->cookie = InterlockedIncrement(&cookie_counter);
        PostThreadMessageW(This->threadid, WM_APP+1, (WPARAM)t, 0);
        *pdwAdviseCookie = t->cookie;
    }

    return S_OK;
1102 1103 1104
}

static HRESULT WINAPI ReferenceClock_AdvisePeriodic(IReferenceClock *iface,
1105 1106
                                                    REFERENCE_TIME rtStartTime,
                                                    REFERENCE_TIME rtPeriodTime,
1107 1108 1109
                                                    HSEMAPHORE hSemaphore,
                                                    DWORD_PTR *pdwAdviseCookie)
{
1110
    DSoundRenderImpl *This = impl_from_IReferenceClock(iface);
1111
    struct dsoundrender_timer *t;
1112

1113
    TRACE("(%p/%p)->(%s, %s, %p, %p)\n", This, iface, wine_dbgstr_longlong(rtStartTime), wine_dbgstr_longlong(rtPeriodTime), (void*)hSemaphore, pdwAdviseCookie);
1114

1115 1116 1117 1118 1119 1120
    if (rtStartTime <= 0 || rtPeriodTime <= 0)
        return E_INVALIDARG;

    if (!pdwAdviseCookie)
        return E_POINTER;

1121
    EnterCriticalSection(&This->renderer.filter.csFilter);
1122 1123 1124 1125 1126 1127
    if (!This->threadid && This->dsbuffer) {
        This->thread_wait = CreateEventW(0, 0, 0, 0);
        This->advisethread = CreateThread(NULL, 0, DSoundAdviseThread, This, 0, &This->threadid);
        WaitForSingleObject(This->thread_wait, INFINITE);
        CloseHandle(This->thread_wait);
    }
1128
    LeaveCriticalSection(&This->renderer.filter.csFilter);
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

    t = HeapAlloc(GetProcessHeap(), 0, sizeof(*t));
    t->next = NULL;
    t->start = rtStartTime;
    t->periodicity = rtPeriodTime;
    t->handle = (HANDLE)hSemaphore;
    t->cookie = InterlockedIncrement(&cookie_counter);
    PostThreadMessageW(This->threadid, WM_APP+1, (WPARAM)t, 0);
    *pdwAdviseCookie = t->cookie;

    return S_OK;
1140 1141 1142 1143 1144
}

static HRESULT WINAPI ReferenceClock_Unadvise(IReferenceClock *iface,
                                              DWORD_PTR dwAdviseCookie)
{
1145
    DSoundRenderImpl *This = impl_from_IReferenceClock(iface);
1146

1147 1148 1149 1150 1151
    TRACE("(%p/%p)->(%p)\n", This, iface, (void*)dwAdviseCookie);
    if (!This->advisethread || !dwAdviseCookie)
        return S_FALSE;
    PostThreadMessageW(This->threadid, WM_APP+3, dwAdviseCookie, 0);
    return S_OK;
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
}

static const IReferenceClockVtbl IReferenceClock_Vtbl =
{
    ReferenceClock_QueryInterface,
    ReferenceClock_AddRef,
    ReferenceClock_Release,
    ReferenceClock_GetTime,
    ReferenceClock_AdviseTime,
    ReferenceClock_AdvisePeriodic,
    ReferenceClock_Unadvise
};
1164

1165 1166 1167 1168 1169
/*** IUnknown methods ***/
static HRESULT WINAPI AMDirectSound_QueryInterface(IAMDirectSound *iface,
						REFIID riid,
						LPVOID*ppvObj)
{
1170
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1171 1172 1173

    TRACE("(%p/%p)->(%s (%p), %p)\n", This, iface, debugstr_guid(riid), riid, ppvObj);

1174
    return DSoundRender_QueryInterface(&This->renderer.filter.IBaseFilter_iface, riid, ppvObj);
1175 1176 1177 1178
}

static ULONG WINAPI AMDirectSound_AddRef(IAMDirectSound *iface)
{
1179
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1180 1181 1182

    TRACE("(%p/%p)->()\n", This, iface);

1183
    return BaseFilterImpl_AddRef(&This->renderer.filter.IBaseFilter_iface);
1184 1185 1186 1187
}

static ULONG WINAPI AMDirectSound_Release(IAMDirectSound *iface)
{
1188
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1189 1190 1191

    TRACE("(%p/%p)->()\n", This, iface);

1192
    return DSoundRender_Release(&This->renderer.filter.IBaseFilter_iface);
1193 1194 1195 1196 1197
}

/*** IAMDirectSound methods ***/
static HRESULT WINAPI AMDirectSound_GetDirectSoundInterface(IAMDirectSound *iface,  IDirectSound **ds)
{
1198
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1199 1200 1201 1202 1203 1204 1205 1206

    FIXME("(%p/%p)->(%p): stub\n", This, iface, ds);

    return E_NOTIMPL;
}

static HRESULT WINAPI AMDirectSound_GetPrimaryBufferInterface(IAMDirectSound *iface, IDirectSoundBuffer **buf)
{
1207
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1208 1209 1210 1211 1212 1213 1214 1215

    FIXME("(%p/%p)->(%p): stub\n", This, iface, buf);

    return E_NOTIMPL;
}

static HRESULT WINAPI AMDirectSound_GetSecondaryBufferInterface(IAMDirectSound *iface, IDirectSoundBuffer **buf)
{
1216
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1217 1218 1219 1220 1221 1222 1223 1224

    FIXME("(%p/%p)->(%p): stub\n", This, iface, buf);

    return E_NOTIMPL;
}

static HRESULT WINAPI AMDirectSound_ReleaseDirectSoundInterface(IAMDirectSound *iface, IDirectSound *ds)
{
1225
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1226 1227 1228 1229 1230 1231 1232 1233

    FIXME("(%p/%p)->(%p): stub\n", This, iface, ds);

    return E_NOTIMPL;
}

static HRESULT WINAPI AMDirectSound_ReleasePrimaryBufferInterface(IAMDirectSound *iface, IDirectSoundBuffer *buf)
{
1234
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1235 1236 1237 1238 1239 1240 1241 1242

    FIXME("(%p/%p)->(%p): stub\n", This, iface, buf);

    return E_NOTIMPL;
}

static HRESULT WINAPI AMDirectSound_ReleaseSecondaryBufferInterface(IAMDirectSound *iface, IDirectSoundBuffer *buf)
{
1243
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1244 1245 1246 1247 1248 1249 1250 1251

    FIXME("(%p/%p)->(%p): stub\n", This, iface, buf);

    return E_NOTIMPL;
}

static HRESULT WINAPI AMDirectSound_SetFocusWindow(IAMDirectSound *iface, HWND hwnd, BOOL bgsilent)
{
1252
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1253 1254 1255 1256 1257 1258 1259 1260

    FIXME("(%p/%p)->(%p,%d): stub\n", This, iface, hwnd, bgsilent);

    return E_NOTIMPL;
}

static HRESULT WINAPI AMDirectSound_GetFocusWindow(IAMDirectSound *iface, HWND hwnd)
{
1261
    DSoundRenderImpl *This = impl_from_IAMDirectSound(iface);
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281

    FIXME("(%p/%p)->(%p): stub\n", This, iface, hwnd);

    return E_NOTIMPL;
}

static const IAMDirectSoundVtbl IAMDirectSound_Vtbl =
{
    AMDirectSound_QueryInterface,
    AMDirectSound_AddRef,
    AMDirectSound_Release,
    AMDirectSound_GetDirectSoundInterface,
    AMDirectSound_GetPrimaryBufferInterface,
    AMDirectSound_GetSecondaryBufferInterface,
    AMDirectSound_ReleaseDirectSoundInterface,
    AMDirectSound_ReleasePrimaryBufferInterface,
    AMDirectSound_ReleaseSecondaryBufferInterface,
    AMDirectSound_SetFocusWindow,
    AMDirectSound_GetFocusWindow
};
1282

1283
static HRESULT WINAPI AMFilterMiscFlags_QueryInterface(IAMFilterMiscFlags *iface, REFIID riid, void **ppv) {
1284
    DSoundRenderImpl *This = impl_from_IAMFilterMiscFlags(iface);
1285 1286 1287 1288
    return IUnknown_QueryInterface((IUnknown*)This, riid, ppv);
}

static ULONG WINAPI AMFilterMiscFlags_AddRef(IAMFilterMiscFlags *iface) {
1289
    DSoundRenderImpl *This = impl_from_IAMFilterMiscFlags(iface);
1290 1291 1292 1293
    return IUnknown_AddRef((IUnknown*)This);
}

static ULONG WINAPI AMFilterMiscFlags_Release(IAMFilterMiscFlags *iface) {
1294
    DSoundRenderImpl *This = impl_from_IAMFilterMiscFlags(iface);
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    return IUnknown_Release((IUnknown*)This);
}

static ULONG WINAPI AMFilterMiscFlags_GetMiscFlags(IAMFilterMiscFlags *iface) {
    return AM_FILTER_MISC_FLAGS_IS_RENDERER;
}

static const IAMFilterMiscFlagsVtbl IAMFilterMiscFlags_Vtbl = {
    AMFilterMiscFlags_QueryInterface,
    AMFilterMiscFlags_AddRef,
    AMFilterMiscFlags_Release,
    AMFilterMiscFlags_GetMiscFlags
};