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