atl80: Added AtlComModuleRegisterServer implementation (based on AtlModuleRegisterSer...
[wine] / dlls / winegstreamer / gstdemux.c
1 /*
2  * GStreamer splitter + decoder, adapted from parser.c
3  *
4  * Copyright 2010 Maarten Lankhorst for CodeWeavers
5  * Copyright 2010 Aric Stewart for CodeWeavers
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include <gst/app/gstappsink.h>
24 #include <gst/app/gstappsrc.h>
25 #include <gst/app/gstappbuffer.h>
26 #include <gst/gstutils.h>
27
28 #include "gst_private.h"
29 #include "gst_guids.h"
30
31 #include "vfwmsgs.h"
32 #include "amvideo.h"
33
34 #include "wine/unicode.h"
35 #include "wine/debug.h"
36
37 #include <assert.h>
38
39 #include "dvdmedia.h"
40 #include "mmreg.h"
41 #include "ks.h"
42 #include "initguid.h"
43 #include "ksmedia.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(gstreamer);
46
47 typedef struct GSTOutPin GSTOutPin;
48 typedef struct GSTInPin {
49     BasePin pin;
50     IAsyncReader *pReader;
51     IMemAllocator *pAlloc;
52 } GSTInPin;
53
54 typedef struct GSTImpl {
55     BaseFilter filter;
56
57     GSTInPin pInputPin;
58     GSTOutPin **ppPins;
59     LONG cStreams;
60
61     LONGLONG filesize;
62
63     BOOL discont, initial;
64     GstElement *gstfilter;
65     GstPad *my_src, *their_sink;
66     GstBus *bus;
67     guint64 start, nextofs, nextpullofs, stop;
68     ALLOCATOR_PROPERTIES props;
69     HANDLE event, changed_ofs;
70
71     HANDLE push_thread;
72 } GSTImpl;
73
74 struct GSTOutPin {
75     BaseOutputPin pin;
76     IQualityControl IQualityControl_iface;
77
78     GstPad *their_src;
79     GstPad *my_sink;
80     int isaud, isvid;
81     AM_MEDIA_TYPE * pmt;
82     HANDLE caps_event;
83     GstSegment *segment;
84     SourceSeeking seek;
85 };
86
87 static const WCHAR wcsInputPinName[] = {'i','n','p','u','t',' ','p','i','n',0};
88 static const IMediaSeekingVtbl GST_Seeking_Vtbl;
89 static const IPinVtbl GST_OutputPin_Vtbl;
90 static const IPinVtbl GST_InputPin_Vtbl;
91 static const IBaseFilterVtbl GST_Vtbl;
92 static const IQualityControlVtbl GSTOutPin_QualityControl_Vtbl;
93
94 static HRESULT GST_AddPin(GSTImpl *This, const PIN_INFO *piOutput, const AM_MEDIA_TYPE *amt);
95 static HRESULT GST_RemoveOutputPins(GSTImpl *This);
96 static HRESULT WINAPI GST_ChangeCurrent(IMediaSeeking *iface);
97 static HRESULT WINAPI GST_ChangeStop(IMediaSeeking *iface);
98 static HRESULT WINAPI GST_ChangeRate(IMediaSeeking *iface);
99
100 static int amt_from_gst_caps_audio(GstCaps *caps, AM_MEDIA_TYPE *amt) {
101     WAVEFORMATEXTENSIBLE *wfe;
102     WAVEFORMATEX *wfx;
103     GstStructure *arg;
104     gint32 depth = 0, bpp = 0;
105     const char *typename;
106     arg = gst_caps_get_structure(caps, 0);
107     typename = gst_structure_get_name(arg);
108     if (!typename)
109         return 0;
110
111     wfe = CoTaskMemAlloc(sizeof(*wfe));
112     wfx = (WAVEFORMATEX*)wfe;
113     amt->majortype = MEDIATYPE_Audio;
114     amt->subtype = MEDIASUBTYPE_PCM;
115     amt->formattype = FORMAT_WaveFormatEx;
116     amt->pbFormat = (BYTE*)wfe;
117     amt->cbFormat = sizeof(*wfe);
118     amt->bFixedSizeSamples = 0;
119     amt->bTemporalCompression = 1;
120     amt->lSampleSize = 0;
121     amt->pUnk = NULL;
122
123     wfx->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
124     if (!gst_structure_get_int(arg, "channels", (INT*)&wfx->nChannels))
125         return 0;
126     if (!gst_structure_get_int(arg, "rate", (INT*)&wfx->nSamplesPerSec))
127         return 0;
128     gst_structure_get_int(arg, "width", &depth);
129     gst_structure_get_int(arg, "depth", &bpp);
130     if (!depth || depth > 32 || depth % 8)
131         depth = bpp;
132     else if (!bpp)
133         bpp = depth;
134     wfe->Samples.wValidBitsPerSample = depth;
135     wfx->wBitsPerSample = bpp;
136     wfx->cbSize = sizeof(*wfe)-sizeof(*wfx);
137     switch (wfx->nChannels) {
138         case 1: wfe->dwChannelMask = KSAUDIO_SPEAKER_MONO; break;
139         case 2: wfe->dwChannelMask = KSAUDIO_SPEAKER_STEREO; break;
140         case 4: wfe->dwChannelMask = KSAUDIO_SPEAKER_SURROUND; break;
141         case 5: wfe->dwChannelMask = (KSAUDIO_SPEAKER_5POINT1 & ~SPEAKER_LOW_FREQUENCY); break;
142         case 6: wfe->dwChannelMask = KSAUDIO_SPEAKER_5POINT1; break;
143         case 8: wfe->dwChannelMask = KSAUDIO_SPEAKER_7POINT1; break;
144         default:
145         wfe->dwChannelMask = 0;
146     }
147     if (!strcmp(typename, "audio/x-raw-float")) {
148         wfe->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
149         wfx->wBitsPerSample = wfe->Samples.wValidBitsPerSample = 32;
150     } else {
151         wfe->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
152         if (wfx->nChannels <= 2 && bpp <= 16 && depth == bpp)  {
153             wfx->wFormatTag = WAVE_FORMAT_PCM;
154             wfx->cbSize = 0;
155         }
156     }
157     wfx->nBlockAlign = wfx->nChannels * wfx->wBitsPerSample/8;
158     wfx->nAvgBytesPerSec = wfx->nSamplesPerSec * wfx->nBlockAlign;
159     return 1;
160 }
161
162 static int amt_from_gst_caps_video(GstCaps *caps, AM_MEDIA_TYPE *amt) {
163     VIDEOINFOHEADER *vih = CoTaskMemAlloc(sizeof(*vih));
164     BITMAPINFOHEADER *bih = &vih->bmiHeader;
165     GstStructure *arg;
166     gint32 width = 0, height = 0, nom = 0, denom = 0;
167     const char *typename;
168     arg = gst_caps_get_structure(caps, 0);
169     typename = gst_structure_get_name(arg);
170     if (!typename)
171         return 0;
172     if (!gst_structure_get_int(arg, "width", &width) ||
173         !gst_structure_get_int(arg, "height", &height) ||
174         !gst_structure_get_fraction(arg, "framerate", &nom, &denom))
175         return 0;
176     amt->formattype = FORMAT_VideoInfo;
177     amt->pbFormat = (BYTE*)vih;
178     amt->cbFormat = sizeof(*vih);
179     amt->bFixedSizeSamples = amt->bTemporalCompression = 1;
180     amt->lSampleSize = 0;
181     amt->pUnk = NULL;
182     ZeroMemory(vih, sizeof(*vih));
183     amt->majortype = MEDIATYPE_Video;
184     if (!strcmp(typename, "video/x-raw-rgb")) {
185         if (!gst_structure_get_int(arg, "bpp", (INT*)&bih->biBitCount))
186             return 0;
187         switch (bih->biBitCount) {
188             case 16: amt->subtype = MEDIASUBTYPE_RGB555; break;
189             case 24: amt->subtype = MEDIASUBTYPE_RGB24; break;
190             case 32: amt->subtype = MEDIASUBTYPE_RGB32; break;
191             default:
192                 FIXME("Unknown bpp %u\n", bih->biBitCount);
193                 return 0;
194         }
195         bih->biCompression = BI_RGB;
196     } else {
197         amt->subtype = MEDIATYPE_Video;
198         if (!gst_structure_get_fourcc(arg, "format", &amt->subtype.Data1))
199             return 0;
200         switch (amt->subtype.Data1) {
201             case mmioFOURCC('I','4','2','0'):
202             case mmioFOURCC('Y','V','1','2'):
203             case mmioFOURCC('N','V','1','2'):
204             case mmioFOURCC('N','V','2','1'):
205                 bih->biBitCount = 12; break;
206             case mmioFOURCC('Y','U','Y','2'):
207             case mmioFOURCC('Y','V','Y','U'):
208                 bih->biBitCount = 16; break;
209         }
210         bih->biCompression = amt->subtype.Data1;
211     }
212     bih->biSizeImage = width * height * bih->biBitCount / 8;
213     vih->AvgTimePerFrame = 10000000;
214     vih->AvgTimePerFrame *= denom;
215     vih->AvgTimePerFrame /= nom;
216     vih->rcSource.left = 0;
217     vih->rcSource.right = width;
218     vih->rcSource.top = height;
219     vih->rcSource.bottom = 0;
220     vih->rcTarget = vih->rcSource;
221     bih->biSize = sizeof(*bih);
222     bih->biWidth = width;
223     bih->biHeight = height;
224     bih->biPlanes = 1;
225     return 1;
226 }
227
228 static gboolean accept_caps_sink(GstPad *pad, GstCaps *caps) {
229     GSTOutPin *pin = gst_pad_get_element_private(pad);
230     AM_MEDIA_TYPE amt;
231     GstStructure *arg;
232     const char *typename;
233     int ret;
234     arg = gst_caps_get_structure(caps, 0);
235     typename = gst_structure_get_name(arg);
236     if (!strcmp(typename, "audio/x-raw-int") ||
237         !strcmp(typename, "audio/x-raw-float")) {
238         if (!pin->isaud) {
239             ERR("Setting audio caps on non-audio pad?\n");
240             return 0;
241         }
242         ret = amt_from_gst_caps_audio(caps, &amt);
243         FreeMediaType(&amt);
244         TRACE("+%i\n", ret);
245         return ret;
246     } else if (!strcmp(typename, "video/x-raw-rgb")
247                || !strcmp(typename, "video/x-raw-yuv")) {
248         if (!pin->isvid) {
249             ERR("Setting video caps on non-video pad?\n");
250             return 0;
251         }
252         ret = amt_from_gst_caps_video(caps, &amt);
253         FreeMediaType(&amt);
254         TRACE("-%i\n", ret);
255         return ret;
256     } else {
257         FIXME("Unhandled type \"%s\"\n", typename);
258         return 0;
259     }
260 }
261
262 static gboolean setcaps_sink(GstPad *pad, GstCaps *caps) {
263     GSTOutPin *pin = gst_pad_get_element_private(pad);
264     GSTImpl *This = (GSTImpl *)pin->pin.pin.pinInfo.pFilter;
265     AM_MEDIA_TYPE amt;
266     GstStructure *arg;
267     const char *typename;
268     int ret;
269     arg = gst_caps_get_structure(caps, 0);
270     typename = gst_structure_get_name(arg);
271     if (!strcmp(typename, "audio/x-raw-int") ||
272         !strcmp(typename, "audio/x-raw-float")) {
273         if (!pin->isaud) {
274             ERR("Setting audio caps on non-audio pad?\n");
275             return 0;
276         }
277         ret = amt_from_gst_caps_audio(caps, &amt);
278     } else if (!strcmp(typename, "video/x-raw-rgb")
279                || !strcmp(typename, "video/x-raw-yuv")) {
280         if (!pin->isvid) {
281             ERR("Setting video caps on non-video pad?\n");
282             return 0;
283         }
284         ret = amt_from_gst_caps_video(caps, &amt);
285         if (ret)
286             This->props.cbBuffer = max(This->props.cbBuffer, ((VIDEOINFOHEADER*)amt.pbFormat)->bmiHeader.biSizeImage);
287     } else {
288         FIXME("Unhandled type \"%s\"\n", typename);
289         return 0;
290     }
291     TRACE("Linking returned %i for %s\n", ret, typename);
292     if (!ret)
293         return 0;
294     FreeMediaType(pin->pmt);
295     *pin->pmt = amt;
296     return 1;
297 }
298
299 static gboolean gst_base_src_perform_seek(GSTImpl *This, GstEvent *event)
300 {
301     gboolean res = TRUE;
302     gdouble rate;
303     GstFormat seek_format;
304     GstSeekFlags flags;
305     GstSeekType cur_type, stop_type;
306     gint64 cur, stop;
307     gboolean flush;
308     guint32 seqnum;
309     GstEvent *tevent;
310     BOOL thread = !!This->push_thread;
311
312     gst_event_parse_seek(event, &rate, &seek_format, &flags,
313                          &cur_type, &cur, &stop_type, &stop);
314
315     if (seek_format != GST_FORMAT_BYTES) {
316         FIXME("Not handling other format %i\n", seek_format);
317         return 0;
318     }
319
320     flush = flags & GST_SEEK_FLAG_FLUSH;
321     seqnum = gst_event_get_seqnum(event);
322
323     /* send flush start */
324     if (flush) {
325         tevent = gst_event_new_flush_start();
326         gst_event_set_seqnum(tevent, seqnum);
327         gst_pad_push_event(This->my_src, tevent);
328         if (This->pInputPin.pReader)
329             IAsyncReader_BeginFlush(This->pInputPin.pReader);
330         if (thread)
331             gst_pad_activate_push(This->my_src, 0);
332     }
333
334     This->nextofs = This->start = cur;
335
336     /* and prepare to continue streaming */
337     if (flush) {
338         tevent = gst_event_new_flush_stop();
339         gst_event_set_seqnum(tevent, seqnum);
340         gst_pad_push_event(This->my_src, tevent);
341         if (This->pInputPin.pReader)
342             IAsyncReader_EndFlush(This->pInputPin.pReader);
343         if (thread)
344             gst_pad_activate_push(This->my_src, 1);
345     }
346
347     return res;
348 }
349
350 static gboolean event_src(GstPad *pad, GstEvent *event) {
351     GSTImpl *This = gst_pad_get_element_private(pad);
352     switch (event->type) {
353         case GST_EVENT_SEEK:
354             return gst_base_src_perform_seek(This, event);
355         case GST_EVENT_FLUSH_START:
356             EnterCriticalSection(&This->filter.csFilter);
357             if (This->pInputPin.pReader)
358                 IAsyncReader_BeginFlush(This->pInputPin.pReader);
359             LeaveCriticalSection(&This->filter.csFilter);
360             break;
361         case GST_EVENT_FLUSH_STOP:
362             EnterCriticalSection(&This->filter.csFilter);
363             if (This->pInputPin.pReader)
364                 IAsyncReader_EndFlush(This->pInputPin.pReader);
365             LeaveCriticalSection(&This->filter.csFilter);
366             break;
367         default:
368             FIXME("%p (%u) stub\n", event, event->type);
369         case GST_EVENT_TAG:
370         case GST_EVENT_QOS:
371             return gst_pad_event_default(pad, event);
372     }
373     return 1;
374 }
375
376 static gboolean event_sink(GstPad *pad, GstEvent *event) {
377     GSTOutPin *pin = gst_pad_get_element_private(pad);
378     switch (event->type) {
379         case GST_EVENT_NEWSEGMENT: {
380             gboolean update;
381             gdouble rate, applied_rate;
382             GstFormat format;
383             gint64 start, stop, pos;
384             gst_event_parse_new_segment_full(event, &update, &rate, &applied_rate, &format, &start, &stop, &pos);
385             if (format != GST_FORMAT_TIME) {
386                 FIXME("Ignoring new segment because of format %i\n", format);
387                 return 1;
388             }
389             gst_segment_set_newsegment_full(pin->segment, update, rate, applied_rate, format, start, stop, pos);
390             pos /= 100;
391             if (stop > 0)
392                 stop /= 100;
393             if (pin->pin.pin.pConnectedTo)
394                 IPin_NewSegment(pin->pin.pin.pConnectedTo, pos, stop, rate*applied_rate);
395             return 1;
396         }
397         case GST_EVENT_EOS:
398             if (pin->pin.pin.pConnectedTo)
399                 IPin_EndOfStream(pin->pin.pin.pConnectedTo);
400             return 1;
401         case GST_EVENT_FLUSH_START:
402             if (pin->pin.pin.pConnectedTo)
403                 IPin_BeginFlush(pin->pin.pin.pConnectedTo);
404             return 1;
405         case GST_EVENT_FLUSH_STOP:
406             gst_segment_init(pin->segment, GST_FORMAT_TIME);
407             if (pin->pin.pin.pConnectedTo)
408                 IPin_EndFlush(pin->pin.pin.pConnectedTo);
409             return 1;
410         default:
411             FIXME("%p stub %s\n", event, gst_event_type_get_name(event->type));
412             return gst_pad_event_default(pad, event);
413     }
414 }
415
416 static void release_sample(void *data) {
417     ULONG ret;
418     ret = IMediaSample_Release((IMediaSample *)data);
419     TRACE("Releasing %p returns %u\n", data, ret);
420 }
421
422 static DWORD CALLBACK push_data(LPVOID iface) {
423     LONGLONG maxlen, curlen;
424     GSTImpl *This = iface;
425     IMediaSample *buf;
426     DWORD_PTR user;
427     HRESULT hr;
428
429     if (!This->stop)
430         IAsyncReader_Length(This->pInputPin.pReader, &maxlen, &curlen);
431     else
432         maxlen = This->stop;
433     TRACE("Starting..\n");
434     for (;;) {
435         REFERENCE_TIME tStart, tStop;
436         ULONG len;
437         GstBuffer *gstbuf;
438         BYTE *data;
439         int ret;
440
441         hr = IMemAllocator_GetBuffer(This->pInputPin.pAlloc, &buf, NULL, NULL, 0);
442         if (FAILED(hr))
443             break;
444
445         if (This->nextofs >= maxlen)
446             break;
447         len = IMediaSample_GetSize(buf);
448         if (This->nextofs + len > maxlen)
449             len = maxlen - This->nextofs;
450
451         tStart = MEDIATIME_FROM_BYTES(This->nextofs);
452         tStop = tStart + MEDIATIME_FROM_BYTES(len);
453         IMediaSample_SetTime(buf, &tStart, &tStop);
454
455         hr = IAsyncReader_Request(This->pInputPin.pReader, buf, 0);
456         if (FAILED(hr)) {
457             IMediaSample_Release(buf);
458             break;
459         }
460         This->nextofs += len;
461         hr = IAsyncReader_WaitForNext(This->pInputPin.pReader, -1, &buf, &user);
462         if (FAILED(hr) || !buf) {
463             if (buf)
464                 IMediaSample_Release(buf);
465             break;
466         }
467
468         IMediaSample_GetPointer(buf, &data);
469         gstbuf = gst_app_buffer_new(data, IMediaSample_GetActualDataLength(buf), release_sample, buf);
470         if (!gstbuf) {
471             IMediaSample_Release(buf);
472             break;
473         }
474         gstbuf->duration = gstbuf->timestamp = -1;
475         ret = gst_pad_push(This->my_src, gstbuf);
476         if (ret >= 0)
477             hr = S_OK;
478         else
479             ERR("Sending returned: %i\n", ret);
480         if (ret == GST_FLOW_ERROR)
481             hr = E_FAIL;
482         else if (ret == GST_FLOW_WRONG_STATE)
483             hr = VFW_E_WRONG_STATE;
484         else if (ret == GST_FLOW_RESEND)
485             hr = S_FALSE;
486         if (hr != S_OK)
487             break;
488     }
489
490     gst_pad_push_event(This->my_src, gst_event_new_eos());
491
492     TRACE("Almost stopping.. %08x\n", hr);
493     do {
494         IAsyncReader_WaitForNext(This->pInputPin.pReader, 0, &buf, &user);
495         if (buf)
496             IMediaSample_Release(buf);
497     } while (buf);
498
499     TRACE("Stopping.. %08x\n", hr);
500     return 0;
501 }
502
503 static HRESULT WINAPI GST_OutPin_QueryAccept(IPin *iface, const AM_MEDIA_TYPE *pmt) {
504     GSTOutPin *pin = (GSTOutPin*)iface;
505     FIXME("stub %p\n", pin);
506     return S_OK;
507 }
508
509 static GstFlowReturn got_data_sink(GstPad *pad, GstBuffer *buf) {
510     GSTOutPin *pin = gst_pad_get_element_private(pad);
511     GSTImpl *This = (GSTImpl *)pin->pin.pin.pinInfo.pFilter;
512     IMediaSample *sample;
513     HRESULT hr;
514     BOOL freeSamp = FALSE;
515
516     if (This->initial) {
517         gst_buffer_unref(buf);
518         TRACE("Triggering %p %p\n", pad, pin->caps_event);
519         SetEvent(pin->caps_event);
520         return GST_FLOW_NOT_LINKED;
521     }
522
523     if (GST_IS_APP_BUFFER(buf)) {
524         sample = GST_APP_BUFFER(buf)->priv;
525         TRACE("Pushing buffer\n");
526     } else if (buf->parent && GST_IS_APP_BUFFER(buf->parent)) {
527         sample = GST_APP_BUFFER(buf->parent)->priv;
528         TRACE("Pushing sub-buffer\n");
529     } else {
530         BYTE *ptr = NULL;
531         hr = BaseOutputPinImpl_GetDeliveryBuffer(&pin->pin, &sample, NULL, NULL, 0);
532         freeSamp = TRUE;
533         if (hr == VFW_E_NOT_CONNECTED) {
534             gst_buffer_unref(buf);
535             return GST_FLOW_NOT_LINKED;
536         }
537         if (FAILED(hr)) {
538             gst_buffer_unref(buf);
539             ERR("Didn't get a GST_APP_BUFFER, and could not get a delivery buffer (%x), returning GST_FLOW_WRONG_STATE\n", hr);
540             return GST_FLOW_WRONG_STATE;
541         }
542         TRACE("Did not get a GST_APP_BUFFER, creating a sample\n");
543         IMediaSample_GetPointer(sample, &ptr);
544         memcpy(ptr, GST_BUFFER_DATA(buf), GST_BUFFER_SIZE(buf));
545     }
546     IMediaSample_SetActualDataLength(sample, GST_BUFFER_SIZE(buf));
547
548     if (GST_BUFFER_TIMESTAMP_IS_VALID(buf)) {
549         REFERENCE_TIME rtStart = gst_segment_to_running_time(pin->segment, GST_FORMAT_TIME, buf->timestamp);
550         if (rtStart >= 0)
551             rtStart /= 100;
552
553         if (GST_BUFFER_DURATION_IS_VALID(buf)) {
554             REFERENCE_TIME tStart = buf->timestamp / 100;
555             REFERENCE_TIME tStop = (buf->timestamp + buf->duration) / 100;
556             REFERENCE_TIME rtStop;
557             rtStop = gst_segment_to_running_time(pin->segment, GST_FORMAT_TIME, buf->timestamp + buf->duration);
558             if (rtStop >= 0)
559                 rtStop /= 100;
560             TRACE("Current time on %p: %i to %i ms\n", pin, (int)(rtStart / 10000), (int)(rtStop / 10000));
561             IMediaSample_SetTime(sample, &rtStart, rtStop >= 0 ? &rtStop : NULL);
562             IMediaSample_SetMediaTime(sample, &tStart, &tStop);
563         } else {
564             IMediaSample_SetTime(sample, rtStart >= 0 ? &rtStart : NULL, NULL);
565             IMediaSample_SetMediaTime(sample, NULL, NULL);
566         }
567     } else {
568         IMediaSample_SetTime(sample, NULL, NULL);
569         IMediaSample_SetMediaTime(sample, NULL, NULL);
570     }
571
572     IMediaSample_SetDiscontinuity(sample, GST_BUFFER_FLAG_IS_SET(buf, GST_BUFFER_FLAG_DISCONT));
573     IMediaSample_SetPreroll(sample, GST_BUFFER_FLAG_IS_SET(buf, GST_BUFFER_FLAG_PREROLL));
574     IMediaSample_SetSyncPoint(sample, !GST_BUFFER_FLAG_IS_SET(buf, GST_BUFFER_FLAG_DELTA_UNIT));
575
576     if (!pin->pin.pin.pConnectedTo)
577         hr = VFW_E_NOT_CONNECTED;
578     else
579         hr = IMemInputPin_Receive(pin->pin.pMemInputPin, sample);
580     TRACE("sending sample: %08x\n", hr);
581     gst_buffer_unref(buf);
582     if (freeSamp)
583         IMediaSample_Release(sample);
584     if (hr == VFW_E_NOT_CONNECTED)
585         return GST_FLOW_NOT_LINKED;
586     else if (FAILED(hr))
587         return GST_FLOW_WRONG_STATE;
588     if (hr != S_OK)
589         return GST_FLOW_RESEND;
590     return GST_FLOW_OK;
591 }
592
593 static GstFlowReturn request_buffer_sink(GstPad *pad, guint64 ofs, guint size, GstCaps *caps, GstBuffer **buf) {
594     GSTOutPin *pin = gst_pad_get_element_private(pad);
595     GSTImpl *This = (GSTImpl *)pin->pin.pin.pinInfo.pFilter;
596     IMediaSample *sample;
597     BYTE *ptr;
598     HRESULT hr;
599
600     TRACE("Requesting buffer\n");
601     if (This->initial) {
602         int ret;
603         ret = setcaps_sink(pad, caps);
604         if (!ret)
605             return GST_FLOW_NOT_NEGOTIATED;
606         *buf = gst_buffer_new_and_alloc(size);
607         return GST_FLOW_OK;
608     }
609
610     if (caps && caps != GST_PAD_CAPS(pad))
611         if (!setcaps_sink(pad, caps))
612             return GST_FLOW_NOT_NEGOTIATED;
613
614     hr = BaseOutputPinImpl_GetDeliveryBuffer(&pin->pin, &sample, NULL, NULL, 0);
615     if (hr == VFW_E_NOT_CONNECTED)
616         return GST_FLOW_NOT_LINKED;
617     if (FAILED(hr)) {
618         ERR("Could not get output buffer: %08x\n", hr);
619         *buf = NULL;
620         return GST_FLOW_WRONG_STATE;
621     }
622     IMediaSample_SetActualDataLength(sample, size);
623     IMediaSample_GetPointer(sample, &ptr);
624     *buf = gst_app_buffer_new(ptr, size, release_sample, sample);
625     if (!*buf) {
626         IMediaSample_Release(sample);
627         ERR("Out of memory\n");
628         return GST_FLOW_ERROR;
629     }
630     gst_buffer_set_caps(*buf, caps);
631     return GST_FLOW_OK;
632 }
633
634 static GstFlowReturn request_buffer_src(GstPad *pad, guint64 ofs, guint len, GstBuffer **buf) {
635     GSTImpl *This = gst_pad_get_element_private(pad);
636     int ret;
637
638     *buf = NULL;
639     TRACE("Requesting %s %u\n", wine_dbgstr_longlong(ofs), len);
640     if (ofs == (guint64)-1)
641         ofs = This->nextpullofs;
642     if (ofs >= This->filesize) {
643         WARN("Reading past eof: %s, %u\n", wine_dbgstr_longlong(ofs), len);
644         return GST_FLOW_UNEXPECTED;
645     }
646     if (len + ofs > This->filesize)
647         len = This->filesize - ofs;
648     This->nextpullofs = ofs + len;
649
650     ret = gst_pad_alloc_buffer(This->my_src, ofs, len, NULL, buf);
651     if (ret >= 0) {
652         HRESULT hr;
653         hr = IAsyncReader_SyncRead(This->pInputPin.pReader, ofs, len, GST_BUFFER_DATA(*buf));
654         if (FAILED(hr)) {
655             ERR("Returned %08x\n", hr);
656             return GST_FLOW_ERROR;
657         }
658     }
659     return ret;
660 }
661
662 static DWORD CALLBACK push_data_init(LPVOID iface) {
663     GSTImpl *This = iface;
664     DWORD64 ofs = 0;
665
666     TRACE("Starting..\n");
667     for (;;) {
668         GstBuffer *buf;
669         GstFlowReturn ret = request_buffer_src(This->my_src, ofs, 4096, &buf);
670         if (ret < 0) {
671             ERR("Obtaining buffer returned: %i\n", ret);
672             break;
673         }
674         ret = gst_pad_push(This->my_src, buf);
675         ofs += 4096;
676         if (ret)
677             TRACE("Sending returned: %i\n", ret);
678         if (ret < 0)
679             break;
680     }
681     TRACE("Stopping..\n");
682     return 0;
683 }
684
685 static void removed_decoded_pad(GstElement *bin, GstPad *pad, GSTImpl *This) {
686     int x;
687     GSTOutPin *pin;
688
689     EnterCriticalSection(&This->filter.csFilter);
690     for (x = 0; x < This->cStreams; ++x) {
691         if (This->ppPins[x]->their_src == pad)
692             break;
693     }
694     if (x == This->cStreams)
695         goto out;
696     pin = This->ppPins[x];
697     gst_pad_unlink(pin->their_src, pin->my_sink);
698     gst_object_unref(pin->their_src);
699     pin->their_src = NULL;
700 out:
701     TRACE("Removed %i/%i\n", x, This->cStreams);
702     LeaveCriticalSection(&This->filter.csFilter);
703 }
704
705 static void init_new_decoded_pad(GstElement *bin, GstPad *pad, gboolean last, GSTImpl *This) {
706     HRESULT hr;
707     PIN_INFO piOutput;
708     const char *typename;
709     char *name;
710     AM_MEDIA_TYPE amt = { };
711     GstCaps *caps;
712     GstStructure *arg;
713     GstPad *mypad;
714     GSTOutPin *pin;
715     int ret;
716     int isvid = 0, isaud = 0;
717
718     piOutput.dir = PINDIR_OUTPUT;
719     piOutput.pFilter = (IBaseFilter *)This;
720     name = gst_pad_get_name(pad);
721     MultiByteToWideChar(CP_UNIXCP, 0, name, -1, piOutput.achName, sizeof(piOutput.achName) / sizeof(piOutput.achName[0]) - 1);
722     TRACE("Name: %s\n", name);
723     g_free(name);
724     piOutput.achName[sizeof(piOutput.achName) / sizeof(piOutput.achName[0]) - 1] = 0;
725
726     caps = gst_pad_get_caps_reffed(pad);
727     arg = gst_caps_get_structure(caps, 0);
728     typename = gst_structure_get_name(arg);
729
730     mypad = gst_pad_new(NULL, GST_PAD_SINK);
731     gst_pad_set_chain_function(mypad, got_data_sink);
732     gst_pad_set_event_function(mypad, event_sink);
733     gst_pad_set_bufferalloc_function(mypad, request_buffer_sink);
734     gst_pad_set_acceptcaps_function(mypad, accept_caps_sink);
735     gst_pad_set_setcaps_function(mypad, setcaps_sink);
736
737     if (!strcmp(typename, "audio/x-raw-int") ||
738         !strcmp(typename, "audio/x-raw-float")) {
739         isaud = 1;
740     } else if (!strcmp(typename, "video/x-raw-rgb")
741                || !strcmp(typename, "video/x-raw-yuv")) {
742         isvid = 1;
743     } else {
744         FIXME("Unknown type \'%s\'\n", typename);
745         return;
746     }
747     GST_PAD_CAPS(mypad) = GST_CAPS_ANY;
748     hr = GST_AddPin(This, &piOutput, &amt);
749     if (FAILED(hr)) {
750         ERR("%08x\n", hr);
751         return;
752     }
753     pin = This->ppPins[This->cStreams - 1];
754     gst_pad_set_element_private(mypad, pin);
755     pin->my_sink = mypad;
756     pin->isaud = isaud;
757     pin->isvid = isvid;
758
759     gst_segment_init(pin->segment, GST_FORMAT_TIME);
760     ret = gst_pad_link(pad, mypad);
761     gst_pad_activate_push(mypad, 1);
762     TRACE("Linking: %i\n", ret);
763     if (ret >= 0) {
764         pin->their_src = pad;
765         gst_object_ref(pin->their_src);
766     }
767 }
768
769 static void existing_new_pad(GstElement *bin, GstPad *pad, gboolean last, GSTImpl *This) {
770     int x;
771
772     if (gst_pad_is_linked(pad))
773         return;
774
775     /* Still holding our own lock */
776     if (This->initial) {
777         init_new_decoded_pad(bin, pad, last, This);
778         return;
779     }
780
781     EnterCriticalSection(&This->filter.csFilter);
782     for (x = 0; x < This->cStreams; ++x) {
783         GSTOutPin *pin = This->ppPins[x];
784         if (!pin->their_src) {
785             gst_segment_init(pin->segment, GST_FORMAT_TIME);
786             if (gst_pad_link(pad, pin->my_sink) >= 0) {
787                 pin->their_src = pad;
788                 gst_object_ref(pin->their_src);
789                 TRACE("Relinked\n");
790                 LeaveCriticalSection(&This->filter.csFilter);
791                 return;
792             }
793         }
794     }
795     init_new_decoded_pad(bin, pad, last, This);
796     LeaveCriticalSection(&This->filter.csFilter);
797 }
798
799 static gboolean check_get_range(GstPad *pad) {
800     return 1;
801 }
802
803 static gboolean query_function(GstPad *pad, GstQuery *query) {
804     GSTImpl *This = gst_pad_get_element_private(pad);
805     GstFormat format;
806     int ret;
807     LONGLONG duration;
808
809     switch (GST_QUERY_TYPE(query)) {
810         case GST_QUERY_DURATION:
811             gst_query_parse_duration (query, &format, NULL);
812             if (format == GST_FORMAT_PERCENT) {
813                 gst_query_set_duration (query, GST_FORMAT_PERCENT, GST_FORMAT_PERCENT_MAX);
814                 return 1;
815             }
816             ret = gst_pad_query_convert (pad, GST_FORMAT_BYTES, This->filesize, &format, &duration);
817             gst_query_set_duration(query, format, duration);
818             return ret;
819         case GST_QUERY_SEEKING:
820             gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
821             TRACE("Seeking %i %i\n", format, GST_FORMAT_BYTES);
822             if (format != GST_FORMAT_BYTES)
823                 return 0;
824             gst_query_set_seeking(query, GST_FORMAT_BYTES, 1, 0, This->filesize);
825             return 1;
826         default:
827             FIXME("Unhandled query type %i\n", GST_QUERY_TYPE(query));
828         case GST_QUERY_URI:
829         case GST_QUERY_CONVERT:
830             return 0;
831     }
832 }
833
834 static gboolean activate_push(GstPad *pad, gboolean activate) {
835     GSTImpl *This = gst_pad_get_element_private(pad);
836     EnterCriticalSection(&This->filter.csFilter);
837     if (!activate) {
838         TRACE("Deactivating\n");
839         if (!This->initial)
840             IAsyncReader_BeginFlush(This->pInputPin.pReader);
841         if (This->push_thread) {
842             WaitForSingleObject(This->push_thread, -1);
843             CloseHandle(This->push_thread);
844             This->push_thread = NULL;
845         }
846         if (!This->initial)
847             IAsyncReader_EndFlush(This->pInputPin.pReader);
848         if (This->filter.state == State_Stopped)
849             This->nextofs = This->start;
850     } else if (!This->push_thread) {
851         TRACE("Activating\n");
852         if (This->initial)
853             This->push_thread = CreateThread(NULL, 0, push_data_init, This, 0, NULL);
854         else
855             This->push_thread = CreateThread(NULL, 0, push_data, This, 0, NULL);
856     }
857     LeaveCriticalSection(&This->filter.csFilter);
858     return 1;
859 }
860
861 static void no_more_pads(GstElement *decodebin, GSTImpl *This) {
862     TRACE("Done\n");
863     SetEvent(This->event);
864 }
865
866 typedef enum {
867   GST_AUTOPLUG_SELECT_TRY,
868   GST_AUTOPLUG_SELECT_EXPOSE,
869   GST_AUTOPLUG_SELECT_SKIP
870 } GstAutoplugSelectResult;
871
872 static GstAutoplugSelectResult autoplug_blacklist(GstElement *bin, GstPad *pad, GstCaps *caps, GstElementFactory *fact, GSTImpl *This) {
873     const char *name = gst_element_factory_get_longname(fact);
874
875     if (strstr(name, "Player protection")) {
876         WARN("Blacklisted a/52 decoder because it only works in Totem\n");
877         return GST_AUTOPLUG_SELECT_SKIP;
878     }
879     if (!strcmp(name, "Fluendo Hardware Accelerated Video Decoder")) {
880         WARN("Disabled video acceleration since it breaks in wine\n");
881         return GST_AUTOPLUG_SELECT_SKIP;
882     }
883     TRACE("using \"%s\"\n", name);
884     return GST_AUTOPLUG_SELECT_TRY;
885 }
886
887 static GstBusSyncReply watch_bus(GstBus *bus, GstMessage *msg, gpointer data) {
888     GSTImpl *This = data;
889     GError *err = NULL;
890     gchar *dbg_info = NULL;
891     if (GST_MESSAGE_TYPE(msg) & GST_MESSAGE_ERROR) {
892         gst_message_parse_error(msg, &err, &dbg_info);
893         FIXME("%s: %s\n", GST_OBJECT_NAME(msg->src), err->message);
894         WARN("%s\n", dbg_info);
895         SetEvent(This->event);
896     } else if (GST_MESSAGE_TYPE(msg) & GST_MESSAGE_WARNING) {
897         gst_message_parse_warning(msg, &err, &dbg_info);
898         WARN("%s: %s\n", GST_OBJECT_NAME(msg->src), err->message);
899         WARN("%s\n", dbg_info);
900     }
901     if (err)
902         g_error_free(err);
903     g_free(dbg_info);
904     return GST_BUS_DROP;
905 }
906
907 static void unknown_type(GstElement *bin, GstPad *pad, GstCaps *caps, GSTImpl *This) {
908     gchar *strcaps = gst_caps_to_string(caps);
909     FIXME("Could not find a filter for caps: %s\n", strcaps);
910     g_free(strcaps);
911 }
912
913 static HRESULT GST_Connect(GSTInPin *pPin, IPin *pConnectPin, ALLOCATOR_PROPERTIES *props) {
914     GSTImpl *This = (GSTImpl*)pPin->pin.pinInfo.pFilter;
915     HRESULT hr;
916     int ret, i;
917     LONGLONG avail, duration;
918     GstFormat format = GST_FORMAT_TIME;
919     GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE(
920         "quartz_src",
921         GST_PAD_SRC,
922         GST_PAD_ALWAYS,
923         GST_STATIC_CAPS_ANY);
924
925     TRACE("%p %p %p\n", pPin, pConnectPin, props);
926     This->props = *props;
927     IAsyncReader_Length(pPin->pReader, &This->filesize, &avail);
928
929     if (!This->bus) {
930         This->bus = gst_bus_new();
931         gst_bus_set_sync_handler(This->bus, watch_bus, This);
932     }
933
934     This->gstfilter = gst_element_factory_make("decodebin2", NULL);
935     if (!This->gstfilter) {
936         FIXME("Could not make source filter, are gstreamer-plugins-* installed for %u bits?\n",
937               8 * (int)sizeof(void*));
938         return E_FAIL;
939     }
940     gst_element_set_bus(This->gstfilter, This->bus);
941     g_signal_connect(This->gstfilter, "new-decoded-pad", G_CALLBACK(existing_new_pad), This);
942     g_signal_connect(This->gstfilter, "pad-removed", G_CALLBACK(removed_decoded_pad), This);
943     g_signal_connect(This->gstfilter, "autoplug-select", G_CALLBACK(autoplug_blacklist), This);
944     g_signal_connect(This->gstfilter, "unknown-type", G_CALLBACK(unknown_type), This);
945
946     This->my_src = gst_pad_new_from_static_template(&src_template, "quartz-src");
947     gst_pad_set_getrange_function(This->my_src, request_buffer_src);
948     gst_pad_set_checkgetrange_function(This->my_src, check_get_range);
949     gst_pad_set_query_function(This->my_src, query_function);
950     gst_pad_set_activatepush_function(This->my_src, activate_push);
951     gst_pad_set_event_function(This->my_src, event_src);
952     gst_pad_set_element_private (This->my_src, This);
953     This->their_sink = gst_element_get_static_pad(This->gstfilter, "sink");
954
955     g_signal_connect(This->gstfilter, "no-more-pads", G_CALLBACK(no_more_pads), This);
956     ret = gst_pad_link(This->my_src, This->their_sink);
957     gst_object_unref(This->their_sink);
958     if (ret < 0) {
959         ERR("Returns: %i\n", ret);
960         return E_FAIL;
961     }
962     This->start = This->nextofs = This->nextpullofs = This->stop = 0;
963
964     /* Add initial pins */
965     This->initial = This->discont = 1;
966     ResetEvent(This->event);
967     gst_element_set_state(This->gstfilter, GST_STATE_PLAYING);
968     gst_pad_set_active(This->my_src, 1);
969     WaitForSingleObject(This->event, -1);
970     gst_element_get_state(This->gstfilter, NULL, NULL, -1);
971
972     if (ret < 0) {
973         WARN("Ret: %i\n", ret);
974         hr = E_FAIL;
975     } else if (!This->cStreams) {
976         FIXME("GStreamer could not find any streams\n");
977         hr = E_FAIL;
978     } else {
979         gst_pad_query_duration(This->ppPins[0]->their_src, &format, &duration);
980         for (i = 0; i < This->cStreams; ++i) {
981             This->ppPins[i]->seek.llDuration = This->ppPins[i]->seek.llStop = duration / 100;
982             This->ppPins[i]->seek.llCurrent = 0;
983             if (!This->ppPins[i]->seek.llDuration)
984                 This->ppPins[i]->seek.dwCapabilities = 0;
985             WaitForSingleObject(This->ppPins[i]->caps_event, -1);
986         }
987         hr = S_OK;
988     }
989     *props = This->props;
990     gst_element_set_state(This->gstfilter, GST_STATE_READY);
991     gst_element_get_state(This->gstfilter, NULL, NULL, -1);
992     if (This->push_thread)
993         gst_pad_activate_push(This->my_src, 0);
994
995     This->initial = 0;
996     This->nextofs = This->nextpullofs = 0;
997     return hr;
998 }
999
1000 static inline GSTOutPin *impl_from_IMediaSeeking( IMediaSeeking *iface ) {
1001     return CONTAINING_RECORD(iface, GSTOutPin, seek.IMediaSeeking_iface);
1002 }
1003
1004 static IPin* WINAPI GST_GetPin(BaseFilter *iface, int pos)
1005 {
1006     GSTImpl *This = (GSTImpl *)iface;
1007     TRACE("Asking for pos %x\n", pos);
1008
1009     if (pos > This->cStreams || pos < 0)
1010         return NULL;
1011     if (!pos)
1012     {
1013         IPin_AddRef((IPin*)&This->pInputPin);
1014         return (IPin*)&This->pInputPin;
1015     }
1016     else
1017     {
1018         IPin_AddRef((IPin*)This->ppPins[pos - 1]);
1019         return (IPin*)This->ppPins[pos - 1];
1020     }
1021 }
1022
1023 static LONG WINAPI GST_GetPinCount(BaseFilter *iface)
1024 {
1025     GSTImpl *This = (GSTImpl *)iface;
1026     return (This->cStreams + 1);
1027 }
1028
1029 static const BaseFilterFuncTable BaseFuncTable = {
1030     GST_GetPin,
1031     GST_GetPinCount
1032 };
1033
1034 IUnknown * CALLBACK Gstreamer_Splitter_create(IUnknown *punkout, HRESULT *phr) {
1035     IUnknown *obj = NULL;
1036     PIN_INFO *piInput;
1037     GSTImpl *This;
1038
1039     if (!Gstreamer_init())
1040     {
1041         *phr = E_FAIL;
1042         return NULL;
1043     }
1044
1045     This = CoTaskMemAlloc(sizeof(*This));
1046     obj = (IUnknown*)This;
1047     if (!This)
1048     {
1049         *phr = E_OUTOFMEMORY;
1050         return NULL;
1051     }
1052
1053     BaseFilter_Init(&This->filter, &GST_Vtbl, &CLSID_Gstreamer_Splitter, (DWORD_PTR)(__FILE__ ": GSTImpl.csFilter"), &BaseFuncTable);
1054
1055     This->cStreams = 0;
1056     This->ppPins = NULL;
1057     This->push_thread = NULL;
1058     This->event = CreateEventW(NULL, 0, 0, NULL);
1059     This->bus = NULL;
1060
1061     piInput = &This->pInputPin.pin.pinInfo;
1062     piInput->dir = PINDIR_INPUT;
1063     piInput->pFilter = (IBaseFilter *)This;
1064     lstrcpynW(piInput->achName, wcsInputPinName, sizeof(piInput->achName) / sizeof(piInput->achName[0]));
1065     This->pInputPin.pin.IPin_iface.lpVtbl = &GST_InputPin_Vtbl;
1066     This->pInputPin.pin.refCount = 1;
1067     This->pInputPin.pin.pConnectedTo = NULL;
1068     This->pInputPin.pin.pCritSec = &This->filter.csFilter;
1069     ZeroMemory(&This->pInputPin.pin.mtCurrent, sizeof(AM_MEDIA_TYPE));
1070     *phr = S_OK;
1071     return obj;
1072 }
1073
1074 static void GST_Destroy(GSTImpl *This) {
1075     IPin *connected = NULL;
1076     ULONG pinref;
1077
1078     TRACE("Destroying\n");
1079
1080     CloseHandle(This->event);
1081
1082     /* Don't need to clean up output pins, disconnecting input pin will do that */
1083     IPin_ConnectedTo((IPin *)&This->pInputPin, &connected);
1084     if (connected) {
1085         assert(IPin_Disconnect(connected) == S_OK);
1086         IPin_Release(connected);
1087         assert(IPin_Disconnect((IPin *)&This->pInputPin) == S_OK);
1088     }
1089     pinref = IPin_Release((IPin *)&This->pInputPin);
1090     if (pinref) {
1091         /* Valgrind could find this, if I kill it here */
1092         ERR("pinref should be null, is %u, destroying anyway\n", pinref);
1093         assert((LONG)pinref > 0);
1094
1095         while (pinref)
1096             pinref = IPin_Release((IPin *)&This->pInputPin);
1097     }
1098     if (This->bus) {
1099         gst_bus_set_sync_handler(This->bus, NULL, NULL);
1100         gst_object_unref(This->bus);
1101     }
1102     CoTaskMemFree(This);
1103 }
1104
1105 static HRESULT WINAPI GST_QueryInterface(IBaseFilter *iface, REFIID riid, LPVOID *ppv) {
1106     GSTImpl *This = (GSTImpl *)iface;
1107     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
1108
1109     *ppv = NULL;
1110
1111     if (IsEqualIID(riid, &IID_IUnknown))
1112         *ppv = This;
1113     else if (IsEqualIID(riid, &IID_IPersist))
1114         *ppv = This;
1115     else if (IsEqualIID(riid, &IID_IMediaFilter))
1116         *ppv = This;
1117     else if (IsEqualIID(riid, &IID_IBaseFilter))
1118         *ppv = This;
1119
1120     if (*ppv) {
1121         IUnknown_AddRef((IUnknown *)(*ppv));
1122         return S_OK;
1123     }
1124
1125     if (!IsEqualIID(riid, &IID_IPin) && !IsEqualIID(riid, &IID_IVideoWindow) &&
1126         !IsEqualIID(riid, &IID_IAMFilterMiscFlags))
1127         FIXME("No interface for %s!\n", debugstr_guid(riid));
1128
1129     return E_NOINTERFACE;
1130 }
1131
1132 static ULONG WINAPI GST_Release(IBaseFilter *iface) {
1133     GSTImpl *This = (GSTImpl *)iface;
1134     ULONG refCount = BaseFilterImpl_Release(iface);
1135
1136     TRACE("(%p)->() Release from %d\n", This, refCount + 1);
1137
1138     if (!refCount)
1139         GST_Destroy(This);
1140
1141     return refCount;
1142 }
1143
1144 static HRESULT WINAPI GST_Stop(IBaseFilter *iface) {
1145     GSTImpl *This = (GSTImpl *)iface;
1146
1147     TRACE("()\n");
1148
1149     if (This->gstfilter)
1150         gst_element_set_state(This->gstfilter, GST_STATE_READY);
1151     return S_OK;
1152 }
1153
1154 static HRESULT WINAPI GST_Pause(IBaseFilter *iface) {
1155     HRESULT hr = S_OK;
1156     GSTImpl *This = (GSTImpl *)iface;
1157     GstState now;
1158     GstStateChangeReturn ret;
1159     TRACE("()\n");
1160
1161     if (!This->gstfilter)
1162         return VFW_E_NOT_CONNECTED;
1163
1164     gst_element_get_state(This->gstfilter, &now, NULL, -1);
1165     if (now == GST_STATE_PAUSED)
1166         return S_OK;
1167     if (now != GST_STATE_PLAYING)
1168         hr = IBaseFilter_Run(iface, -1);
1169     if (FAILED(hr))
1170         return hr;
1171     ret = gst_element_set_state(This->gstfilter, GST_STATE_PAUSED);
1172     if (ret == GST_STATE_CHANGE_ASYNC)
1173         hr = S_FALSE;
1174     return hr;
1175 }
1176
1177 static HRESULT WINAPI GST_Run(IBaseFilter *iface, REFERENCE_TIME tStart) {
1178     HRESULT hr = S_OK;
1179     GSTImpl *This = (GSTImpl *)iface;
1180     ULONG i;
1181     GstState now;
1182     HRESULT hr_any = VFW_E_NOT_CONNECTED;
1183
1184     TRACE("(%s)\n", wine_dbgstr_longlong(tStart));
1185
1186     if (!This->gstfilter)
1187         return VFW_E_NOT_CONNECTED;
1188
1189     EnterCriticalSection(&This->filter.csFilter);
1190     This->filter.rtStreamStart = tStart;
1191     LeaveCriticalSection(&This->filter.csFilter);
1192
1193     gst_element_get_state(This->gstfilter, &now, NULL, -1);
1194     if (now == GST_STATE_PLAYING)
1195         return S_OK;
1196     if (now == GST_STATE_PAUSED) {
1197         GstStateChangeReturn ret;
1198         ret = gst_element_set_state(This->gstfilter, GST_STATE_PLAYING);
1199         if (ret == GST_STATE_CHANGE_ASYNC)
1200             return S_FALSE;
1201         return S_OK;
1202     }
1203
1204     EnterCriticalSection(&This->filter.csFilter);
1205     gst_pad_set_blocked(This->my_src, 0);
1206     gst_pad_set_blocked(This->their_sink, 0);
1207     gst_element_set_state(This->gstfilter, GST_STATE_PLAYING);
1208     This->filter.rtStreamStart = tStart;
1209
1210     for (i = 0; i < This->cStreams; i++) {
1211         hr = BaseOutputPinImpl_Active((BaseOutputPin *)This->ppPins[i]);
1212         if (SUCCEEDED(hr)) {
1213             gst_pad_set_blocked(This->ppPins[i]->my_sink, 0);
1214             if (This->ppPins[i]->their_src)
1215                 gst_pad_set_blocked(This->ppPins[i]->their_src, 0);
1216             hr_any = hr;
1217         }
1218     }
1219     hr = hr_any;
1220     if (SUCCEEDED(hr))
1221         gst_pad_set_active(This->my_src, 1);
1222     LeaveCriticalSection(&This->filter.csFilter);
1223
1224     return hr;
1225 }
1226
1227 static HRESULT WINAPI GST_GetState(IBaseFilter *iface, DWORD dwMilliSecsTimeout, FILTER_STATE *pState) {
1228     GSTImpl *This = (GSTImpl *)iface;
1229     HRESULT hr = S_OK;
1230     GstState now, pending;
1231     GstStateChangeReturn ret;
1232
1233     TRACE("(%d, %p)\n", dwMilliSecsTimeout, pState);
1234
1235     if (!This->gstfilter) {
1236         *pState = State_Stopped;
1237         return S_OK;
1238     }
1239
1240     ret = gst_element_get_state(This->gstfilter, &now, &pending, dwMilliSecsTimeout == INFINITE ? -1 : dwMilliSecsTimeout * 1000);
1241
1242     if (ret == GST_STATE_CHANGE_ASYNC)
1243         hr = VFW_S_STATE_INTERMEDIATE;
1244     else
1245         pending = now;
1246
1247     switch (pending) {
1248         case GST_STATE_PAUSED: *pState = State_Paused; return hr;
1249         case GST_STATE_PLAYING: *pState = State_Running; return hr;
1250         default: *pState = State_Stopped; return hr;
1251     }
1252 }
1253
1254 static HRESULT WINAPI GST_FindPin(IBaseFilter *iface, LPCWSTR Id, IPin **ppPin) {
1255     FIXME("(%p)->(%s,%p) stub\n", iface, debugstr_w(Id), ppPin);
1256     return E_NOTIMPL;
1257 }
1258
1259 static const IBaseFilterVtbl GST_Vtbl = {
1260     GST_QueryInterface,
1261     BaseFilterImpl_AddRef,
1262     GST_Release,
1263     BaseFilterImpl_GetClassID,
1264     GST_Stop,
1265     GST_Pause,
1266     GST_Run,
1267     GST_GetState,
1268     BaseFilterImpl_SetSyncSource,
1269     BaseFilterImpl_GetSyncSource,
1270     BaseFilterImpl_EnumPins,
1271     GST_FindPin,
1272     BaseFilterImpl_QueryFilterInfo,
1273     BaseFilterImpl_JoinFilterGraph,
1274     BaseFilterImpl_QueryVendorInfo
1275 };
1276
1277 static HRESULT WINAPI GST_ChangeCurrent(IMediaSeeking *iface) {
1278     return S_OK;
1279 }
1280
1281 static HRESULT WINAPI GST_ChangeStop(IMediaSeeking *iface) {
1282     return S_OK;
1283 }
1284
1285 static HRESULT WINAPI GST_ChangeRate(IMediaSeeking *iface) {
1286     GSTOutPin *This = impl_from_IMediaSeeking(iface);
1287     GstEvent *ev = gst_event_new_seek(This->seek.dRate, GST_FORMAT_TIME, 0, GST_SEEK_TYPE_NONE, -1, GST_SEEK_TYPE_NONE, -1);
1288     TRACE("(%p) New rate %g\n", iface, This->seek.dRate);
1289     gst_pad_push_event(This->my_sink, ev);
1290     return S_OK;
1291 }
1292
1293 static HRESULT WINAPI GST_Seeking_QueryInterface(IMediaSeeking *iface, REFIID riid, void **ppv) {
1294     GSTOutPin *This = impl_from_IMediaSeeking(iface);
1295     return IUnknown_QueryInterface((IUnknown *)This, riid, ppv);
1296 }
1297
1298 static ULONG WINAPI GST_Seeking_AddRef(IMediaSeeking *iface) {
1299     GSTOutPin *This = impl_from_IMediaSeeking(iface);
1300     return IUnknown_AddRef((IUnknown *)This);
1301 }
1302
1303 static ULONG WINAPI GST_Seeking_Release(IMediaSeeking *iface) {
1304     GSTOutPin *This = impl_from_IMediaSeeking(iface);
1305     return IUnknown_Release((IUnknown *)This);
1306 }
1307
1308 static HRESULT WINAPI GST_Seeking_GetCurrentPosition(IMediaSeeking *iface, REFERENCE_TIME *pos) {
1309     GSTOutPin *This = impl_from_IMediaSeeking(iface);
1310     GstFormat format = GST_FORMAT_TIME;
1311
1312     if (!pos)
1313         return E_POINTER;
1314
1315     if (!This->their_src) {
1316         *pos = This->seek.llCurrent;
1317         TRACE("Cached value\n");
1318         if (This->seek.llDuration)
1319             return S_OK;
1320         else
1321             return E_NOTIMPL;
1322     }
1323
1324     if (!gst_pad_query_position(This->their_src, &format, pos)) {
1325         WARN("Could not query position\n");
1326         return E_NOTIMPL;
1327     }
1328     *pos /= 100;
1329     This->seek.llCurrent = *pos;
1330     return S_OK;
1331 }
1332
1333 static GstSeekType type_from_flags(DWORD flags) {
1334     switch (flags & AM_SEEKING_PositioningBitsMask) {
1335     case AM_SEEKING_NoPositioning: return GST_SEEK_TYPE_NONE;
1336     case AM_SEEKING_AbsolutePositioning: return GST_SEEK_TYPE_SET;
1337     case AM_SEEKING_RelativePositioning: return GST_SEEK_TYPE_CUR;
1338     case AM_SEEKING_IncrementalPositioning: return GST_SEEK_TYPE_END;
1339     }
1340     return GST_SEEK_TYPE_NONE;
1341 }
1342
1343
1344 static HRESULT WINAPI GST_Seeking_SetPositions(IMediaSeeking *iface, REFERENCE_TIME *pCur, DWORD curflags, REFERENCE_TIME *pStop, DWORD stopflags) {
1345     HRESULT hr;
1346     GSTOutPin *This = impl_from_IMediaSeeking(iface);
1347     GstSeekFlags f = 0;
1348     GstSeekType curtype, stoptype;
1349     GstEvent *e;
1350
1351     if (!This->seek.llDuration)
1352         return E_NOTIMPL;
1353
1354     hr = SourceSeekingImpl_SetPositions(iface, pCur, curflags, pStop, stopflags);
1355     if (!This->their_src)
1356         return hr;
1357
1358     curtype = type_from_flags(curflags);
1359     stoptype = type_from_flags(stopflags);
1360     if (curflags & AM_SEEKING_SeekToKeyFrame)
1361         f |= GST_SEEK_FLAG_KEY_UNIT;
1362     if (curflags & AM_SEEKING_Segment)
1363         f |= GST_SEEK_FLAG_SEGMENT;
1364     if (!(curflags & AM_SEEKING_NoFlush))
1365         f |= GST_SEEK_FLAG_FLUSH;
1366
1367     e = gst_event_new_seek(This->seek.dRate, GST_FORMAT_TIME, f, curtype, pCur ? *pCur * 100 : -1, stoptype, pStop ? *pStop * 100 : -1);
1368     if (gst_pad_push_event(This->my_sink, e))
1369         return S_OK;
1370     else
1371         return E_NOTIMPL;
1372 }
1373
1374 static const IMediaSeekingVtbl GST_Seeking_Vtbl =
1375 {
1376     GST_Seeking_QueryInterface,
1377     GST_Seeking_AddRef,
1378     GST_Seeking_Release,
1379     SourceSeekingImpl_GetCapabilities,
1380     SourceSeekingImpl_CheckCapabilities,
1381     SourceSeekingImpl_IsFormatSupported,
1382     SourceSeekingImpl_QueryPreferredFormat,
1383     SourceSeekingImpl_GetTimeFormat,
1384     SourceSeekingImpl_IsUsingTimeFormat,
1385     SourceSeekingImpl_SetTimeFormat,
1386     SourceSeekingImpl_GetDuration,
1387     SourceSeekingImpl_GetStopPosition,
1388     GST_Seeking_GetCurrentPosition,
1389     SourceSeekingImpl_ConvertTimeFormat,
1390     GST_Seeking_SetPositions,
1391     SourceSeekingImpl_GetPositions,
1392     SourceSeekingImpl_GetAvailable,
1393     SourceSeekingImpl_SetRate,
1394     SourceSeekingImpl_GetRate,
1395     SourceSeekingImpl_GetPreroll
1396 };
1397
1398 static inline GSTOutPin *impl_from_IQualityControl( IQualityControl *iface )
1399 {
1400     return (GSTOutPin*)CONTAINING_RECORD(iface, GSTOutPin, IQualityControl_iface);
1401 }
1402
1403 static HRESULT WINAPI GST_QualityControl_QueryInterface(IQualityControl *iface, REFIID riid, void **ppv)
1404 {
1405     GSTOutPin *pin = impl_from_IQualityControl(iface);
1406     return IPin_QueryInterface((IPin*)pin, riid, ppv);
1407 }
1408
1409 static ULONG WINAPI GST_QualityControl_AddRef(IQualityControl *iface)
1410 {
1411     GSTOutPin *pin = impl_from_IQualityControl(iface);
1412     return IPin_AddRef((IPin*)pin);
1413 }
1414
1415 static ULONG WINAPI GST_QualityControl_Release(IQualityControl *iface)
1416 {
1417     GSTOutPin *pin = impl_from_IQualityControl(iface);
1418     return IPin_Release((IPin*)pin);
1419 }
1420
1421 static HRESULT WINAPI GST_QualityControl_Notify(IQualityControl *iface, IBaseFilter *sender, Quality qm) {
1422     GSTOutPin *pin = impl_from_IQualityControl(iface);
1423     REFERENCE_TIME late = qm.Late;
1424     if (qm.Late < 0 && -qm.Late > qm.TimeStamp)
1425         late = -qm.TimeStamp;
1426     gst_pad_push_event(pin->my_sink, gst_event_new_qos(1000./qm.Proportion, late*100, qm.TimeStamp*100));
1427     return S_OK;
1428 }
1429
1430 static HRESULT WINAPI GST_QualityControl_SetSink(IQualityControl *iface, IQualityControl *tonotify)
1431 {
1432     /* Do nothing */
1433     return S_OK;
1434 }
1435
1436 static const IQualityControlVtbl GSTOutPin_QualityControl_Vtbl = {
1437     GST_QualityControl_QueryInterface,
1438     GST_QualityControl_AddRef,
1439     GST_QualityControl_Release,
1440     GST_QualityControl_Notify,
1441     GST_QualityControl_SetSink
1442 };
1443
1444 static HRESULT WINAPI GSTOutPin_QueryInterface(IPin *iface, REFIID riid, void **ppv) {
1445     GSTOutPin *This = (GSTOutPin *)iface;
1446
1447     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
1448
1449     *ppv = NULL;
1450
1451     if (IsEqualIID(riid, &IID_IUnknown))
1452         *ppv = iface;
1453     else if (IsEqualIID(riid, &IID_IPin))
1454         *ppv = iface;
1455     else if (IsEqualIID(riid, &IID_IMediaSeeking))
1456         *ppv = &This->seek;
1457     else if (IsEqualIID(riid, &IID_IQualityControl))
1458         *ppv = &This->IQualityControl_iface;
1459
1460     if (*ppv) {
1461         IUnknown_AddRef((IUnknown *)(*ppv));
1462         return S_OK;
1463     }
1464     FIXME("No interface for %s!\n", debugstr_guid(riid));
1465     return E_NOINTERFACE;
1466 }
1467
1468 static ULONG WINAPI GSTOutPin_Release(IPin *iface) {
1469     GSTOutPin *This = (GSTOutPin *)iface;
1470     ULONG refCount = InterlockedDecrement(&This->pin.pin.refCount);
1471     TRACE("(%p)->() Release from %d\n", iface, refCount + 1);
1472
1473     if (!refCount) {
1474         if (This->their_src)
1475             gst_pad_unlink(This->their_src, This->my_sink);
1476         gst_object_unref(This->my_sink);
1477         CloseHandle(This->caps_event);
1478         DeleteMediaType(This->pmt);
1479         FreeMediaType(&This->pin.pin.mtCurrent);
1480         gst_segment_free(This->segment);
1481         CoTaskMemFree(This);
1482         return 0;
1483     }
1484     return refCount;
1485 }
1486
1487 static HRESULT WINAPI GSTOutPin_GetMediaType(BasePin *iface, int iPosition, AM_MEDIA_TYPE *pmt)
1488 {
1489     GSTOutPin *This = (GSTOutPin *)iface;
1490
1491     if (iPosition < 0)
1492         return E_INVALIDARG;
1493     if (iPosition > 0)
1494         return VFW_S_NO_MORE_ITEMS;
1495     CopyMediaType(pmt, This->pmt);
1496     return S_OK;
1497 }
1498
1499 static HRESULT WINAPI GSTOutPin_DecideBufferSize(BaseOutputPin *iface, IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *ppropInputRequest)
1500 {
1501     /* Unused */
1502     return S_OK;
1503 }
1504
1505 static HRESULT WINAPI GSTOutPin_DecideAllocator(BaseOutputPin *iface, IMemInputPin *pPin, IMemAllocator **pAlloc)
1506 {
1507     HRESULT hr;
1508     GSTOutPin *This = (GSTOutPin *)iface;
1509     GSTImpl *GSTfilter = (GSTImpl*)This->pin.pin.pinInfo.pFilter;
1510
1511     *pAlloc = NULL;
1512     if (GSTfilter->pInputPin.pAlloc)
1513         hr = IMemInputPin_NotifyAllocator(pPin, GSTfilter->pInputPin.pAlloc, FALSE);
1514     else
1515         hr = VFW_E_NO_ALLOCATOR;
1516
1517     return hr;
1518 }
1519
1520 static HRESULT WINAPI GSTOutPin_BreakConnect(BaseOutputPin *This)
1521 {
1522     HRESULT hr;
1523
1524     TRACE("(%p)->()\n", This);
1525
1526     EnterCriticalSection(This->pin.pCritSec);
1527     if (!This->pin.pConnectedTo || !This->pMemInputPin)
1528         hr = VFW_E_NOT_CONNECTED;
1529     else
1530     {
1531         hr = IPin_Disconnect(This->pin.pConnectedTo);
1532         IPin_Disconnect((IPin *)This);
1533     }
1534     LeaveCriticalSection(This->pin.pCritSec);
1535
1536     return hr;
1537 }
1538
1539 static const IPinVtbl GST_OutputPin_Vtbl = {
1540     GSTOutPin_QueryInterface,
1541     BasePinImpl_AddRef,
1542     GSTOutPin_Release,
1543     BaseOutputPinImpl_Connect,
1544     BaseOutputPinImpl_ReceiveConnection,
1545     BaseOutputPinImpl_Disconnect,
1546     BasePinImpl_ConnectedTo,
1547     BasePinImpl_ConnectionMediaType,
1548     BasePinImpl_QueryPinInfo,
1549     BasePinImpl_QueryDirection,
1550     BasePinImpl_QueryId,
1551     GST_OutPin_QueryAccept,
1552     BasePinImpl_EnumMediaTypes,
1553     BasePinImpl_QueryInternalConnections,
1554     BaseOutputPinImpl_EndOfStream,
1555     BaseOutputPinImpl_BeginFlush,
1556     BaseOutputPinImpl_EndFlush,
1557     BasePinImpl_NewSegment
1558 };
1559
1560 static const BasePinFuncTable output_BaseFuncTable = {
1561     NULL,
1562     BaseOutputPinImpl_AttemptConnection,
1563     BasePinImpl_GetMediaTypeVersion,
1564     GSTOutPin_GetMediaType
1565 };
1566
1567 static const BaseOutputPinFuncTable output_BaseOutputFuncTable = {
1568     GSTOutPin_DecideBufferSize,
1569     GSTOutPin_DecideAllocator,
1570     GSTOutPin_BreakConnect
1571 };
1572
1573 static HRESULT GST_AddPin(GSTImpl *This, const PIN_INFO *piOutput, const AM_MEDIA_TYPE *amt) {
1574     HRESULT hr;
1575     This->ppPins = CoTaskMemRealloc(This->ppPins, (This->cStreams + 1) * sizeof(IPin *));
1576
1577     hr = BaseOutputPin_Construct(&GST_OutputPin_Vtbl, sizeof(GSTOutPin), piOutput, &output_BaseFuncTable, &output_BaseOutputFuncTable, &This->filter.csFilter, (IPin**)(This->ppPins + This->cStreams));
1578     if (SUCCEEDED(hr)) {
1579         GSTOutPin *pin = This->ppPins[This->cStreams];
1580         pin->pmt = CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
1581         CopyMediaType(pin->pmt, amt);
1582         pin->pin.pin.pinInfo.pFilter = (LPVOID)This;
1583         pin->caps_event = CreateEventW(NULL, 0, 0, NULL);
1584         pin->segment = gst_segment_new();
1585         This->cStreams++;
1586         pin->IQualityControl_iface.lpVtbl = &GSTOutPin_QualityControl_Vtbl;
1587         SourceSeeking_Init(&pin->seek, &GST_Seeking_Vtbl, GST_ChangeStop, GST_ChangeCurrent, GST_ChangeRate, &This->filter.csFilter);
1588         BaseFilterImpl_IncrementPinVersion((BaseFilter*)This);
1589     } else
1590         ERR("Failed with error %x\n", hr);
1591     return hr;
1592 }
1593
1594 static HRESULT GST_RemoveOutputPins(GSTImpl *This) {
1595     HRESULT hr;
1596     ULONG i;
1597     GSTOutPin **ppOldPins = This->ppPins;
1598     TRACE("(%p)\n", This);
1599
1600     if (!This->gstfilter)
1601         return S_OK;
1602     gst_element_set_bus(This->gstfilter, NULL);
1603     gst_element_set_state(This->gstfilter, GST_STATE_NULL);
1604     gst_pad_unlink(This->my_src, This->their_sink);
1605     if (This->push_thread)
1606         gst_pad_activate_push(This->my_src, 0);
1607     gst_object_unref(This->my_src);
1608     This->my_src = This->their_sink = NULL;
1609
1610     for (i = 0; i < This->cStreams; i++) {
1611         hr = BaseOutputPinImpl_BreakConnect(&ppOldPins[i]->pin);
1612         TRACE("Disconnect: %08x\n", hr);
1613         IPin_Release((IPin*)ppOldPins[i]);
1614     }
1615     This->cStreams = 0;
1616     This->ppPins = NULL;
1617     gst_object_unref(This->gstfilter);
1618     This->gstfilter = NULL;
1619     BaseFilterImpl_IncrementPinVersion((BaseFilter*)This);
1620     CoTaskMemFree(ppOldPins);
1621     return S_OK;
1622 }
1623
1624 static ULONG WINAPI GSTInPin_Release(IPin *iface) {
1625     GSTInPin *This = (GSTInPin*)iface;
1626     ULONG refCount = InterlockedDecrement(&This->pin.refCount);
1627
1628     TRACE("(%p)->() Release from %d\n", iface, refCount + 1);
1629     if (!refCount) {
1630         FreeMediaType(&This->pin.mtCurrent);
1631         if (This->pAlloc)
1632             IMemAllocator_Release(This->pAlloc);
1633         This->pAlloc = NULL;
1634         This->pin.IPin_iface.lpVtbl = NULL;
1635         return 0;
1636     } else
1637         return refCount;
1638 }
1639
1640 static HRESULT WINAPI GSTInPin_ReceiveConnection(IPin *iface, IPin *pReceivePin, const AM_MEDIA_TYPE *pmt) {
1641     PIN_DIRECTION pindirReceive;
1642     HRESULT hr = S_OK;
1643     GSTInPin *This = (GSTInPin*)iface;
1644
1645     TRACE("(%p/%p)->(%p, %p)\n", This, iface, pReceivePin, pmt);
1646     dump_AM_MEDIA_TYPE(pmt);
1647
1648     EnterCriticalSection(This->pin.pCritSec);
1649     if (!This->pin.pConnectedTo) {
1650         ALLOCATOR_PROPERTIES props;
1651
1652         props.cBuffers = 8;
1653         props.cbBuffer = 16384;
1654         props.cbAlign = 1;
1655         props.cbPrefix = 0;
1656
1657         if (SUCCEEDED(hr) && IPin_QueryAccept(iface, pmt) != S_OK)
1658             hr = VFW_E_TYPE_NOT_ACCEPTED;
1659         if (SUCCEEDED(hr)) {
1660             IPin_QueryDirection(pReceivePin, &pindirReceive);
1661             if (pindirReceive != PINDIR_OUTPUT) {
1662                 ERR("Can't connect from non-output pin\n");
1663                 hr = VFW_E_INVALID_DIRECTION;
1664             }
1665         }
1666
1667         This->pReader = NULL;
1668         This->pAlloc = NULL;
1669         if (SUCCEEDED(hr))
1670             hr = IPin_QueryInterface(pReceivePin, &IID_IAsyncReader, (LPVOID *)&This->pReader);
1671         if (SUCCEEDED(hr))
1672             hr = GST_Connect(This, pReceivePin, &props);
1673         if (SUCCEEDED(hr))
1674             hr = IAsyncReader_RequestAllocator(This->pReader, NULL, &props, &This->pAlloc);
1675         if (SUCCEEDED(hr)) {
1676             CopyMediaType(&This->pin.mtCurrent, pmt);
1677             This->pin.pConnectedTo = pReceivePin;
1678             IPin_AddRef(pReceivePin);
1679             hr = IMemAllocator_Commit(This->pAlloc);
1680         } else {
1681             GST_RemoveOutputPins((GSTImpl *)This->pin.pinInfo.pFilter);
1682             if (This->pReader)
1683                 IAsyncReader_Release(This->pReader);
1684             This->pReader = NULL;
1685             if (This->pAlloc)
1686                 IMemAllocator_Release(This->pAlloc);
1687             This->pAlloc = NULL;
1688         }
1689         TRACE("Size: %i\n", props.cbBuffer);
1690     } else
1691         hr = VFW_E_ALREADY_CONNECTED;
1692     LeaveCriticalSection(This->pin.pCritSec);
1693     return hr;
1694 }
1695
1696 static HRESULT WINAPI GSTInPin_Disconnect(IPin *iface) {
1697     HRESULT hr;
1698     GSTInPin *This = (GSTInPin*)iface;
1699     FILTER_STATE state;
1700     TRACE("()\n");
1701
1702     hr = IBaseFilter_GetState(This->pin.pinInfo.pFilter, INFINITE, &state);
1703     EnterCriticalSection(This->pin.pCritSec);
1704     if (This->pin.pConnectedTo) {
1705         GSTImpl *Parser = (GSTImpl *)This->pin.pinInfo.pFilter;
1706
1707         if (SUCCEEDED(hr) && state == State_Stopped) {
1708             IMemAllocator_Decommit(This->pAlloc);
1709             IPin_Disconnect(This->pin.pConnectedTo);
1710             This->pin.pConnectedTo = NULL;
1711             hr = GST_RemoveOutputPins(Parser);
1712         } else
1713             hr = VFW_E_NOT_STOPPED;
1714     } else
1715         hr = S_FALSE;
1716     LeaveCriticalSection(This->pin.pCritSec);
1717     return hr;
1718 }
1719
1720 static HRESULT WINAPI GSTInPin_QueryAccept(IPin *iface, const AM_MEDIA_TYPE *pmt) {
1721     GSTInPin *This = (GSTInPin*)iface;
1722
1723     TRACE("(%p)->(%p)\n", This, pmt);
1724     dump_AM_MEDIA_TYPE(pmt);
1725
1726     if (IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream))
1727         return S_OK;
1728     return S_FALSE;
1729 }
1730
1731 static HRESULT WINAPI GSTInPin_EndOfStream(IPin *iface) {
1732     GSTInPin *pin = (GSTInPin*)iface;
1733     GSTImpl *This = (GSTImpl*)pin->pin.pinInfo.pFilter;
1734
1735     FIXME("Propagate message on %p\n", This);
1736     return S_OK;
1737 }
1738
1739 static HRESULT WINAPI GSTInPin_BeginFlush(IPin *iface) {
1740     GSTInPin *pin = (GSTInPin*)iface;
1741     GSTImpl *This = (GSTImpl*)pin->pin.pinInfo.pFilter;
1742
1743     FIXME("Propagate message on %p\n", This);
1744     return S_OK;
1745 }
1746
1747 static HRESULT WINAPI GSTInPin_EndFlush(IPin *iface) {
1748     GSTInPin *pin = (GSTInPin*)iface;
1749     GSTImpl *This = (GSTImpl*)pin->pin.pinInfo.pFilter;
1750
1751     FIXME("Propagate message on %p\n", This);
1752     return S_OK;
1753 }
1754
1755 static HRESULT WINAPI GSTInPin_NewSegment(IPin *iface, REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) {
1756     GSTInPin *pin = (GSTInPin*)iface;
1757     GSTImpl *This = (GSTImpl*)pin->pin.pinInfo.pFilter;
1758
1759     BasePinImpl_NewSegment(iface, tStart, tStop, dRate);
1760     FIXME("Propagate message on %p\n", This);
1761     return S_OK;
1762 }
1763
1764 static HRESULT WINAPI GSTInPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
1765 {
1766     GSTInPin *This = (GSTInPin*)iface;
1767
1768     TRACE("(%p/%p)->(%s, %p)\n", This, iface, debugstr_guid(riid), ppv);
1769
1770     *ppv = NULL;
1771
1772     if (IsEqualIID(riid, &IID_IUnknown))
1773         *ppv = iface;
1774     else if (IsEqualIID(riid, &IID_IPin))
1775         *ppv = iface;
1776     else if (IsEqualIID(riid, &IID_IMediaSeeking))
1777     {
1778         return IBaseFilter_QueryInterface(This->pin.pinInfo.pFilter, &IID_IMediaSeeking, ppv);
1779     }
1780
1781     if (*ppv)
1782     {
1783         IUnknown_AddRef((IUnknown *)(*ppv));
1784         return S_OK;
1785     }
1786
1787     FIXME("No interface for %s!\n", debugstr_guid(riid));
1788
1789     return E_NOINTERFACE;
1790 }
1791
1792 static HRESULT WINAPI GSTInPin_EnumMediaTypes(IPin *iface, IEnumMediaTypes **ppEnum)
1793 {
1794     BasePin *This = (BasePin *)iface;
1795
1796     TRACE("(%p/%p)->(%p)\n", This, iface, ppEnum);
1797
1798     return EnumMediaTypes_Construct(This, BasePinImpl_GetMediaType, BasePinImpl_GetMediaTypeVersion, ppEnum);
1799 }
1800
1801 static const IPinVtbl GST_InputPin_Vtbl = {
1802     GSTInPin_QueryInterface,
1803     BasePinImpl_AddRef,
1804     GSTInPin_Release,
1805     BaseInputPinImpl_Connect,
1806     GSTInPin_ReceiveConnection,
1807     GSTInPin_Disconnect,
1808     BasePinImpl_ConnectedTo,
1809     BasePinImpl_ConnectionMediaType,
1810     BasePinImpl_QueryPinInfo,
1811     BasePinImpl_QueryDirection,
1812     BasePinImpl_QueryId,
1813     GSTInPin_QueryAccept,
1814     GSTInPin_EnumMediaTypes,
1815     BasePinImpl_QueryInternalConnections,
1816     GSTInPin_EndOfStream,
1817     GSTInPin_BeginFlush,
1818     GSTInPin_EndFlush,
1819     GSTInPin_NewSegment
1820 };