pin.c 23.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Generic Implementation of IPin Interface
 *
 * Copyright 2003 Robert Shearman
 *
 * 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
 */

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

#include "wine/debug.h"
#include "wine/unicode.h"
#include "uuids.h"
#include "vfwmsgs.h"
#include <assert.h>

WINE_DEFAULT_DEBUG_CHANNEL(quartz);

32
static const IPinVtbl PullPin_Vtbl;
33

34 35
#define ALIGNDOWN(value,boundary) ((value)/(boundary)*(boundary))
#define ALIGNUP(value,boundary) (ALIGNDOWN((value)+(boundary)-1, (boundary)))
36

37 38 39 40 41 42 43 44
typedef HRESULT (*SendPinFunc)( IPin *to, LPVOID arg );

/** Helper function, there are a lot of places where the error code is inherited
 * The following rules apply:
 *
 * Return the first received error code (E_NOTIMPL is ignored)
 * If no errors occur: return the first received non-error-code that isn't S_OK
 */
45
static HRESULT updatehres( HRESULT original, HRESULT new )
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
{
    if (FAILED( original ) || new == E_NOTIMPL)
        return original;

    if (FAILED( new ) || original == S_OK)
        return new;

    return original;
}

/** Sends a message from a pin further to other, similar pins
 * fnMiddle is called on each pin found further on the stream.
 * fnEnd (can be NULL) is called when the message can't be sent any further (this is a renderer or source)
 *
 * If the pin given is an input pin, the message will be sent downstream to other input pins
 * If the pin given is an output pin, the message will be sent upstream to other output pins
 */
static HRESULT SendFurther( IPin *from, SendPinFunc fnMiddle, LPVOID arg, SendPinFunc fnEnd )
{
    PIN_INFO pin_info;
    ULONG amount = 0;
    HRESULT hr = S_OK;
    HRESULT hr_return = S_OK;
    IEnumPins *enumpins = NULL;
    BOOL foundend = TRUE;
    PIN_DIRECTION from_dir;

    IPin_QueryDirection( from, &from_dir );

    hr = IPin_QueryInternalConnections( from, NULL, &amount );
    if (hr != E_NOTIMPL && amount)
        FIXME("Use QueryInternalConnections!\n");
     hr = S_OK;

    pin_info.pFilter = NULL;
    hr = IPin_QueryPinInfo( from, &pin_info );
    if (FAILED(hr))
        goto out;

    hr = IBaseFilter_EnumPins( pin_info.pFilter, &enumpins );
    if (FAILED(hr))
        goto out;

    hr = IEnumPins_Reset( enumpins );
    while (hr == S_OK) {
        IPin *pin = NULL;
        hr = IEnumPins_Next( enumpins, 1, &pin, NULL );
        if (hr == VFW_E_ENUM_OUT_OF_SYNC)
        {
            hr = IEnumPins_Reset( enumpins );
            continue;
        }
        if (pin)
        {
            PIN_DIRECTION dir;

            IPin_QueryDirection( pin, &dir );
            if (dir != from_dir)
            {
                IPin *connected = NULL;

                foundend = FALSE;
                IPin_ConnectedTo( pin, &connected );
                if (connected)
                {
                    HRESULT hr_local;

113
                    hr_local = fnMiddle( connected, arg );
114 115 116 117 118 119
                    hr_return = updatehres( hr_return, hr_local );
                    IPin_Release(connected);
                }
            }
            IPin_Release( pin );
        }
120 121 122 123 124
        else
        {
            hr = S_OK;
            break;
        }
125 126
    }

127 128 129 130 131 132 133 134 135 136
    if (!foundend)
        hr = hr_return;
    else if (fnEnd) {
        HRESULT hr_local;

        hr_local = fnEnd( from, arg );
        hr_return = updatehres( hr_return, hr_local );
    }

out:
137 138
    if (enumpins)
        IEnumPins_Release( enumpins );
139 140 141 142 143
    if (pin_info.pFilter)
        IBaseFilter_Release( pin_info.pFilter );
    return hr;
}

