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