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