144 145 146 147 148 149 150 151 152 153 154 155

static void Copy_PinInfo(PIN_INFO * pDest, const PIN_INFO * pSrc)
{
    /* Tempting to just do a memcpy, but the name field is
       128 characters long! We will probably never exceed 10
       most of the time, so we are better off copying 
       each field manually */
    strcpyW(pDest->achName, pSrc->achName);
    pDest->dir = pSrc->dir;
    pDest->pFilter = pSrc->pFilter;
}

156 157 158 159 160 161 162 163
static HRESULT deliver_endofstream(IPin* pin, LPVOID unused)
{
    return IPin_EndOfStream( pin );
}

static HRESULT deliver_beginflush(IPin* pin, LPVOID unused)
{
    return IPin_BeginFlush( pin );
164 165
}

166 167 168
static HRESULT deliver_endflush(IPin* pin, LPVOID unused)
{
    return IPin_EndFlush( pin );
169 170
}

171 172 173 174 175 176 177 178 179 180
typedef struct newsegmentargs
{
    REFERENCE_TIME tStart, tStop;
    double rate;
} newsegmentargs;

static HRESULT deliver_newsegment(IPin *pin, LPVOID data)
{
    newsegmentargs *args = data;
    return IPin_NewSegment(pin, args->tStart, args->tStop, args->rate);
181 182
}

183
/*** PullPin implementation ***/
184

185
static HRESULT PullPin_Init(const IPinVtbl *PullPin_Vtbl, const PIN_INFO * pPinInfo, SAMPLEPROC_PULL pSampleProc, LPVOID pUserData,
186
                            QUERYACCEPTPROC pQueryAccept, CLEANUPPROC pCleanUp, REQUESTPROC pCustomRequest, STOPPROCESSPROC pDone, LPCRITICAL_SECTION pCritSec, PullPin * pPinImpl)
187 188
{
    /* Common attributes */
189
    pPinImpl->pin.IPin_iface.lpVtbl = PullPin_Vtbl;
190 191 192 193
    pPinImpl->pin.refCount = 1;
    pPinImpl->pin.pConnectedTo = NULL;
    pPinImpl->pin.pCritSec = pCritSec;
    Copy_PinInfo(&pPinImpl->pin.pinInfo, pPinInfo);
194
    ZeroMemory(&pPinImpl->pin.mtCurrent, sizeof(AM_MEDIA_TYPE));
195 196

    /* Input pin attributes */
197 198
    pPinImpl->pUserData = pUserData;
    pPinImpl->fnQueryAccept = pQueryAccept;
199
    pPinImpl->fnSampleProc = pSampleProc;
200
    pPinImpl->fnCleanProc = pCleanUp;
201
    pPinImpl->fnDone = pDone;
202 203
    pPinImpl->fnPreConnect = NULL;
    pPinImpl->pAlloc = NULL;
204
    pPinImpl->prefAlloc = NULL;
205 206
    pPinImpl->pReader = NULL;
    pPinImpl->hThread = NULL;
207
    pPinImpl->hEventStateChanged = CreateEventW(NULL, TRUE, TRUE, NULL);
208
    pPinImpl->thread_sleepy = CreateEventW(NULL, FALSE, FALSE, NULL);
209 210

    pPinImpl->rtStart = 0;
211
    pPinImpl->rtCurrent = 0;
212
    pPinImpl->rtStop = ((LONGLONG)0x7fffffff << 32) | 0xffffffff;
213
    pPinImpl->dRate = 1.0;
214 215 216
    pPinImpl->state = Req_Die;
    pPinImpl->fnCustomRequest = pCustomRequest;
    pPinImpl->stop_playback = 1;
217

218 219 220
    InitializeCriticalSection(&pPinImpl->thread_lock);
    pPinImpl->thread_lock.DebugInfo->Spare[0] = (DWORD_PTR)( __FILE__ ": PullPin.thread_lock");

221 222 223
    return S_OK;
}

