d3dx9: Implement D3DXFVFFromDeclarator.
[wine] / dlls / quartz / pin.c
1 /*
2  * Generic Implementation of IPin Interface
3  *
4  * Copyright 2003 Robert Shearman
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * 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 #include "quartz_private.h"
22 #include "pin.h"
23
24 #include "wine/debug.h"
25 #include "wine/unicode.h"
26 #include "uuids.h"
27 #include "vfwmsgs.h"
28 #include <assert.h>
29
30 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
31
32 static const IPinVtbl InputPin_Vtbl;
33 static const IPinVtbl OutputPin_Vtbl;
34 static const IMemInputPinVtbl MemInputPin_Vtbl;
35 static const IPinVtbl PullPin_Vtbl;
36
37 #define ALIGNDOWN(value,boundary) ((value)/(boundary)*(boundary))
38 #define ALIGNUP(value,boundary) (ALIGNDOWN((value)+(boundary)-1, (boundary)))
39
40 typedef HRESULT (*SendPinFunc)( IPin *to, LPVOID arg );
41
42 /** Helper function, there are a lot of places where the error code is inherited
43  * The following rules apply:
44  *
45  * Return the first received error code (E_NOTIMPL is ignored)
46  * If no errors occur: return the first received non-error-code that isn't S_OK
47  */
48 HRESULT updatehres( HRESULT original, HRESULT new )
49 {
50     if (FAILED( original ) || new == E_NOTIMPL)
51         return original;
52
53     if (FAILED( new ) || original == S_OK)
54         return new;
55
56     return original;
57 }
58
59 /** Sends a message from a pin further to other, similar pins
60  * fnMiddle is called on each pin found further on the stream.
61  * fnEnd (can be NULL) is called when the message can't be sent any further (this is a renderer or source)
62  *
63  * If the pin given is an input pin, the message will be sent downstream to other input pins
64  * If the pin given is an output pin, the message will be sent upstream to other output pins
65  */
66 static HRESULT SendFurther( IPin *from, SendPinFunc fnMiddle, LPVOID arg, SendPinFunc fnEnd )
67 {
68     PIN_INFO pin_info;
69     ULONG amount = 0;
70     HRESULT hr = S_OK;
71     HRESULT hr_return = S_OK;
72     IEnumPins *enumpins = NULL;
73     BOOL foundend = TRUE;
74     PIN_DIRECTION from_dir;
75
76     IPin_QueryDirection( from, &from_dir );
77
78     hr = IPin_QueryInternalConnections( from, NULL, &amount );
79     if (hr != E_NOTIMPL && amount)
80         FIXME("Use QueryInternalConnections!\n");
81      hr = S_OK;
82
83     pin_info.pFilter = NULL;
84     hr = IPin_QueryPinInfo( from, &pin_info );
85     if (FAILED(hr))
86         goto out;
87
88     hr = IBaseFilter_EnumPins( pin_info.pFilter, &enumpins );
89     if (FAILED(hr))
90         goto out;
91
92     hr = IEnumPins_Reset( enumpins );
93     while (hr == S_OK) {
94         IPin *pin = NULL;
95         hr = IEnumPins_Next( enumpins, 1, &pin, NULL );
96         if (hr == VFW_E_ENUM_OUT_OF_SYNC)
97         {
98             hr = IEnumPins_Reset( enumpins );
99             continue;
100         }
101         if (pin)
102         {
103             PIN_DIRECTION dir;
104
105             IPin_QueryDirection( pin, &dir );
106             if (dir != from_dir)
107             {
108                 IPin *connected = NULL;
109
110                 foundend = FALSE;
111                 IPin_ConnectedTo( pin, &connected );
112                 if (connected)
113                 {
114                     HRESULT hr_local;
115
116                     hr_local = fnMiddle( connected, arg );
117                     hr_return = updatehres( hr_return, hr_local );
118                     IPin_Release(connected);
119                 }
120             }
121             IPin_Release( pin );
122         }
123         else
124         {
125             hr = S_OK;
126             break;
127         }
128     }
129
130     if (!foundend)
131         hr = hr_return;
132     else if (fnEnd) {
133         HRESULT hr_local;
134
135         hr_local = fnEnd( from, arg );
136         hr_return = updatehres( hr_return, hr_local );
137     }
138
139 out:
140     if (pin_info.pFilter)
141         IBaseFilter_Release( pin_info.pFilter );
142     return hr;
143 }
144
145
146 static void Copy_PinInfo(PIN_INFO * pDest, const PIN_INFO * pSrc)
147 {
148     /* Tempting to just do a memcpy, but the name field is
149        128 characters long! We will probably never exceed 10
150        most of the time, so we are better off copying 
151        each field manually */
152     strcpyW(pDest->achName, pSrc->achName);
153     pDest->dir = pSrc->dir;
154     pDest->pFilter = pSrc->pFilter;
155 }
156
157 /*** Common pin functions ***/
158
159 ULONG WINAPI IPinImpl_AddRef(IPin * iface)
160 {
161     IPinImpl *This = (IPinImpl *)iface;
162     ULONG refCount = InterlockedIncrement(&This->refCount);
163     
164     TRACE("(%p)->() AddRef from %d\n", iface, refCount - 1);
165     
166     return refCount;
167 }
168
169 HRESULT WINAPI IPinImpl_Disconnect(IPin * iface)
170 {
171     HRESULT hr;
172     IPinImpl *This = (IPinImpl *)iface;
173
174     TRACE("()\n");
175
176     EnterCriticalSection(This->pCritSec);
177     {
178         if (This->pConnectedTo)
179         {
180             IPin_Release(This->pConnectedTo);
181             This->pConnectedTo = NULL;
182             FreeMediaType(&This->mtCurrent);
183             ZeroMemory(&This->mtCurrent, sizeof(This->mtCurrent));
184             hr = S_OK;
185         }
186         else
187             hr = S_FALSE;
188     }
189     LeaveCriticalSection(This->pCritSec);
190     
191     return hr;
192 }
193
194 HRESULT WINAPI IPinImpl_ConnectedTo(IPin * iface, IPin ** ppPin)
195 {
196     HRESULT hr;
197     IPinImpl *This = (IPinImpl *)iface;
198
199     TRACE("(%p)\n", ppPin);
200
201     EnterCriticalSection(This->pCritSec);
202     {
203         if (This->pConnectedTo)
204         {
205             *ppPin = This->pConnectedTo;
206             IPin_AddRef(*ppPin);
207             hr = S_OK;
208         }
209         else
210         {
211             hr = VFW_E_NOT_CONNECTED;
212             *ppPin = NULL;
213         }
214     }
215     LeaveCriticalSection(This->pCritSec);
216
217     return hr;
218 }
219
220 HRESULT WINAPI IPinImpl_ConnectionMediaType(IPin * iface, AM_MEDIA_TYPE * pmt)
221 {
222     HRESULT hr;
223     IPinImpl *This = (IPinImpl *)iface;
224
225     TRACE("(%p/%p)->(%p)\n", This, iface, pmt);
226
227     EnterCriticalSection(This->pCritSec);
228     {
229         if (This->pConnectedTo)
230         {
231             CopyMediaType(pmt, &This->mtCurrent);
232             hr = S_OK;
233         }
234         else
235         {
236             ZeroMemory(pmt, sizeof(*pmt));
237             hr = VFW_E_NOT_CONNECTED;
238         }
239     }
240     LeaveCriticalSection(This->pCritSec);
241
242     return hr;
243 }
244
245 HRESULT WINAPI IPinImpl_QueryPinInfo(IPin * iface, PIN_INFO * pInfo)
246 {
247     IPinImpl *This = (IPinImpl *)iface;
248
249     TRACE("(%p/%p)->(%p)\n", This, iface, pInfo);
250
251     Copy_PinInfo(pInfo, &This->pinInfo);
252     IBaseFilter_AddRef(pInfo->pFilter);
253
254     return S_OK;
255 }
256
257 HRESULT WINAPI IPinImpl_QueryDirection(IPin * iface, PIN_DIRECTION * pPinDir)
258 {
259     IPinImpl *This = (IPinImpl *)iface;
260
261     TRACE("(%p/%p)->(%p)\n", This, iface, pPinDir);
262
263     *pPinDir = This->pinInfo.dir;
264
265     return S_OK;
266 }
267
268 HRESULT WINAPI IPinImpl_QueryId(IPin * iface, LPWSTR * Id)
269 {
270     IPinImpl *This = (IPinImpl *)iface;
271
272     TRACE("(%p/%p)->(%p)\n", This, iface, Id);
273
274     *Id = CoTaskMemAlloc((strlenW(This->pinInfo.achName) + 1) * sizeof(WCHAR));
275     if (!*Id)
276         return E_OUTOFMEMORY;
277
278     strcpyW(*Id, This->pinInfo.achName);
279
280     return S_OK;
281 }
282
283 HRESULT WINAPI IPinImpl_QueryAccept(IPin * iface, const AM_MEDIA_TYPE * pmt)
284 {
285     IPinImpl *This = (IPinImpl *)iface;
286
287     TRACE("(%p/%p)->(%p)\n", This, iface, pmt);
288
289     return (This->fnQueryAccept(This->pUserData, pmt) == S_OK ? S_OK : S_FALSE);
290 }
291
292 HRESULT WINAPI IPinImpl_EnumMediaTypes(IPin * iface, IEnumMediaTypes ** ppEnum)
293 {
294     IPinImpl *This = (IPinImpl *)iface;
295     ENUMMEDIADETAILS emd;
296
297     TRACE("(%p/%p)->(%p)\n", This, iface, ppEnum);
298
299     /* override this method to allow enumeration of your types */
300     emd.cMediaTypes = 0;
301     emd.pMediaTypes = NULL;
302
303     return IEnumMediaTypesImpl_Construct(&emd, ppEnum);
304 }
305
306 HRESULT WINAPI IPinImpl_QueryInternalConnections(IPin * iface, IPin ** apPin, ULONG * cPin)
307 {
308     IPinImpl *This = (IPinImpl *)iface;
309
310     TRACE("(%p/%p)->(%p, %p)\n", This, iface, apPin, cPin);
311
312     return E_NOTIMPL; /* to tell caller that all input pins connected to all output pins */
313 }
314
315 /*** IPin implementation for an input pin ***/
316
317 HRESULT WINAPI InputPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
318 {
319     InputPin *This = (InputPin *)iface;
320
321     TRACE("(%p)->(%s, %p)\n", iface, qzdebugstr_guid(riid), ppv);
322
323     *ppv = NULL;
324
325     if (IsEqualIID(riid, &IID_IUnknown))
326         *ppv = iface;
327     else if (IsEqualIID(riid, &IID_IPin))
328         *ppv = iface;
329     else if (IsEqualIID(riid, &IID_IMemInputPin))
330         *ppv = &This->lpVtblMemInput;
331     else if (IsEqualIID(riid, &IID_IMediaSeeking))
332     {
333         return IBaseFilter_QueryInterface(This->pin.pinInfo.pFilter, &IID_IMediaSeeking, ppv);
334     }
335
336     if (*ppv)
337     {
338         IUnknown_AddRef((IUnknown *)(*ppv));
339         return S_OK;
340     }
341
342     FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
343
344     return E_NOINTERFACE;
345 }
346
347 ULONG WINAPI InputPin_Release(IPin * iface)
348 {
349     InputPin *This = (InputPin *)iface;
350     ULONG refCount = InterlockedDecrement(&This->pin.refCount);
351     
352     TRACE("(%p)->() Release from %d\n", iface, refCount + 1);
353     
354     if (!refCount)
355     {
356         FreeMediaType(&This->pin.mtCurrent);
357         if (This->pAllocator)
358             IMemAllocator_Release(This->pAllocator);
359         This->pAllocator = NULL;
360         This->pin.lpVtbl = NULL;
361         CoTaskMemFree(This);
362         return 0;
363     }
364     else
365         return refCount;
366 }
367
368 HRESULT WINAPI InputPin_Connect(IPin * iface, IPin * pConnector, const AM_MEDIA_TYPE * pmt)
369 {
370     ERR("Outgoing connection on an input pin! (%p, %p)\n", pConnector, pmt);
371
372     return E_UNEXPECTED;
373 }
374
375
376 HRESULT WINAPI InputPin_ReceiveConnection(IPin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
377 {
378     InputPin *This = (InputPin *)iface;
379     PIN_DIRECTION pindirReceive;
380     HRESULT hr = S_OK;
381
382     TRACE("(%p, %p)\n", pReceivePin, pmt);
383     dump_AM_MEDIA_TYPE(pmt);
384
385     EnterCriticalSection(This->pin.pCritSec);
386     {
387         if (This->pin.pConnectedTo)
388             hr = VFW_E_ALREADY_CONNECTED;
389
390         if (SUCCEEDED(hr) && This->pin.fnQueryAccept(This->pin.pUserData, pmt) != S_OK)
391             hr = VFW_E_TYPE_NOT_ACCEPTED; /* FIXME: shouldn't we just map common errors onto
392                                            * VFW_E_TYPE_NOT_ACCEPTED and pass the value on otherwise? */
393
394         if (SUCCEEDED(hr))
395         {
396             IPin_QueryDirection(pReceivePin, &pindirReceive);
397
398             if (pindirReceive != PINDIR_OUTPUT)
399             {
400                 ERR("Can't connect from non-output pin\n");
401                 hr = VFW_E_INVALID_DIRECTION;
402             }
403         }
404
405         if (SUCCEEDED(hr))
406         {
407             CopyMediaType(&This->pin.mtCurrent, pmt);
408             This->pin.pConnectedTo = pReceivePin;
409             IPin_AddRef(pReceivePin);
410         }
411     }
412     LeaveCriticalSection(This->pin.pCritSec);
413
414     return hr;
415 }
416
417 static HRESULT deliver_endofstream(IPin* pin, LPVOID unused)
418 {
419     return IPin_EndOfStream( pin );
420 }
421
422 HRESULT WINAPI InputPin_EndOfStream(IPin * iface)
423 {
424     HRESULT hr = S_OK;
425     InputPin *This = (InputPin *)iface;
426
427     TRACE("(%p)\n", This);
428
429     EnterCriticalSection(This->pin.pCritSec);
430     if (This->flushing)
431         hr = S_FALSE;
432     else
433         This->end_of_stream = 1;
434     LeaveCriticalSection(This->pin.pCritSec);
435
436     if (hr == S_OK)
437         hr = SendFurther( iface, deliver_endofstream, NULL, NULL );
438     return hr;
439 }
440
441 static HRESULT deliver_beginflush(IPin* pin, LPVOID unused)
442 {
443     return IPin_BeginFlush( pin );
444 }
445
446 HRESULT WINAPI InputPin_BeginFlush(IPin * iface)
447 {
448     InputPin *This = (InputPin *)iface;
449     HRESULT hr;
450     TRACE("() semi-stub\n");
451
452     EnterCriticalSection(This->pin.pCritSec);
453     This->flushing = 1;
454
455     if (This->fnCleanProc)
456         This->fnCleanProc(This->pin.pUserData);
457
458     hr = SendFurther( iface, deliver_beginflush, NULL, NULL );
459     LeaveCriticalSection(This->pin.pCritSec);
460
461     return hr;
462 }
463
464 static HRESULT deliver_endflush(IPin* pin, LPVOID unused)
465 {
466     return IPin_EndFlush( pin );
467 }
468
469 HRESULT WINAPI InputPin_EndFlush(IPin * iface)
470 {
471     InputPin *This = (InputPin *)iface;
472     HRESULT hr;
473     TRACE("(%p)\n", This);
474
475     EnterCriticalSection(This->pin.pCritSec);
476     This->flushing = This->end_of_stream = 0;
477
478     hr = SendFurther( iface, deliver_endflush, NULL, NULL );
479     LeaveCriticalSection(This->pin.pCritSec);
480
481     return hr;
482 }
483
484 typedef struct newsegmentargs
485 {
486     REFERENCE_TIME tStart, tStop;
487     double rate;
488 } newsegmentargs;
489
490 static HRESULT deliver_newsegment(IPin *pin, LPVOID data)
491 {
492     newsegmentargs *args = data;
493     return IPin_NewSegment(pin, args->tStart, args->tStop, args->rate);
494 }
495
496 HRESULT WINAPI InputPin_NewSegment(IPin * iface, REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
497 {
498     InputPin *This = (InputPin *)iface;
499     newsegmentargs args;
500
501     TRACE("(%x%08x, %x%08x, %e)\n", (ULONG)(tStart >> 32), (ULONG)tStart, (ULONG)(tStop >> 32), (ULONG)tStop, dRate);
502
503     args.tStart = This->tStart = tStart;
504     args.tStop = This->tStop = tStop;
505     args.rate = This->dRate = dRate;
506
507     return SendFurther( iface, deliver_newsegment, &args, NULL );
508 }
509
510 static const IPinVtbl InputPin_Vtbl = 
511 {
512     InputPin_QueryInterface,
513     IPinImpl_AddRef,
514     InputPin_Release,
515     InputPin_Connect,
516     InputPin_ReceiveConnection,
517     IPinImpl_Disconnect,
518     IPinImpl_ConnectedTo,
519     IPinImpl_ConnectionMediaType,
520     IPinImpl_QueryPinInfo,
521     IPinImpl_QueryDirection,
522     IPinImpl_QueryId,
523     IPinImpl_QueryAccept,
524     IPinImpl_EnumMediaTypes,
525     IPinImpl_QueryInternalConnections,
526     InputPin_EndOfStream,
527     InputPin_BeginFlush,
528     InputPin_EndFlush,
529     InputPin_NewSegment
530 };
531
532 /*** IMemInputPin implementation ***/
533
534 static inline InputPin *impl_from_IMemInputPin( IMemInputPin *iface )
535 {
536     return (InputPin *)((char*)iface - FIELD_OFFSET(InputPin, lpVtblMemInput));
537 }
538
539 static HRESULT WINAPI MemInputPin_QueryInterface(IMemInputPin * iface, REFIID riid, LPVOID * ppv)
540 {
541     InputPin *This = impl_from_IMemInputPin(iface);
542
543     return IPin_QueryInterface((IPin *)&This->pin, riid, ppv);
544 }
545
546 static ULONG WINAPI MemInputPin_AddRef(IMemInputPin * iface)
547 {
548     InputPin *This = impl_from_IMemInputPin(iface);
549
550     return IPin_AddRef((IPin *)&This->pin);
551 }
552
553 static ULONG WINAPI MemInputPin_Release(IMemInputPin * iface)
554 {
555     InputPin *This = impl_from_IMemInputPin(iface);
556
557     return IPin_Release((IPin *)&This->pin);
558 }
559
560 static HRESULT WINAPI MemInputPin_GetAllocator(IMemInputPin * iface, IMemAllocator ** ppAllocator)
561 {
562     InputPin *This = impl_from_IMemInputPin(iface);
563
564     TRACE("(%p/%p)->(%p)\n", This, iface, ppAllocator);
565
566     *ppAllocator = This->pAllocator;
567     if (*ppAllocator)
568         IMemAllocator_AddRef(*ppAllocator);
569     
570     return *ppAllocator ? S_OK : VFW_E_NO_ALLOCATOR;
571 }
572
573 static HRESULT WINAPI MemInputPin_NotifyAllocator(IMemInputPin * iface, IMemAllocator * pAllocator, BOOL bReadOnly)
574 {
575     InputPin *This = impl_from_IMemInputPin(iface);
576
577     TRACE("(%p/%p)->(%p, %d)\n", This, iface, pAllocator, bReadOnly);
578
579     if (bReadOnly)
580         FIXME("Read only flag not handled yet!\n");
581
582     /* FIXME: Should we release the allocator on disconnection? */
583     if (!pAllocator)
584     {
585         WARN("Null allocator\n");
586         return E_POINTER;
587     }
588
589     if (This->preferred_allocator && pAllocator != This->preferred_allocator)
590         return E_FAIL;
591
592     if (This->pAllocator)
593         IMemAllocator_Release(This->pAllocator);
594     This->pAllocator = pAllocator;
595     if (This->pAllocator)
596         IMemAllocator_AddRef(This->pAllocator);
597
598     return S_OK;
599 }
600
601 static HRESULT WINAPI MemInputPin_GetAllocatorRequirements(IMemInputPin * iface, ALLOCATOR_PROPERTIES * pProps)
602 {
603     InputPin *This = impl_from_IMemInputPin(iface);
604
605     TRACE("(%p/%p)->(%p)\n", This, iface, pProps);
606
607     /* override this method if you have any specific requirements */
608
609     return E_NOTIMPL;
610 }
611
612 static HRESULT WINAPI MemInputPin_Receive(IMemInputPin * iface, IMediaSample * pSample)
613 {
614     InputPin *This = impl_from_IMemInputPin(iface);
615     HRESULT hr;
616
617     /* this trace commented out for performance reasons */
618     /*TRACE("(%p/%p)->(%p)\n", This, iface, pSample);*/
619     hr = This->fnSampleProc(This->pin.pUserData, pSample);
620     return hr;
621 }
622
623 static HRESULT WINAPI MemInputPin_ReceiveMultiple(IMemInputPin * iface, IMediaSample ** pSamples, LONG nSamples, LONG *nSamplesProcessed)
624 {
625     HRESULT hr = S_OK;
626     InputPin *This = impl_from_IMemInputPin(iface);
627
628     TRACE("(%p/%p)->(%p, %d, %p)\n", This, iface, pSamples, nSamples, nSamplesProcessed);
629
630     for (*nSamplesProcessed = 0; *nSamplesProcessed < nSamples; (*nSamplesProcessed)++)
631     {
632         hr = IMemInputPin_Receive(iface, pSamples[*nSamplesProcessed]);
633         if (hr != S_OK)
634             break;
635     }
636
637     return hr;
638 }
639
640 static HRESULT WINAPI MemInputPin_ReceiveCanBlock(IMemInputPin * iface)
641 {
642     InputPin *This = impl_from_IMemInputPin(iface);
643
644     TRACE("(%p/%p)->()\n", This, iface);
645
646     return S_OK;
647 }
648
649 static const IMemInputPinVtbl MemInputPin_Vtbl = 
650 {
651     MemInputPin_QueryInterface,
652     MemInputPin_AddRef,
653     MemInputPin_Release,
654     MemInputPin_GetAllocator,
655     MemInputPin_NotifyAllocator,
656     MemInputPin_GetAllocatorRequirements,
657     MemInputPin_Receive,
658     MemInputPin_ReceiveMultiple,
659     MemInputPin_ReceiveCanBlock
660 };
661
662 /*** OutputPin implementation ***/
663
664 HRESULT WINAPI OutputPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
665 {
666     OutputPin *This = (OutputPin *)iface;
667
668     TRACE("(%p/%p)->(%s, %p)\n", This, iface, qzdebugstr_guid(riid), ppv);
669
670     *ppv = NULL;
671
672     if (IsEqualIID(riid, &IID_IUnknown))
673         *ppv = iface;
674     else if (IsEqualIID(riid, &IID_IPin))
675         *ppv = iface;
676     else if (IsEqualIID(riid, &IID_IMediaSeeking))
677     {
678         return IBaseFilter_QueryInterface(This->pin.pinInfo.pFilter, &IID_IMediaSeeking, ppv);
679     }
680
681     if (*ppv)
682     {
683         IUnknown_AddRef((IUnknown *)(*ppv));
684         return S_OK;
685     }
686
687     FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
688
689     return E_NOINTERFACE;
690 }
691
692 ULONG WINAPI OutputPin_Release(IPin * iface)
693 {
694     OutputPin *This = (OutputPin *)iface;
695     ULONG refCount = InterlockedDecrement(&This->pin.refCount);
696
697     TRACE("(%p)->() Release from %d\n", iface, refCount + 1);
698
699     if (!refCount)
700     {
701         FreeMediaType(&This->pin.mtCurrent);
702         CoTaskMemFree(This);
703         return 0;
704     }
705     return refCount;
706 }
707
708 HRESULT WINAPI OutputPin_Connect(IPin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
709 {
710     HRESULT hr;
711     OutputPin *This = (OutputPin *)iface;
712
713     TRACE("(%p/%p)->(%p, %p)\n", This, iface, pReceivePin, pmt);
714     dump_AM_MEDIA_TYPE(pmt);
715
716     /* If we try to connect to ourself, we will definitely deadlock.
717      * There are other cases where we could deadlock too, but this
718      * catches the obvious case */
719     assert(pReceivePin != iface);
720
721     EnterCriticalSection(This->pin.pCritSec);
722     {
723         /* if we have been a specific type to connect with, then we can either connect
724          * with that or fail. We cannot choose different AM_MEDIA_TYPE */
725         if (pmt && !IsEqualGUID(&pmt->majortype, &GUID_NULL) && !IsEqualGUID(&pmt->subtype, &GUID_NULL))
726             hr = This->pConnectSpecific(iface, pReceivePin, pmt);
727         else
728         {
729             /* negotiate media type */
730
731             IEnumMediaTypes * pEnumCandidates;
732             AM_MEDIA_TYPE * pmtCandidate = NULL; /* Candidate media type */
733
734             if (SUCCEEDED(hr = IPin_EnumMediaTypes(iface, &pEnumCandidates)))
735             {
736                 hr = VFW_E_NO_ACCEPTABLE_TYPES; /* Assume the worst, but set to S_OK if connected successfully */
737
738                 /* try this filter's media types first */
739                 while (S_OK == IEnumMediaTypes_Next(pEnumCandidates, 1, &pmtCandidate, NULL))
740                 {
741                     assert(pmtCandidate);
742                     dump_AM_MEDIA_TYPE(pmtCandidate);
743                     if (!IsEqualGUID(&FORMAT_None, &pmtCandidate->formattype)
744                         && !IsEqualGUID(&GUID_NULL, &pmtCandidate->formattype))
745                         assert(pmtCandidate->pbFormat);
746                     if (( !pmt || CompareMediaTypes(pmt, pmtCandidate, TRUE) ) && 
747                         (This->pConnectSpecific(iface, pReceivePin, pmtCandidate) == S_OK))
748                     {
749                         hr = S_OK;
750                         DeleteMediaType(pmtCandidate);
751                         break;
752                     }
753                     DeleteMediaType(pmtCandidate);
754                     pmtCandidate = NULL;
755                 }
756                 IEnumMediaTypes_Release(pEnumCandidates);
757             }
758
759             /* then try receiver filter's media types */
760             if (hr != S_OK && SUCCEEDED(hr = IPin_EnumMediaTypes(pReceivePin, &pEnumCandidates))) /* if we haven't already connected successfully */
761             {
762                 hr = VFW_E_NO_ACCEPTABLE_TYPES; /* Assume the worst, but set to S_OK if connected successfully */
763
764                 while (S_OK == IEnumMediaTypes_Next(pEnumCandidates, 1, &pmtCandidate, NULL))
765                 {
766                     assert(pmtCandidate);
767                     dump_AM_MEDIA_TYPE(pmtCandidate);
768                     if (( !pmt || CompareMediaTypes(pmt, pmtCandidate, TRUE) ) && 
769                         (This->pConnectSpecific(iface, pReceivePin, pmtCandidate) == S_OK))
770                     {
771                         hr = S_OK;
772                         DeleteMediaType(pmtCandidate);
773                         break;
774                     }
775                     DeleteMediaType(pmtCandidate);
776                     pmtCandidate = NULL;
777                 } /* while */
778                 IEnumMediaTypes_Release(pEnumCandidates);
779             } /* if not found */
780         } /* if negotiate media type */
781     } /* if succeeded */
782     LeaveCriticalSection(This->pin.pCritSec);
783
784     TRACE(" -- %x\n", hr);
785     return hr;
786 }
787
788 HRESULT WINAPI OutputPin_ReceiveConnection(IPin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
789 {
790     ERR("Incoming connection on an output pin! (%p, %p)\n", pReceivePin, pmt);
791
792     return E_UNEXPECTED;
793 }
794
795 HRESULT WINAPI OutputPin_Disconnect(IPin * iface)
796 {
797     HRESULT hr;
798     OutputPin *This = (OutputPin *)iface;
799
800     TRACE("()\n");
801
802     EnterCriticalSection(This->pin.pCritSec);
803     {
804         if (This->pMemInputPin)
805         {
806             IMemInputPin_Release(This->pMemInputPin);
807             This->pMemInputPin = NULL;
808         }
809         if (This->pin.pConnectedTo)
810         {
811             IPin_Release(This->pin.pConnectedTo);
812             This->pin.pConnectedTo = NULL;
813             FreeMediaType(&This->pin.mtCurrent);
814             ZeroMemory(&This->pin.mtCurrent, sizeof(This->pin.mtCurrent));
815             hr = S_OK;
816         }
817         else
818             hr = S_FALSE;
819     }
820     LeaveCriticalSection(This->pin.pCritSec);
821
822     return hr;
823 }
824
825 HRESULT WINAPI OutputPin_EndOfStream(IPin * iface)
826 {
827     TRACE("()\n");
828
829     /* not supposed to do anything in an output pin */
830
831     return E_UNEXPECTED;
832 }
833
834 HRESULT WINAPI OutputPin_BeginFlush(IPin * iface)
835 {
836     TRACE("(%p)->()\n", iface);
837
838     /* not supposed to do anything in an output pin */
839
840     return E_UNEXPECTED;
841 }
842
843 HRESULT WINAPI OutputPin_EndFlush(IPin * iface)
844 {
845     TRACE("(%p)->()\n", iface);
846
847     /* not supposed to do anything in an output pin */
848
849     return E_UNEXPECTED;
850 }
851
852 HRESULT WINAPI OutputPin_NewSegment(IPin * iface, REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
853 {
854     TRACE("(%p)->(%x%08x, %x%08x, %e)\n", iface, (ULONG)(tStart >> 32), (ULONG)tStart, (ULONG)(tStop >> 32), (ULONG)tStop, dRate);
855
856     /* not supposed to do anything in an output pin */
857
858     return E_UNEXPECTED;
859 }
860
861 static const IPinVtbl OutputPin_Vtbl = 
862 {
863     OutputPin_QueryInterface,
864     IPinImpl_AddRef,
865     OutputPin_Release,
866     OutputPin_Connect,
867     OutputPin_ReceiveConnection,
868     OutputPin_Disconnect,
869     IPinImpl_ConnectedTo,
870     IPinImpl_ConnectionMediaType,
871     IPinImpl_QueryPinInfo,
872     IPinImpl_QueryDirection,
873     IPinImpl_QueryId,
874     IPinImpl_QueryAccept,
875     IPinImpl_EnumMediaTypes,
876     IPinImpl_QueryInternalConnections,
877     OutputPin_EndOfStream,
878     OutputPin_BeginFlush,
879     OutputPin_EndFlush,
880     OutputPin_NewSegment
881 };
882
883 HRESULT OutputPin_GetDeliveryBuffer(OutputPin * This, IMediaSample ** ppSample, REFERENCE_TIME * tStart, REFERENCE_TIME * tStop, DWORD dwFlags)
884 {
885     HRESULT hr;
886
887     TRACE("(%p, %p, %p, %x)\n", ppSample, tStart, tStop, dwFlags);
888
889     EnterCriticalSection(This->pin.pCritSec);
890     {
891         if (!This->pin.pConnectedTo)
892             hr = VFW_E_NOT_CONNECTED;
893         else
894         {
895             IMemAllocator * pAlloc = NULL;
896             
897             hr = IMemInputPin_GetAllocator(This->pMemInputPin, &pAlloc);
898
899             if (SUCCEEDED(hr))
900                 hr = IMemAllocator_GetBuffer(pAlloc, ppSample, tStart, tStop, dwFlags);
901
902             if (SUCCEEDED(hr))
903                 hr = IMediaSample_SetTime(*ppSample, tStart, tStop);
904
905             if (pAlloc)
906                 IMemAllocator_Release(pAlloc);
907         }
908     }
909     LeaveCriticalSection(This->pin.pCritSec);
910     
911     return hr;
912 }
913
914 HRESULT OutputPin_SendSample(OutputPin * This, IMediaSample * pSample)
915 {
916     HRESULT hr = S_OK;
917     IMemInputPin * pMemConnected = NULL;
918     PIN_INFO pinInfo;
919
920     EnterCriticalSection(This->pin.pCritSec);
921     {
922         if (!This->pin.pConnectedTo || !This->pMemInputPin)
923             hr = VFW_E_NOT_CONNECTED;
924         else
925         {
926             /* we don't have the lock held when using This->pMemInputPin,
927              * so we need to AddRef it to stop it being deleted while we are
928              * using it. Same with its filter. */
929             pMemConnected = This->pMemInputPin;
930             IMemInputPin_AddRef(pMemConnected);
931             hr = IPin_QueryPinInfo(This->pin.pConnectedTo, &pinInfo);
932         }
933     }
934     LeaveCriticalSection(This->pin.pCritSec);
935
936     if (SUCCEEDED(hr))
937     {
938         /* NOTE: if we are in a critical section when Receive is called
939          * then it causes some problems (most notably with the native Video
940          * Renderer) if we are re-entered for whatever reason */
941         hr = IMemInputPin_Receive(pMemConnected, pSample);
942
943         /* If the filter's destroyed, tell upstream to stop sending data */
944         if(IBaseFilter_Release(pinInfo.pFilter) == 0 && SUCCEEDED(hr))
945             hr = S_FALSE;
946     }
947     if (pMemConnected)
948         IMemInputPin_Release(pMemConnected);
949
950     return hr;
951 }
952
953 HRESULT OutputPin_CommitAllocator(OutputPin * This)
954 {
955     HRESULT hr = S_OK;
956
957     TRACE("(%p)->()\n", This);
958
959     EnterCriticalSection(This->pin.pCritSec);
960     {
961         if (!This->pin.pConnectedTo || !This->pMemInputPin)
962             hr = VFW_E_NOT_CONNECTED;
963         else
964         {
965             IMemAllocator * pAlloc = NULL;
966
967             hr = IMemInputPin_GetAllocator(This->pMemInputPin, &pAlloc);
968
969             if (SUCCEEDED(hr))
970                 hr = IMemAllocator_Commit(pAlloc);
971
972             if (pAlloc)
973                 IMemAllocator_Release(pAlloc);
974         }
975     }
976     LeaveCriticalSection(This->pin.pCritSec);
977
978     TRACE("--> %08x\n", hr);
979     return hr;
980 }
981
982 HRESULT OutputPin_DecommitAllocator(OutputPin * This)
983 {
984     HRESULT hr = S_OK;
985
986     TRACE("(%p)->()\n", This);
987
988     EnterCriticalSection(This->pin.pCritSec);
989     {
990         if (!This->pin.pConnectedTo || !This->pMemInputPin)
991             hr = VFW_E_NOT_CONNECTED;
992         else
993         {
994             IMemAllocator * pAlloc = NULL;
995
996             hr = IMemInputPin_GetAllocator(This->pMemInputPin, &pAlloc);
997
998             if (SUCCEEDED(hr))
999                 hr = IMemAllocator_Decommit(pAlloc);
1000
1001             if (pAlloc)
1002                 IMemAllocator_Release(pAlloc);
1003         }
1004     }
1005     LeaveCriticalSection(This->pin.pCritSec);
1006
1007     TRACE("--> %08x\n", hr);
1008     return hr;
1009 }
1010
1011 HRESULT OutputPin_DeliverDisconnect(OutputPin * This)
1012 {
1013     HRESULT hr;
1014
1015     TRACE("(%p)->()\n", This);
1016
1017     EnterCriticalSection(This->pin.pCritSec);
1018     {
1019         if (!This->pin.pConnectedTo || !This->pMemInputPin)
1020             hr = VFW_E_NOT_CONNECTED;
1021         else if (!This->custom_allocator)
1022         {
1023             IMemAllocator * pAlloc = NULL;
1024
1025             hr = IMemInputPin_GetAllocator(This->pMemInputPin, &pAlloc);
1026
1027             if (SUCCEEDED(hr))
1028                 hr = IMemAllocator_Decommit(pAlloc);
1029
1030             if (pAlloc)
1031                 IMemAllocator_Release(pAlloc);
1032
1033             if (SUCCEEDED(hr))
1034                 hr = IPin_Disconnect(This->pin.pConnectedTo);
1035         }
1036         else /* Kill the allocator! */
1037         {
1038             hr = IPin_Disconnect(This->pin.pConnectedTo);
1039         }
1040         IPin_Disconnect((IPin *)This);
1041     }
1042     LeaveCriticalSection(This->pin.pCritSec);
1043
1044     return hr;
1045 }
1046
1047 /*** PullPin implementation ***/
1048
1049 static HRESULT PullPin_Init(const IPinVtbl *PullPin_Vtbl, const PIN_INFO * pPinInfo, SAMPLEPROC_PULL pSampleProc, LPVOID pUserData,
1050                             QUERYACCEPTPROC pQueryAccept, CLEANUPPROC pCleanUp, REQUESTPROC pCustomRequest, STOPPROCESSPROC pDone, LPCRITICAL_SECTION pCritSec, PullPin * pPinImpl)
1051 {
1052     /* Common attributes */
1053     pPinImpl->pin.lpVtbl = PullPin_Vtbl;
1054     pPinImpl->pin.refCount = 1;
1055     pPinImpl->pin.pConnectedTo = NULL;
1056     pPinImpl->pin.fnQueryAccept = pQueryAccept;
1057     pPinImpl->pin.pUserData = pUserData;
1058     pPinImpl->pin.pCritSec = pCritSec;
1059     Copy_PinInfo(&pPinImpl->pin.pinInfo, pPinInfo);
1060     ZeroMemory(&pPinImpl->pin.mtCurrent, sizeof(AM_MEDIA_TYPE));
1061
1062     /* Input pin attributes */
1063     pPinImpl->fnSampleProc = pSampleProc;
1064     pPinImpl->fnCleanProc = pCleanUp;
1065     pPinImpl->fnDone = pDone;
1066     pPinImpl->fnPreConnect = NULL;
1067     pPinImpl->pAlloc = NULL;
1068     pPinImpl->pReader = NULL;
1069     pPinImpl->hThread = NULL;
1070     pPinImpl->hEventStateChanged = CreateEventW(NULL, TRUE, TRUE, NULL);
1071     pPinImpl->thread_sleepy = CreateEventW(NULL, FALSE, FALSE, NULL);
1072
1073     pPinImpl->rtStart = 0;
1074     pPinImpl->rtCurrent = 0;
1075     pPinImpl->rtStop = ((LONGLONG)0x7fffffff << 32) | 0xffffffff;
1076     pPinImpl->dRate = 1.0;
1077     pPinImpl->state = Req_Die;
1078     pPinImpl->fnCustomRequest = pCustomRequest;
1079     pPinImpl->stop_playback = 1;
1080
1081     InitializeCriticalSection(&pPinImpl->thread_lock);
1082     pPinImpl->thread_lock.DebugInfo->Spare[0] = (DWORD_PTR)( __FILE__ ": PullPin.thread_lock");
1083
1084     return S_OK;
1085 }
1086
1087 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)
1088 {
1089     PullPin * pPinImpl;
1090
1091     *ppPin = NULL;
1092
1093     if (pPinInfo->dir != PINDIR_INPUT)
1094     {
1095         ERR("Pin direction(%x) != PINDIR_INPUT\n", pPinInfo->dir);
1096         return E_INVALIDARG;
1097     }
1098
1099     pPinImpl = CoTaskMemAlloc(sizeof(*pPinImpl));
1100
1101     if (!pPinImpl)
1102         return E_OUTOFMEMORY;
1103
1104     if (SUCCEEDED(PullPin_Init(PullPin_Vtbl, pPinInfo, pSampleProc, pUserData, pQueryAccept, pCleanUp, pCustomRequest, pDone, pCritSec, pPinImpl)))
1105     {
1106         *ppPin = (IPin *)(&pPinImpl->pin.lpVtbl);
1107         return S_OK;
1108     }
1109
1110     CoTaskMemFree(pPinImpl);
1111     return E_FAIL;
1112 }
1113
1114 static HRESULT PullPin_InitProcessing(PullPin * This);
1115
1116 HRESULT WINAPI PullPin_ReceiveConnection(IPin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
1117 {
1118     PIN_DIRECTION pindirReceive;
1119     HRESULT hr = S_OK;
1120     PullPin *This = (PullPin *)iface;
1121
1122     TRACE("(%p/%p)->(%p, %p)\n", This, iface, pReceivePin, pmt);
1123     dump_AM_MEDIA_TYPE(pmt);
1124
1125     EnterCriticalSection(This->pin.pCritSec);
1126     if (!This->pin.pConnectedTo)
1127     {
1128         ALLOCATOR_PROPERTIES props;
1129
1130         props.cBuffers = 3;
1131         props.cbBuffer = 64 * 1024; /* 64k bytes */
1132         props.cbAlign = 1;
1133         props.cbPrefix = 0;
1134
1135         if (SUCCEEDED(hr) && (This->pin.fnQueryAccept(This->pin.pUserData, pmt) != S_OK))
1136             hr = VFW_E_TYPE_NOT_ACCEPTED; /* FIXME: shouldn't we just map common errors onto 
1137                                            * VFW_E_TYPE_NOT_ACCEPTED and pass the value on otherwise? */
1138
1139         if (SUCCEEDED(hr))
1140         {
1141             IPin_QueryDirection(pReceivePin, &pindirReceive);
1142
1143             if (pindirReceive != PINDIR_OUTPUT)
1144             {
1145                 ERR("Can't connect from non-output pin\n");
1146                 hr = VFW_E_INVALID_DIRECTION;
1147             }
1148         }
1149
1150         This->pReader = NULL;
1151         This->pAlloc = NULL;
1152         if (SUCCEEDED(hr))
1153         {
1154             hr = IPin_QueryInterface(pReceivePin, &IID_IAsyncReader, (LPVOID *)&This->pReader);
1155         }
1156
1157         if (SUCCEEDED(hr) && This->fnPreConnect)
1158         {
1159             hr = This->fnPreConnect(iface, pReceivePin, &props);
1160         }
1161
1162         if (SUCCEEDED(hr))
1163         {
1164             hr = IAsyncReader_RequestAllocator(This->pReader, NULL, &props, &This->pAlloc);
1165         }
1166
1167         if (SUCCEEDED(hr))
1168         {
1169             CopyMediaType(&This->pin.mtCurrent, pmt);
1170             This->pin.pConnectedTo = pReceivePin;
1171             IPin_AddRef(pReceivePin);
1172             hr = IMemAllocator_Commit(This->pAlloc);
1173         }
1174
1175         if (SUCCEEDED(hr))
1176             hr = PullPin_InitProcessing(This);
1177
1178         if (FAILED(hr))
1179         {
1180              if (This->pReader)
1181                  IAsyncReader_Release(This->pReader);
1182              This->pReader = NULL;
1183              if (This->pAlloc)
1184                  IMemAllocator_Release(This->pAlloc);
1185              This->pAlloc = NULL;
1186         }
1187     }
1188     else
1189         hr = VFW_E_ALREADY_CONNECTED;
1190     LeaveCriticalSection(This->pin.pCritSec);
1191     return hr;
1192 }
1193
1194 HRESULT WINAPI PullPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
1195 {
1196     PullPin *This = (PullPin *)iface;
1197
1198     TRACE("(%p/%p)->(%s, %p)\n", This, iface, qzdebugstr_guid(riid), ppv);
1199
1200     *ppv = NULL;
1201
1202     if (IsEqualIID(riid, &IID_IUnknown))
1203         *ppv = iface;
1204     else if (IsEqualIID(riid, &IID_IPin))
1205         *ppv = iface;
1206     else if (IsEqualIID(riid, &IID_IMediaSeeking))
1207     {
1208         return IBaseFilter_QueryInterface(This->pin.pinInfo.pFilter, &IID_IMediaSeeking, ppv);
1209     }
1210
1211     if (*ppv)
1212     {
1213         IUnknown_AddRef((IUnknown *)(*ppv));
1214         return S_OK;
1215     }
1216
1217     FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
1218
1219     return E_NOINTERFACE;
1220 }
1221
1222 ULONG WINAPI PullPin_Release(IPin *iface)
1223 {
1224     PullPin *This = (PullPin *)iface;
1225     ULONG refCount = InterlockedDecrement(&This->pin.refCount);
1226
1227     TRACE("(%p)->() Release from %d\n", This, refCount + 1);
1228
1229     if (!refCount)
1230     {
1231         WaitForSingleObject(This->hEventStateChanged, INFINITE);
1232         assert(!This->hThread);
1233
1234         if(This->pAlloc)
1235             IMemAllocator_Release(This->pAlloc);
1236         if(This->pReader)
1237             IAsyncReader_Release(This->pReader);
1238         CloseHandle(This->thread_sleepy);
1239         CloseHandle(This->hEventStateChanged);
1240         This->thread_lock.DebugInfo->Spare[0] = 0;
1241         DeleteCriticalSection(&This->thread_lock);
1242         CoTaskMemFree(This);
1243         return 0;
1244     }
1245     return refCount;
1246 }
1247
1248 static void PullPin_Flush(PullPin *This)
1249 {
1250     IMediaSample *pSample;
1251     TRACE("Flushing!\n");
1252
1253     if (This->pReader)
1254     {
1255         /* Flush outstanding samples */
1256         IAsyncReader_BeginFlush(This->pReader);
1257
1258         for (;;)
1259         {
1260             DWORD_PTR dwUser;
1261
1262             IAsyncReader_WaitForNext(This->pReader, 0, &pSample, &dwUser);
1263
1264             if (!pSample)
1265                 break;
1266
1267             assert(!IMediaSample_GetActualDataLength(pSample));
1268
1269             IMediaSample_Release(pSample);
1270         }
1271
1272         IAsyncReader_EndFlush(This->pReader);
1273     }
1274 }
1275
1276 static void PullPin_Thread_Process(PullPin *This)
1277 {
1278     HRESULT hr;
1279     IMediaSample * pSample = NULL;
1280     ALLOCATOR_PROPERTIES allocProps;
1281
1282     hr = IMemAllocator_GetProperties(This->pAlloc, &allocProps);
1283
1284     This->cbAlign = allocProps.cbAlign;
1285
1286     if (This->rtCurrent < This->rtStart)
1287         This->rtCurrent = MEDIATIME_FROM_BYTES(ALIGNDOWN(BYTES_FROM_MEDIATIME(This->rtStart), This->cbAlign));
1288
1289     TRACE("Start\n");
1290
1291     if (This->rtCurrent >= This->rtStop)
1292     {
1293         IPin_EndOfStream((IPin *)This);
1294         return;
1295     }
1296
1297     /* There is no sample in our buffer */
1298     hr = This->fnCustomRequest(This->pin.pUserData);
1299
1300     if (FAILED(hr))
1301         ERR("Request error: %x\n", hr);
1302
1303     EnterCriticalSection(This->pin.pCritSec);
1304     SetEvent(This->hEventStateChanged);
1305     LeaveCriticalSection(This->pin.pCritSec);
1306
1307     if (SUCCEEDED(hr))
1308     do
1309     {
1310         DWORD_PTR dwUser;
1311
1312         TRACE("Process sample\n");
1313
1314         pSample = NULL;
1315         hr = IAsyncReader_WaitForNext(This->pReader, 10000, &pSample, &dwUser);
1316
1317         /* Return an empty sample on error to the implementation in case it does custom parsing, so it knows it's gone */
1318         if (SUCCEEDED(hr))
1319         {
1320             hr = This->fnSampleProc(This->pin.pUserData, pSample, dwUser);
1321         }
1322         else
1323         {
1324             /* FIXME: This is not well handled yet! */
1325             ERR("Processing error: %x\n", hr);
1326             if (hr == VFW_E_TIMEOUT)
1327             {
1328                 assert(!pSample);
1329                 hr = S_OK;
1330                 continue;
1331             }
1332         }
1333
1334         if (pSample)
1335         {
1336             IMediaSample_Release(pSample);
1337             pSample = NULL;
1338         }
1339     } while (This->rtCurrent < This->rtStop && hr == S_OK && !This->stop_playback);
1340
1341     /* Sample was rejected, and we are asked to terminate */
1342     if (pSample)
1343     {
1344         IMediaSample_Release(pSample);
1345     }
1346
1347     /* Can't reset state to Sleepy here because that might race, instead PauseProcessing will do that for us
1348      * Flush remaining samples
1349      */
1350     if (This->fnDone)
1351         This->fnDone(This->pin.pUserData);
1352
1353     TRACE("End: %08x, %d\n", hr, This->stop_playback);
1354 }
1355
1356 static void PullPin_Thread_Pause(PullPin *This)
1357 {
1358     PullPin_Flush(This);
1359
1360     EnterCriticalSection(This->pin.pCritSec);
1361     This->state = Req_Sleepy;
1362     SetEvent(This->hEventStateChanged);
1363     LeaveCriticalSection(This->pin.pCritSec);
1364 }
1365
1366 static void  PullPin_Thread_Stop(PullPin *This)
1367 {
1368     TRACE("(%p)->()\n", This);
1369
1370     EnterCriticalSection(This->pin.pCritSec);
1371     {
1372         CloseHandle(This->hThread);
1373         This->hThread = NULL;
1374         SetEvent(This->hEventStateChanged);
1375     }
1376     LeaveCriticalSection(This->pin.pCritSec);
1377
1378     IBaseFilter_Release(This->pin.pinInfo.pFilter);
1379
1380     CoUninitialize();
1381     ExitThread(0);
1382 }
1383
1384 static DWORD WINAPI PullPin_Thread_Main(LPVOID pv)
1385 {
1386     PullPin *This = pv;
1387     CoInitializeEx(NULL, COINIT_MULTITHREADED);
1388
1389     PullPin_Flush(This);
1390
1391     for (;;)
1392     {
1393         WaitForSingleObject(This->thread_sleepy, INFINITE);
1394
1395         TRACE("State: %d\n", This->state);
1396
1397         switch (This->state)
1398         {
1399         case Req_Die: PullPin_Thread_Stop(This); break;
1400         case Req_Run: PullPin_Thread_Process(This); break;
1401         case Req_Pause: PullPin_Thread_Pause(This); break;
1402         case Req_Sleepy: ERR("Should not be signalled with SLEEPY!\n"); break;
1403         default: ERR("Unknown state request: %d\n", This->state); break;
1404         }
1405     }
1406     return 0;
1407 }
1408
1409 static HRESULT PullPin_InitProcessing(PullPin * This)
1410 {
1411     HRESULT hr = S_OK;
1412
1413     TRACE("(%p)->()\n", This);
1414
1415     /* if we are connected */
1416     if (This->pAlloc)
1417     {
1418         DWORD dwThreadId;
1419
1420         WaitForSingleObject(This->hEventStateChanged, INFINITE);
1421         EnterCriticalSection(This->pin.pCritSec);
1422
1423         assert(!This->hThread);
1424         assert(This->state == Req_Die);
1425         assert(This->stop_playback);
1426         assert(WaitForSingleObject(This->thread_sleepy, 0) == WAIT_TIMEOUT);
1427         This->state = Req_Sleepy;
1428
1429         /* AddRef the filter to make sure it and it's pins will be around
1430          * as long as the thread */
1431         IBaseFilter_AddRef(This->pin.pinInfo.pFilter);
1432
1433
1434         This->hThread = CreateThread(NULL, 0, PullPin_Thread_Main, This, 0, &dwThreadId);
1435         if (!This->hThread)
1436         {
1437             hr = HRESULT_FROM_WIN32(GetLastError());
1438             IBaseFilter_Release(This->pin.pinInfo.pFilter);
1439         }
1440
1441         if (SUCCEEDED(hr))
1442         {
1443             SetEvent(This->hEventStateChanged);
1444             /* If assert fails, that means a command was not processed before the thread previously terminated */
1445         }
1446         LeaveCriticalSection(This->pin.pCritSec);
1447     }
1448
1449     TRACE(" -- %x\n", hr);
1450
1451     return hr;
1452 }
1453
1454 HRESULT PullPin_StartProcessing(PullPin * This)
1455 {
1456     /* if we are connected */
1457     TRACE("(%p)->()\n", This);
1458     if(This->pAlloc)
1459     {
1460         assert(This->hThread);
1461
1462         PullPin_WaitForStateChange(This, INFINITE);
1463
1464         assert(This->state == Req_Sleepy);
1465
1466         /* Wake up! */
1467         assert(WaitForSingleObject(This->thread_sleepy, 0) == WAIT_TIMEOUT);
1468         This->state = Req_Run;
1469         This->stop_playback = 0;
1470         ResetEvent(This->hEventStateChanged);
1471         SetEvent(This->thread_sleepy);
1472     }
1473
1474     return S_OK;
1475 }
1476
1477 HRESULT PullPin_PauseProcessing(PullPin * This)
1478 {
1479     /* if we are connected */
1480     TRACE("(%p)->()\n", This);
1481     if(This->pAlloc)
1482     {
1483         assert(This->hThread);
1484
1485         PullPin_WaitForStateChange(This, INFINITE);
1486
1487         EnterCriticalSection(This->pin.pCritSec);
1488
1489         assert(!This->stop_playback);
1490         assert(This->state == Req_Run|| This->state == Req_Sleepy);
1491
1492         assert(WaitForSingleObject(This->thread_sleepy, 0) == WAIT_TIMEOUT);
1493         This->state = Req_Pause;
1494         This->stop_playback = 1;
1495         ResetEvent(This->hEventStateChanged);
1496         SetEvent(This->thread_sleepy);
1497
1498         LeaveCriticalSection(This->pin.pCritSec);
1499     }
1500
1501     return S_OK;
1502 }
1503
1504 static HRESULT PullPin_StopProcessing(PullPin * This)
1505 {
1506     TRACE("(%p)->()\n", This);
1507
1508     /* if we are alive */
1509     assert(This->hThread);
1510
1511     PullPin_WaitForStateChange(This, INFINITE);
1512
1513     assert(This->state == Req_Pause || This->state == Req_Sleepy);
1514
1515     This->stop_playback = 1;
1516     This->state = Req_Die;
1517     assert(WaitForSingleObject(This->thread_sleepy, 0) == WAIT_TIMEOUT);
1518     ResetEvent(This->hEventStateChanged);
1519     SetEvent(This->thread_sleepy);
1520     return S_OK;
1521 }
1522
1523 HRESULT PullPin_WaitForStateChange(PullPin * This, DWORD dwMilliseconds)
1524 {
1525     if (WaitForSingleObject(This->hEventStateChanged, dwMilliseconds) == WAIT_TIMEOUT)
1526         return S_FALSE;
1527     return S_OK;
1528 }
1529
1530 HRESULT WINAPI PullPin_EndOfStream(IPin * iface)
1531 {
1532     FIXME("(%p)->() stub\n", iface);
1533
1534     return SendFurther( iface, deliver_endofstream, NULL, NULL );
1535 }
1536
1537 HRESULT WINAPI PullPin_BeginFlush(IPin * iface)
1538 {
1539     PullPin *This = (PullPin *)iface;
1540     TRACE("(%p)->()\n", This);
1541
1542     EnterCriticalSection(This->pin.pCritSec);
1543     {
1544         SendFurther( iface, deliver_beginflush, NULL, NULL );
1545     }
1546     LeaveCriticalSection(This->pin.pCritSec);
1547
1548     EnterCriticalSection(&This->thread_lock);
1549     {
1550         if (This->pReader)
1551             IAsyncReader_BeginFlush(This->pReader);
1552         PullPin_WaitForStateChange(This, INFINITE);
1553
1554         if (This->hThread && This->state == Req_Run)
1555         {
1556             PullPin_PauseProcessing(This);
1557             PullPin_WaitForStateChange(This, INFINITE);
1558         }
1559     }
1560     LeaveCriticalSection(&This->thread_lock);
1561
1562     EnterCriticalSection(This->pin.pCritSec);
1563     {
1564         This->fnCleanProc(This->pin.pUserData);
1565     }
1566     LeaveCriticalSection(This->pin.pCritSec);
1567
1568     return S_OK;
1569 }
1570
1571 HRESULT WINAPI PullPin_EndFlush(IPin * iface)
1572 {
1573     PullPin *This = (PullPin *)iface;
1574
1575     TRACE("(%p)->()\n", iface);
1576
1577     /* Send further first: Else a race condition might terminate processing early */
1578     EnterCriticalSection(This->pin.pCritSec);
1579     SendFurther( iface, deliver_endflush, NULL, NULL );
1580     LeaveCriticalSection(This->pin.pCritSec);
1581
1582     EnterCriticalSection(&This->thread_lock);
1583     {
1584         FILTER_STATE state;
1585
1586         if (This->pReader)
1587             IAsyncReader_EndFlush(This->pReader);
1588
1589         IBaseFilter_GetState(This->pin.pinInfo.pFilter, INFINITE, &state);
1590
1591         if (state != State_Stopped)
1592             PullPin_StartProcessing(This);
1593
1594         PullPin_WaitForStateChange(This, INFINITE);
1595     }
1596     LeaveCriticalSection(&This->thread_lock);
1597
1598     return S_OK;
1599 }
1600
1601 HRESULT WINAPI PullPin_Disconnect(IPin *iface)
1602 {
1603     HRESULT hr;
1604     PullPin *This = (PullPin *)iface;
1605
1606     TRACE("()\n");
1607
1608     EnterCriticalSection(This->pin.pCritSec);
1609     {
1610         if (FAILED(hr = IMemAllocator_Decommit(This->pAlloc)))
1611             ERR("Allocator decommit failed with error %x. Possible memory leak\n", hr);
1612
1613         if (This->pin.pConnectedTo)
1614         {
1615             IPin_Release(This->pin.pConnectedTo);
1616             This->pin.pConnectedTo = NULL;
1617             PullPin_StopProcessing(This);
1618
1619             FreeMediaType(&This->pin.mtCurrent);
1620             ZeroMemory(&This->pin.mtCurrent, sizeof(This->pin.mtCurrent));
1621             hr = S_OK;
1622         }
1623         else
1624             hr = S_FALSE;
1625     }
1626     LeaveCriticalSection(This->pin.pCritSec);
1627
1628     return hr;
1629 }
1630
1631 HRESULT WINAPI PullPin_NewSegment(IPin * iface, REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
1632 {
1633     newsegmentargs args;
1634     FIXME("(%p)->(%s, %s, %g) stub\n", iface, wine_dbgstr_longlong(tStart), wine_dbgstr_longlong(tStop), dRate);
1635
1636     args.tStart = tStart;
1637     args.tStop = tStop;
1638     args.rate = dRate;
1639
1640     return SendFurther( iface, deliver_newsegment, &args, NULL );
1641 }
1642
1643 static const IPinVtbl PullPin_Vtbl = 
1644 {
1645     PullPin_QueryInterface,
1646     IPinImpl_AddRef,
1647     PullPin_Release,
1648     InputPin_Connect,
1649     PullPin_ReceiveConnection,
1650     PullPin_Disconnect,
1651     IPinImpl_ConnectedTo,
1652     IPinImpl_ConnectionMediaType,
1653     IPinImpl_QueryPinInfo,
1654     IPinImpl_QueryDirection,
1655     IPinImpl_QueryId,
1656     IPinImpl_QueryAccept,
1657     IPinImpl_EnumMediaTypes,
1658     IPinImpl_QueryInternalConnections,
1659     PullPin_EndOfStream,
1660     PullPin_BeginFlush,
1661     PullPin_EndFlush,
1662     PullPin_NewSegment
1663 };
1664
1665 /*** The Construct functions ***/
1666
1667 /* Function called as a helper to IPin_Connect */
1668 /* specific AM_MEDIA_TYPE - it cannot be NULL */
1669 /* NOTE: not part of standard interface */
1670 static HRESULT OutputPin_ConnectSpecific(IPin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
1671 {
1672     OutputPin *This = (OutputPin *)iface;
1673     HRESULT hr;
1674     IMemAllocator * pMemAlloc = NULL;
1675     ALLOCATOR_PROPERTIES actual; /* FIXME: should we put the actual props back in to This? */
1676
1677     TRACE("(%p, %p)\n", pReceivePin, pmt);
1678     dump_AM_MEDIA_TYPE(pmt);
1679
1680     /* FIXME: call queryacceptproc */
1681
1682     This->pin.pConnectedTo = pReceivePin;
1683     IPin_AddRef(pReceivePin);
1684     CopyMediaType(&This->pin.mtCurrent, pmt);
1685
1686     hr = IPin_ReceiveConnection(pReceivePin, iface, pmt);
1687
1688     /* get the IMemInputPin interface we will use to deliver samples to the
1689      * connected pin */
1690     if (SUCCEEDED(hr))
1691     {
1692         This->pMemInputPin = NULL;
1693         hr = IPin_QueryInterface(pReceivePin, &IID_IMemInputPin, (LPVOID)&This->pMemInputPin);
1694
1695         if (SUCCEEDED(hr) && !This->custom_allocator)
1696         {
1697             hr = IMemInputPin_GetAllocator(This->pMemInputPin, &pMemAlloc);
1698
1699             if (hr == VFW_E_NO_ALLOCATOR)
1700                 /* Input pin provides no allocator, use standard memory allocator */
1701                 hr = CoCreateInstance(&CLSID_MemoryAllocator, NULL, CLSCTX_INPROC_SERVER, &IID_IMemAllocator, (LPVOID*)&pMemAlloc);
1702
1703             if (SUCCEEDED(hr))
1704                 hr = IMemAllocator_SetProperties(pMemAlloc, &This->allocProps, &actual);
1705
1706             if (SUCCEEDED(hr))
1707                 hr = IMemInputPin_NotifyAllocator(This->pMemInputPin, pMemAlloc, This->readonly);
1708
1709             if (pMemAlloc)
1710                 IMemAllocator_Release(pMemAlloc);
1711         }
1712         else if (SUCCEEDED(hr))
1713         {
1714             if (This->alloc)
1715             {
1716                 hr = IMemInputPin_NotifyAllocator(This->pMemInputPin, This->alloc, This->readonly);
1717             }
1718             else
1719                 hr = VFW_E_NO_ALLOCATOR;
1720         }
1721
1722         /* break connection if we couldn't get the allocator */
1723         if (FAILED(hr))
1724         {
1725             if (This->pMemInputPin)
1726                 IMemInputPin_Release(This->pMemInputPin);
1727             This->pMemInputPin = NULL;
1728
1729             IPin_Disconnect(pReceivePin);
1730         }
1731     }
1732
1733     if (FAILED(hr))
1734     {
1735         IPin_Release(This->pin.pConnectedTo);
1736         This->pin.pConnectedTo = NULL;
1737         FreeMediaType(&This->pin.mtCurrent);
1738     }
1739
1740     TRACE(" -- %x\n", hr);
1741     return hr;
1742 }
1743
1744 static HRESULT InputPin_Init(const IPinVtbl *InputPin_Vtbl, const PIN_INFO * pPinInfo, SAMPLEPROC_PUSH pSampleProc, LPVOID pUserData,
1745                              QUERYACCEPTPROC pQueryAccept, CLEANUPPROC pCleanUp, LPCRITICAL_SECTION pCritSec, IMemAllocator *allocator, InputPin * pPinImpl)
1746 {
1747     TRACE("\n");
1748
1749     /* Common attributes */
1750     pPinImpl->pin.refCount = 1;
1751     pPinImpl->pin.pConnectedTo = NULL;
1752     pPinImpl->pin.fnQueryAccept = pQueryAccept;
1753     pPinImpl->pin.pUserData = pUserData;
1754     pPinImpl->pin.pCritSec = pCritSec;
1755     Copy_PinInfo(&pPinImpl->pin.pinInfo, pPinInfo);
1756     ZeroMemory(&pPinImpl->pin.mtCurrent, sizeof(AM_MEDIA_TYPE));
1757
1758     /* Input pin attributes */
1759     pPinImpl->fnSampleProc = pSampleProc;
1760     pPinImpl->fnCleanProc = pCleanUp;
1761     pPinImpl->pAllocator = pPinImpl->preferred_allocator = allocator;
1762     if (pPinImpl->preferred_allocator)
1763         IMemAllocator_AddRef(pPinImpl->preferred_allocator);
1764     pPinImpl->tStart = 0;
1765     pPinImpl->tStop = 0;
1766     pPinImpl->dRate = 1.0;
1767     pPinImpl->pin.lpVtbl = InputPin_Vtbl;
1768     pPinImpl->lpVtblMemInput = &MemInputPin_Vtbl;
1769     pPinImpl->flushing = pPinImpl->end_of_stream = 0;
1770
1771     return S_OK;
1772 }
1773
1774 static HRESULT OutputPin_Init(const IPinVtbl *OutputPin_Vtbl, const PIN_INFO * pPinInfo, const ALLOCATOR_PROPERTIES * props, LPVOID pUserData,
1775                               QUERYACCEPTPROC pQueryAccept, LPCRITICAL_SECTION pCritSec, OutputPin * pPinImpl)
1776 {
1777     TRACE("\n");
1778
1779     /* Common attributes */
1780     pPinImpl->pin.lpVtbl = OutputPin_Vtbl;
1781     pPinImpl->pin.refCount = 1;
1782     pPinImpl->pin.pConnectedTo = NULL;
1783     pPinImpl->pin.fnQueryAccept = pQueryAccept;
1784     pPinImpl->pin.pUserData = pUserData;
1785     pPinImpl->pin.pCritSec = pCritSec;
1786     Copy_PinInfo(&pPinImpl->pin.pinInfo, pPinInfo);
1787     ZeroMemory(&pPinImpl->pin.mtCurrent, sizeof(AM_MEDIA_TYPE));
1788
1789     /* Output pin attributes */
1790     pPinImpl->pMemInputPin = NULL;
1791     pPinImpl->pConnectSpecific = OutputPin_ConnectSpecific;
1792     /* If custom_allocator is set, you will need to specify an allocator
1793      * in the alloc member of the struct before an output pin can connect
1794      */
1795     pPinImpl->custom_allocator = 0;
1796     pPinImpl->alloc = NULL;
1797     pPinImpl->readonly = FALSE;
1798     if (props)
1799     {
1800         pPinImpl->allocProps = *props;
1801         if (pPinImpl->allocProps.cbAlign == 0)
1802             pPinImpl->allocProps.cbAlign = 1;
1803     }
1804     else
1805         ZeroMemory(&pPinImpl->allocProps, sizeof(pPinImpl->allocProps));
1806
1807     return S_OK;
1808 }
1809
1810 HRESULT InputPin_Construct(const IPinVtbl *InputPin_Vtbl, const PIN_INFO * pPinInfo, SAMPLEPROC_PUSH pSampleProc, LPVOID pUserData, QUERYACCEPTPROC pQueryAccept, CLEANUPPROC pCleanUp, LPCRITICAL_SECTION pCritSec, IMemAllocator *allocator, IPin ** ppPin)
1811 {
1812     InputPin * pPinImpl;
1813
1814     *ppPin = NULL;
1815
1816     if (pPinInfo->dir != PINDIR_INPUT)
1817     {
1818         ERR("Pin direction(%x) != PINDIR_INPUT\n", pPinInfo->dir);
1819         return E_INVALIDARG;
1820     }
1821
1822     pPinImpl = CoTaskMemAlloc(sizeof(*pPinImpl));
1823
1824     if (!pPinImpl)
1825         return E_OUTOFMEMORY;
1826
1827     if (SUCCEEDED(InputPin_Init(InputPin_Vtbl, pPinInfo, pSampleProc, pUserData, pQueryAccept, pCleanUp, pCritSec, allocator, pPinImpl)))
1828     {
1829         *ppPin = (IPin *)pPinImpl;
1830         return S_OK;
1831     }
1832
1833     CoTaskMemFree(pPinImpl);
1834     return E_FAIL;
1835 }
1836
1837 HRESULT OutputPin_Construct(const IPinVtbl *OutputPin_Vtbl, LONG outputpin_size, const PIN_INFO * pPinInfo, ALLOCATOR_PROPERTIES *props, LPVOID pUserData, QUERYACCEPTPROC pQueryAccept, LPCRITICAL_SECTION pCritSec, IPin ** ppPin)
1838 {
1839     OutputPin * pPinImpl;
1840
1841     *ppPin = NULL;
1842
1843     if (pPinInfo->dir != PINDIR_OUTPUT)
1844     {
1845         ERR("Pin direction(%x) != PINDIR_OUTPUT\n", pPinInfo->dir);
1846         return E_INVALIDARG;
1847     }
1848
1849     assert(outputpin_size >= sizeof(OutputPin));
1850
1851     pPinImpl = CoTaskMemAlloc(outputpin_size);
1852
1853     if (!pPinImpl)
1854         return E_OUTOFMEMORY;
1855
1856     if (SUCCEEDED(OutputPin_Init(OutputPin_Vtbl, pPinInfo, props, pUserData, pQueryAccept, pCritSec, pPinImpl)))
1857     {
1858         *ppPin = (IPin *)(&pPinImpl->pin.lpVtbl);
1859         return S_OK;
1860     }
1861
1862     CoTaskMemFree(pPinImpl);
1863     return E_FAIL;
1864 }