224
HRESULT PullPin_Construct(const IPinVtbl *PullPin_Vtbl, const PIN_INFO * pPinInfo, SAMPLEPROC_PULL pSampleProc, LPVOID pUserData, QUERYACCEPTPROC pQueryAccept, CLEANUPPROC pCleanUp, REQUESTPROC pCustomRequest, STOPPROCESSPROC pDone, LPCRITICAL_SECTION pCritSec, IPin ** ppPin)
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
{
    PullPin * pPinImpl;

    *ppPin = NULL;

    if (pPinInfo->dir != PINDIR_INPUT)
    {
        ERR("Pin direction(%x) != PINDIR_INPUT\n", pPinInfo->dir);
        return E_INVALIDARG;
    }

    pPinImpl = CoTaskMemAlloc(sizeof(*pPinImpl));

    if (!pPinImpl)
        return E_OUTOFMEMORY;

241
    if (SUCCEEDED(PullPin_Init(PullPin_Vtbl, pPinInfo, pSampleProc, pUserData, pQueryAccept, pCleanUp, pCustomRequest, pDone, pCritSec, pPinImpl)))
242
    {
243
        *ppPin = &pPinImpl->pin.IPin_iface;
244 245 246 247 248 249 250
        return S_OK;
    }

    CoTaskMemFree(pPinImpl);
    return E_FAIL;
}

251 252
static HRESULT PullPin_InitProcessing(PullPin * This);

253 254 255 256
HRESULT WINAPI PullPin_ReceiveConnection(IPin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
{
    PIN_DIRECTION pindirReceive;
    HRESULT hr = S_OK;
257
    PullPin *This = impl_PullPin_from_IPin(iface);
258

259
    TRACE("(%p/%p)->(%p, %p)\n", This, iface, pReceivePin, pmt);
260 261 262
    dump_AM_MEDIA_TYPE(pmt);

    EnterCriticalSection(This->pin.pCritSec);
263
    if (!This->pin.pConnectedTo)
264
    {
265 266 267 268 269 270 271
        ALLOCATOR_PROPERTIES props;

        props.cBuffers = 3;
        props.cbBuffer = 64 * 1024; /* 64k bytes */
        props.cbAlign = 1;
        props.cbPrefix = 0;

272
        if (SUCCEEDED(hr) && (This->fnQueryAccept(This->pUserData, pmt) != S_OK))
273 274 275 276 277 278 279 280 281 282 283 284 285 286
            hr = VFW_E_TYPE_NOT_ACCEPTED; /* FIXME: shouldn't we just map common errors onto 
                                           * VFW_E_TYPE_NOT_ACCEPTED and pass the value on otherwise? */

        if (SUCCEEDED(hr))
        {
            IPin_QueryDirection(pReceivePin, &pindirReceive);

            if (pindirReceive != PINDIR_OUTPUT)
            {
                ERR("Can't connect from non-output pin\n");
                hr = VFW_E_INVALID_DIRECTION;
            }
        }

287 288
        This->pReader = NULL;
        This->pAlloc = NULL;
289
        This->prefAlloc = NULL;
290 291 292 293 294
        if (SUCCEEDED(hr))
        {
            hr = IPin_QueryInterface(pReceivePin, &IID_IAsyncReader, (LPVOID *)&This->pReader);
        }

295
        if (SUCCEEDED(hr) && This->fnPreConnect)
296
        {
297
            hr = This->fnPreConnect(iface, pReceivePin, &props);
298 299
        }

300 301 302 303 304
        /*
         * Some custom filters (such as the one used by Fallout 3
         * and Fallout: New Vegas) expect to be passed a non-NULL
         * preferred allocator.
         */
305
        if (SUCCEEDED(hr))
306
        {
307 308 309 310 311 312
            hr = StdMemAllocator_create(NULL, (LPVOID *) &This->prefAlloc);
        }

        if (SUCCEEDED(hr))
        {
            hr = IAsyncReader_RequestAllocator(This->pReader, This->prefAlloc, &props, &This->pAlloc);
313 314 315 316 317 318 319
        }

        if (SUCCEEDED(hr))
        {
            CopyMediaType(&This->pin.mtCurrent, pmt);
            This->pin.pConnectedTo = pReceivePin;
            IPin_AddRef(pReceivePin);
320
            hr = IMemAllocator_Commit(This->pAlloc);
321
        }
322

323 324 325
        if (SUCCEEDED(hr))
            hr = PullPin_InitProcessing(This);

326
        if (FAILED(hr))
327 328 329 330
        {
             if (This->pReader)
                 IAsyncReader_Release(This->pReader);
             This->pReader = NULL;
331 332 333
             if (This->prefAlloc)
                 IMemAllocator_Release(This->prefAlloc);
             This->prefAlloc = NULL;
334 335 336 337
             if (This->pAlloc)
                 IMemAllocator_Release(This->pAlloc);
             This->pAlloc = NULL;
        }
338
    }
339 340
    else
        hr = VFW_E_ALREADY_CONNECTED;
341 342 343 344 345 346
    LeaveCriticalSection(This->pin.pCritSec);
    return hr;
}

HRESULT WINAPI PullPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
{
347
    PullPin *This = impl_PullPin_from_IPin(iface);
348 349

    TRACE("(%p/%p)->(%s, %p)\n", This, iface, qzdebugstr_guid(riid), ppv);
350 351 352 353

    *ppv = NULL;

    if (IsEqualIID(riid, &IID_IUnknown))
354
        *ppv = iface;
355
    else if (IsEqualIID(riid, &IID_IPin))
356
        *ppv = iface;
357 358
    else if (IsEqualIID(riid, &IID_IMediaSeeking) ||
             IsEqualIID(riid, &IID_IQualityControl))
359
    {
360
        return IBaseFilter_QueryInterface(This->pin.pinInfo.pFilter, riid, ppv);
361
    }
362 363 364 365 366 367 368 369 370 371 372 373

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

    FIXME("No interface for %s!\n", qzdebugstr_guid(riid));

    return E_NOINTERFACE;
}

374
ULONG WINAPI PullPin_Release(IPin *iface)
375
{
376
    PullPin *This = impl_PullPin_from_IPin(iface);
377
    ULONG refCount = InterlockedDecrement(&This->pin.refCount);
378

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

381
    if (!refCount)
382
    {
383 384 385
        WaitForSingleObject(This->hEventStateChanged, INFINITE);
        assert(!This->hThread);

386 387
        if(This->prefAlloc)
            IMemAllocator_Release(This->prefAlloc);
388 389 390 391
        if(This->pAlloc)
            IMemAllocator_Release(This->pAlloc);
        if(This->pReader)
            IAsyncReader_Release(This->pReader);
392
        CloseHandle(This->thread_sleepy);
393
        CloseHandle(This->hEventStateChanged);
394 395
        This->thread_lock.DebugInfo->Spare[0] = 0;
        DeleteCriticalSection(&This->thread_lock);
396 397 398
        CoTaskMemFree(This);
        return 0;
    }
399
    return refCount;
400 401
}

402
static void PullPin_Flush(PullPin *This)
403
{
404
    IMediaSample *pSample;
405
    TRACE("Flushing!\n");
406

407 408
    if (This->pReader)
    {
409 410 411
        /* Do not allow state to change while flushing */
        EnterCriticalSection(This->pin.pCritSec);

412 413
        /* Flush outstanding samples */
        IAsyncReader_BeginFlush(This->pReader);
414

415 416 417 418 419 420 421 422
        for (;;)
        {
            DWORD_PTR dwUser;

            IAsyncReader_WaitForNext(This->pReader, 0, &pSample, &dwUser);

            if (!pSample)
                break;
423

424
            assert(!IMediaSample_GetActualDataLength(pSample));
425

426 427 428 429
            IMediaSample_Release(pSample);
        }

        IAsyncReader_EndFlush(This->pReader);
430 431

        LeaveCriticalSection(This->pin.pCritSec);
432 433 434
    }
}

435
static void PullPin_Thread_Process(PullPin *This)
436 437 438 439
{
    HRESULT hr;
    IMediaSample * pSample = NULL;
    ALLOCATOR_PROPERTIES allocProps;
440

441 442
    hr = IMemAllocator_GetProperties(This->pAlloc, &allocProps);

443 444
    This->cbAlign = allocProps.cbAlign;

445
    if (This->rtCurrent < This->rtStart)
446
        This->rtCurrent = MEDIATIME_FROM_BYTES(ALIGNDOWN(BYTES_FROM_MEDIATIME(This->rtStart), This->cbAlign));
447

448 449
    TRACE("Start\n");

450 451
    if (This->rtCurrent >= This->rtStop)
    {
452
        IPin_EndOfStream(&This->pin.IPin_iface);
453
        return;
454
    }
455 456

    /* There is no sample in our buffer */
457
    hr = This->fnCustomRequest(This->pUserData);
458

459 460 461
    if (FAILED(hr))
        ERR("Request error: %x\n", hr);

462 463 464
    EnterCriticalSection(This->pin.pCritSec);
    SetEvent(This->hEventStateChanged);
    LeaveCriticalSection(This->pin.pCritSec);
465

466
    if (SUCCEEDED(hr))
467
    do
468
    {
469
        DWORD_PTR dwUser;
470

471 472
        TRACE("Process sample\n");

473
        pSample = NULL;
474
        hr = IAsyncReader_WaitForNext(This->pReader, 10000, &pSample, &dwUser);
475

476
        /* Return an empty sample on error to the implementation in case it does custom parsing, so it knows it's gone */
477
        if (SUCCEEDED(hr))
478
        {
479
            hr = This->fnSampleProc(This->pUserData, pSample, dwUser);
480
        }
481
        else
482
        {
483 484
            if (hr == VFW_E_TIMEOUT)
            {
485 486
                if (pSample != NULL)
                    WARN("Non-NULL sample returned with VFW_E_TIMEOUT.\n");
487 488
                hr = S_OK;
            }
489 490 491
            /* FIXME: Errors are not well handled yet! */
            else
                ERR("Processing error: %x\n", hr);
492
        }
493

494
        if (pSample)
495
        {
496
            IMediaSample_Release(pSample);
497 498
            pSample = NULL;
        }
499
    } while (This->rtCurrent < This->rtStop && hr == S_OK && !This->stop_playback);
500

501 502 503 504 505 506
    /*
     * Sample was rejected, and we are asked to terminate.  When there is more than one buffer
     * it is possible for a filter to have several queued samples, making it necessary to
     * release all of these pending samples.
     */
    if (This->stop_playback || FAILED(hr))
507
    {
508 509 510 511 512 513 514 515 516
        DWORD_PTR dwUser;

        do
        {
            if (pSample)
                IMediaSample_Release(pSample);
            pSample = NULL;
            IAsyncReader_WaitForNext(This->pReader, 0, &pSample, &dwUser);
        } while(pSample);
517
    }
518

519 520 521
    /* Can't reset state to Sleepy here because that might race, instead PauseProcessing will do that for us
     * Flush remaining samples
     */
522
    if (This->fnDone)
523
        This->fnDone(This->pUserData);
524

525
    TRACE("End: %08x, %d\n", hr, This->stop_playback);
526 527
}

528
static void PullPin_Thread_Pause(PullPin *This)
529
{
530 531
    PullPin_Flush(This);

532 533 534 535 536 537
    EnterCriticalSection(This->pin.pCritSec);
    This->state = Req_Sleepy;
    SetEvent(This->hEventStateChanged);
    LeaveCriticalSection(This->pin.pCritSec);
}

538
static void  PullPin_Thread_Stop(PullPin *This)
539
{
540
    TRACE("(%p)->()\n", This);
541 542 543 544 545

    EnterCriticalSection(This->pin.pCritSec);
    {
        CloseHandle(This->hThread);
        This->hThread = NULL;
546
        SetEvent(This->hEventStateChanged);
547 548 549
    }
    LeaveCriticalSection(This->pin.pCritSec);

550 551
    IBaseFilter_Release(This->pin.pinInfo.pFilter);

552
    CoUninitialize();
553 554 555
    ExitThread(0);
}

556 557 558 559 560
static DWORD WINAPI PullPin_Thread_Main(LPVOID pv)
{
    PullPin *This = pv;
    CoInitializeEx(NULL, COINIT_MULTITHREADED);

561 562
    PullPin_Flush(This);

563 564 565 566 567 568 569 570 571
    for (;;)
    {
        WaitForSingleObject(This->thread_sleepy, INFINITE);

        TRACE("State: %d\n", This->state);

        switch (This->state)
        {
        case Req_Die: PullPin_Thread_Stop(This); break;
572 573
        case Req_Run: PullPin_Thread_Process(This); break;
        case Req_Pause: PullPin_Thread_Pause(This); break;
574 575 576 577
        case Req_Sleepy: ERR("Should not be signalled with SLEEPY!\n"); break;
        default: ERR("Unknown state request: %d\n", This->state); break;
        }
    }
578
    return 0;
579 580
}

581
static HRESULT PullPin_InitProcessing(PullPin * This)
582 583 584
{
    HRESULT hr = S_OK;

585
    TRACE("(%p)->()\n", This);
586 587 588 589

    /* if we are connected */
    if (This->pAlloc)
    {
590 591
        DWORD dwThreadId;

592
        WaitForSingleObject(This->hEventStateChanged, INFINITE);
593
        EnterCriticalSection(This->pin.pCritSec);
594

595 596 597 598 599
        assert(!This->hThread);
        assert(This->state == Req_Die);
        assert(This->stop_playback);
        assert(WaitForSingleObject(This->thread_sleepy, 0) == WAIT_TIMEOUT);
        This->state = Req_Sleepy;
600

601 602 603
        /* AddRef the filter to make sure it and it's pins will be around
         * as long as the thread */
        IBaseFilter_AddRef(This->pin.pinInfo.pFilter);
604

605 606 607 608 609 610 611 612 613 614 615 616

        This->hThread = CreateThread(NULL, 0, PullPin_Thread_Main, This, 0, &dwThreadId);
        if (!This->hThread)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
            IBaseFilter_Release(This->pin.pinInfo.pFilter);
        }

        if (SUCCEEDED(hr))
        {
            SetEvent(This->hEventStateChanged);
            /* If assert fails, that means a command was not processed before the thread previously terminated */
617 618 619 620
        }
        LeaveCriticalSection(This->pin.pCritSec);
    }

621
    TRACE(" -- %x\n", hr);
622 623 624 625 626 627 628

    return hr;
}

HRESULT PullPin_StartProcessing(PullPin * This)
{
    /* if we are connected */
629
    TRACE("(%p)->()\n", This);
630 631 632
    if(This->pAlloc)
    {
        assert(This->hThread);
633 634

        PullPin_WaitForStateChange(This, INFINITE);
635

636 637 638 639 640 641 642 643
        assert(This->state == Req_Sleepy);

        /* Wake up! */
        assert(WaitForSingleObject(This->thread_sleepy, 0) == WAIT_TIMEOUT);
        This->state = Req_Run;
        This->stop_playback = 0;
        ResetEvent(This->hEventStateChanged);
        SetEvent(This->thread_sleepy);
644 645 646 647 648 649 650
    }

    return S_OK;
}

HRESULT PullPin_PauseProcessing(PullPin * This)
{
651 652 653 654 655 656 657
    /* if we are connected */
    TRACE("(%p)->()\n", This);
    if(This->pAlloc)
    {
        assert(This->hThread);

        PullPin_WaitForStateChange(This, INFINITE);
658

659
        EnterCriticalSection(This->pin.pCritSec);
660

661 662 663 664
        assert(!This->stop_playback);
        assert(This->state == Req_Run|| This->state == Req_Sleepy);

        assert(WaitForSingleObject(This->thread_sleepy, 0) == WAIT_TIMEOUT);
665

666
        This->state = Req_Pause;
667
        This->stop_playback = 1;
668
        ResetEvent(This->hEventStateChanged);
669
        SetEvent(This->thread_sleepy);
670

671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
        /* Release any outstanding samples */
        if (This->pReader)
        {
            IMediaSample *pSample;
            DWORD_PTR dwUser;

            do
            {
                pSample = NULL;
                IAsyncReader_WaitForNext(This->pReader, 0, &pSample, &dwUser);
                if (pSample)
                    IMediaSample_Release(pSample);
            } while(pSample);
        }

686
        LeaveCriticalSection(This->pin.pCritSec);
687
    }
688 689 690 691

    return S_OK;
}

692
static HRESULT PullPin_StopProcessing(PullPin * This)
693
{
694 695
    TRACE("(%p)->()\n", This);

696
    /* if we are alive */
697
    assert(This->hThread);
698

699
    PullPin_WaitForStateChange(This, INFINITE);
700

701 702 703 704 705 706 707
    assert(This->state == Req_Pause || This->state == Req_Sleepy);

    This->stop_playback = 1;
    This->state = Req_Die;
    assert(WaitForSingleObject(This->thread_sleepy, 0) == WAIT_TIMEOUT);
    ResetEvent(This->hEventStateChanged);
    SetEvent(This->thread_sleepy);
708 709 710 711 712 713 714 715 716 717
    return S_OK;
}

HRESULT PullPin_WaitForStateChange(PullPin * This, DWORD dwMilliseconds)
{
    if (WaitForSingleObject(This->hEventStateChanged, dwMilliseconds) == WAIT_TIMEOUT)
        return S_FALSE;
    return S_OK;
}

718 719
HRESULT WINAPI PullPin_QueryAccept(IPin * iface, const AM_MEDIA_TYPE * pmt)
{
720
    PullPin *This = impl_PullPin_from_IPin(iface);
721 722 723 724 725 726

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

    return (This->fnQueryAccept(This->pUserData, pmt) == S_OK ? S_OK : S_FALSE);
}

727 728
HRESULT WINAPI PullPin_EndOfStream(IPin * iface)
{
729
    PullPin *This = impl_PullPin_from_IPin(iface);
730 731 732
    HRESULT hr = S_FALSE;

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

734 735 736 737 738 739
    EnterCriticalSection(This->pin.pCritSec);
    hr = SendFurther( iface, deliver_endofstream, NULL, NULL );
    SetEvent(This->hEventStateChanged);
    LeaveCriticalSection(This->pin.pCritSec);

    return hr;
740 741 742 743
}

HRESULT WINAPI PullPin_BeginFlush(IPin * iface)
{
744
    PullPin *This = impl_PullPin_from_IPin(iface);
745
    TRACE("(%p)->()\n", This);
746

747 748 749 750 751 752
    EnterCriticalSection(This->pin.pCritSec);
    {
        SendFurther( iface, deliver_beginflush, NULL, NULL );
    }
    LeaveCriticalSection(This->pin.pCritSec);

753 754
    EnterCriticalSection(&This->thread_lock);
    {
755 756
        if (This->pReader)
            IAsyncReader_BeginFlush(This->pReader);
757
        PullPin_WaitForStateChange(This, INFINITE);
758

759
        if (This->hThread && This->state == Req_Run)
760 761 762 763
        {
            PullPin_PauseProcessing(This);
            PullPin_WaitForStateChange(This, INFINITE);
        }
764
    }
765
    LeaveCriticalSection(&This->thread_lock);
766

767 768
    EnterCriticalSection(This->pin.pCritSec);
    {
769
        This->fnCleanProc(This->pUserData);
770 771 772
    }
    LeaveCriticalSection(This->pin.pCritSec);

773
    return S_OK;
774 775 776 777
}

HRESULT WINAPI PullPin_EndFlush(IPin * iface)
{
778
    PullPin *This = impl_PullPin_from_IPin(iface);
779

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

782 783 784 785 786
    /* Send further first: Else a race condition might terminate processing early */
    EnterCriticalSection(This->pin.pCritSec);
    SendFurther( iface, deliver_endflush, NULL, NULL );
    LeaveCriticalSection(This->pin.pCritSec);

787 788 789
    EnterCriticalSection(&This->thread_lock);
    {
        FILTER_STATE state;
790 791 792 793

        if (This->pReader)
            IAsyncReader_EndFlush(This->pReader);

794 795
        IBaseFilter_GetState(This->pin.pinInfo.pFilter, INFINITE, &state);

796
        if (state != State_Stopped)
797
            PullPin_StartProcessing(This);
798 799

        PullPin_WaitForStateChange(This, INFINITE);
800 801 802 803
    }
    LeaveCriticalSection(&This->thread_lock);

    return S_OK;
804 805
}

806 807 808
HRESULT WINAPI PullPin_Disconnect(IPin *iface)
{
    HRESULT hr;
809
    PullPin *This = impl_PullPin_from_IPin(iface);
810 811 812 813 814 815 816 817 818 819 820 821

    TRACE("()\n");

    EnterCriticalSection(This->pin.pCritSec);
    {
        if (FAILED(hr = IMemAllocator_Decommit(This->pAlloc)))
            ERR("Allocator decommit failed with error %x. Possible memory leak\n", hr);

        if (This->pin.pConnectedTo)
        {
            IPin_Release(This->pin.pConnectedTo);
            This->pin.pConnectedTo = NULL;
822
            PullPin_StopProcessing(This);
823 824 825

            FreeMediaType(&This->pin.mtCurrent);
            ZeroMemory(&This->pin.mtCurrent, sizeof(This->pin.mtCurrent));
826 827 828 829 830 831 832 833 834 835
            hr = S_OK;
        }
        else
            hr = S_FALSE;
    }
    LeaveCriticalSection(This->pin.pCritSec);

    return hr;
}

836 837
HRESULT WINAPI PullPin_NewSegment(IPin * iface, REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
838
    newsegmentargs args;
839 840
    FIXME("(%p)->(%s, %s, %g) stub\n", iface, wine_dbgstr_longlong(tStart), wine_dbgstr_longlong(tStop), dRate);

841 842 843 844 845
    args.tStart = tStart;
    args.tStop = tStop;
    args.rate = dRate;

    return SendFurther( iface, deliver_newsegment, &args, NULL );
846 847 848 849 850
}

static const IPinVtbl PullPin_Vtbl = 
{
    PullPin_QueryInterface,
851
    BasePinImpl_AddRef,
852
    PullPin_Release,
853
    BaseInputPinImpl_Connect,
854
    PullPin_ReceiveConnection,
855
    PullPin_Disconnect,
856 857 858 859 860 861 862 863
    BasePinImpl_ConnectedTo,
    BasePinImpl_ConnectionMediaType,
    BasePinImpl_QueryPinInfo,
    BasePinImpl_QueryDirection,
    BasePinImpl_QueryId,
    PullPin_QueryAccept,
    BasePinImpl_EnumMediaTypes,
    BasePinImpl_QueryInternalConnections,
864 865 866 867 868
    PullPin_EndOfStream,
    PullPin_BeginFlush,
    PullPin_EndFlush,
    PullPin_NewSegment
};