gstdemux.c 70.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * GStreamer splitter + decoder, adapted from parser.c
 *
 * Copyright 2010 Maarten Lankhorst for CodeWeavers
 * Copyright 2010 Aric Stewart for CodeWeavers
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "config.h"
23 24 25 26

#include <gst/gst.h>
#include <gst/video/video.h>
#include <gst/audio/audio.h>
27 28 29

#include "gst_private.h"
#include "gst_guids.h"
30
#include "gst_cbs.h"
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

#include "vfwmsgs.h"
#include "amvideo.h"

#include "wine/unicode.h"
#include "wine/debug.h"

#include <assert.h>

#include "dvdmedia.h"
#include "mmreg.h"
#include "ks.h"
#include "initguid.h"
#include "ksmedia.h"

WINE_DEFAULT_DEBUG_CHANNEL(gstreamer);

48 49
static pthread_key_t wine_gst_key;

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
typedef struct GSTOutPin GSTOutPin;
typedef struct GSTInPin {
    BasePin pin;
    IAsyncReader *pReader;
    IMemAllocator *pAlloc;
} GSTInPin;

typedef struct GSTImpl {
    BaseFilter filter;

    GSTInPin pInputPin;
    GSTOutPin **ppPins;
    LONG cStreams;

    LONGLONG filesize;

66
    BOOL discont, initial, ignore_flush;
67
    GstElement *container;
68 69 70 71 72
    GstPad *my_src, *their_sink;
    GstBus *bus;
    guint64 start, nextofs, nextpullofs, stop;
    ALLOCATOR_PROPERTIES props;
    HANDLE event, changed_ofs;
73 74

    HANDLE push_thread;
75 76 77 78
} GSTImpl;

struct GSTOutPin {
    BaseOutputPin pin;
79
    IQualityControl IQualityControl_iface;
80

81 82
    GstElement *flipfilter;
    GstPad *flip_sink, *flip_src;
83 84
    GstPad *their_src;
    GstPad *my_sink;
85
    GstBufferPool *gstpool;
86
    BOOL isaud, isvid;
87 88
    AM_MEDIA_TYPE * pmt;
    HANDLE caps_event;
89
    GstSegment *segment;
90
    SourceSeeking seek;
91 92
};

93 94
const char* media_quark_string = "media-sample";

95 96 97 98 99
static const WCHAR wcsInputPinName[] = {'i','n','p','u','t',' ','p','i','n',0};
static const IMediaSeekingVtbl GST_Seeking_Vtbl;
static const IPinVtbl GST_OutputPin_Vtbl;
static const IPinVtbl GST_InputPin_Vtbl;
static const IBaseFilterVtbl GST_Vtbl;
100
static const IQualityControlVtbl GSTOutPin_QualityControl_Vtbl;
101 102 103

static HRESULT GST_AddPin(GSTImpl *This, const PIN_INFO *piOutput, const AM_MEDIA_TYPE *amt);
static HRESULT GST_RemoveOutputPins(GSTImpl *This);
104 105 106
static HRESULT WINAPI GST_ChangeCurrent(IMediaSeeking *iface);
static HRESULT WINAPI GST_ChangeStop(IMediaSeeking *iface);
static HRESULT WINAPI GST_ChangeRate(IMediaSeeking *iface);
107

108 109 110 111 112 113 114 115 116 117 118
void mark_wine_thread(void)
{
    /* set it to non-NULL to indicate that this is a Wine thread */
    pthread_setspecific(wine_gst_key, &wine_gst_key);
}

BOOL is_wine_thread(void)
{
    return pthread_getspecific(wine_gst_key) != NULL;
}

119 120
static gboolean amt_from_gst_caps_audio(GstCaps *caps, AM_MEDIA_TYPE *amt)
{
121 122
    WAVEFORMATEXTENSIBLE *wfe;
    WAVEFORMATEX *wfx;
123
    gint32 depth, bpp;
124
    GstAudioInfo ainfo;
125

126
    if (!gst_audio_info_from_caps (&ainfo, caps))
127
        return FALSE;
128 129 130 131 132 133 134 135 136 137 138 139 140 141

    wfe = CoTaskMemAlloc(sizeof(*wfe));
    wfx = (WAVEFORMATEX*)wfe;
    amt->majortype = MEDIATYPE_Audio;
    amt->subtype = MEDIASUBTYPE_PCM;
    amt->formattype = FORMAT_WaveFormatEx;
    amt->pbFormat = (BYTE*)wfe;
    amt->cbFormat = sizeof(*wfe);
    amt->bFixedSizeSamples = 0;
    amt->bTemporalCompression = 1;
    amt->lSampleSize = 0;
    amt->pUnk = NULL;

    wfx->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
142 143 144 145 146 147

    wfx->nChannels = ainfo.channels;
    wfx->nSamplesPerSec = ainfo.rate;
    depth = GST_AUDIO_INFO_WIDTH(&ainfo);
    bpp = GST_AUDIO_INFO_DEPTH(&ainfo);

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    if (!depth || depth > 32 || depth % 8)
        depth = bpp;
    else if (!bpp)
        bpp = depth;
    wfe->Samples.wValidBitsPerSample = depth;
    wfx->wBitsPerSample = bpp;
    wfx->cbSize = sizeof(*wfe)-sizeof(*wfx);
    switch (wfx->nChannels) {
        case 1: wfe->dwChannelMask = KSAUDIO_SPEAKER_MONO; break;
        case 2: wfe->dwChannelMask = KSAUDIO_SPEAKER_STEREO; break;
        case 4: wfe->dwChannelMask = KSAUDIO_SPEAKER_SURROUND; break;
        case 5: wfe->dwChannelMask = (KSAUDIO_SPEAKER_5POINT1 & ~SPEAKER_LOW_FREQUENCY); break;
        case 6: wfe->dwChannelMask = KSAUDIO_SPEAKER_5POINT1; break;
        case 8: wfe->dwChannelMask = KSAUDIO_SPEAKER_7POINT1; break;
        default:
        wfe->dwChannelMask = 0;
    }
165
    if (GST_AUDIO_INFO_IS_FLOAT(&ainfo)) {
166 167
        wfe->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
        wfx->wBitsPerSample = wfe->Samples.wValidBitsPerSample = 32;
168
    } else {
169
        wfe->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
170 171 172 173 174
        if (wfx->nChannels <= 2 && bpp <= 16 && depth == bpp)  {
            wfx->wFormatTag = WAVE_FORMAT_PCM;
            wfx->cbSize = 0;
        }
    }
175 176
    wfx->nBlockAlign = wfx->nChannels * wfx->wBitsPerSample/8;
    wfx->nAvgBytesPerSec = wfx->nSamplesPerSec * wfx->nBlockAlign;
177
    return TRUE;
178 179
}

180 181
static gboolean amt_from_gst_caps_video(GstCaps *caps, AM_MEDIA_TYPE *amt)
{
182 183
    VIDEOINFOHEADER *vih;
    BITMAPINFOHEADER *bih;
184
    gint32 width, height, nom, denom;
185
    GstVideoInfo vinfo;
186

187
    if (!gst_video_info_from_caps (&vinfo, caps))
188
        return FALSE;
189 190 191 192
    width = vinfo.width;
    height = vinfo.height;
    nom = vinfo.fps_n;
    denom = vinfo.fps_d;
193

194 195 196
    vih = CoTaskMemAlloc(sizeof(*vih));
    bih = &vih->bmiHeader;

197 198 199 200 201 202 203 204
    amt->formattype = FORMAT_VideoInfo;
    amt->pbFormat = (BYTE*)vih;
    amt->cbFormat = sizeof(*vih);
    amt->bFixedSizeSamples = amt->bTemporalCompression = 1;
    amt->lSampleSize = 0;
    amt->pUnk = NULL;
    ZeroMemory(vih, sizeof(*vih));
    amt->majortype = MEDIATYPE_Video;
205 206
    if (GST_VIDEO_INFO_IS_RGB(&vinfo)) {
        bih->biBitCount = GST_VIDEO_FORMAT_INFO_BITS(vinfo.finfo);
207 208 209 210 211 212
        switch (bih->biBitCount) {
            case 16: amt->subtype = MEDIASUBTYPE_RGB555; break;
            case 24: amt->subtype = MEDIASUBTYPE_RGB24; break;
            case 32: amt->subtype = MEDIASUBTYPE_RGB32; break;
            default:
                FIXME("Unknown bpp %u\n", bih->biBitCount);
213
                CoTaskMemFree(vih);
214
                return FALSE;
215 216 217 218
        }
        bih->biCompression = BI_RGB;
    } else {
        amt->subtype = MEDIATYPE_Video;
219 220
        if (!(amt->subtype.Data1 = gst_video_format_to_fourcc(vinfo.finfo->format))) {
            CoTaskMemFree(vih);
221
            return FALSE;
222
        }
223 224 225 226 227 228 229 230 231 232 233 234 235
        switch (amt->subtype.Data1) {
            case mmioFOURCC('I','4','2','0'):
            case mmioFOURCC('Y','V','1','2'):
            case mmioFOURCC('N','V','1','2'):
            case mmioFOURCC('N','V','2','1'):
                bih->biBitCount = 12; break;
            case mmioFOURCC('Y','U','Y','2'):
            case mmioFOURCC('Y','V','Y','U'):
                bih->biBitCount = 16; break;
        }
        bih->biCompression = amt->subtype.Data1;
    }
    bih->biSizeImage = width * height * bih->biBitCount / 8;
236 237
    if ((vih->AvgTimePerFrame = (REFERENCE_TIME)MulDiv(10000000, denom, nom)) == -1)
        vih->AvgTimePerFrame = 0; /* zero division or integer overflow */
238 239 240 241 242 243 244 245 246
    vih->rcSource.left = 0;
    vih->rcSource.right = width;
    vih->rcSource.top = height;
    vih->rcSource.bottom = 0;
    vih->rcTarget = vih->rcSource;
    bih->biSize = sizeof(*bih);
    bih->biWidth = width;
    bih->biHeight = height;
    bih->biPlanes = 1;
247
    return TRUE;
248 249
}

250 251
static gboolean accept_caps_sink(GstPad *pad, GstCaps *caps)
{
252 253
    GSTOutPin *pin = gst_pad_get_element_private(pad);
    AM_MEDIA_TYPE amt;
254 255
    GstStructure *arg;
    const char *typename;
256
    gboolean ret;
257 258 259

    TRACE("%p %p\n", pad, caps);

260 261
    arg = gst_caps_get_structure(caps, 0);
    typename = gst_structure_get_name(arg);
262
    if (!strcmp(typename, "audio/x-raw")) {
263 264
        if (!pin->isaud) {
            ERR("Setting audio caps on non-audio pad?\n");
265
            return FALSE;
266 267
        }
        ret = amt_from_gst_caps_audio(caps, &amt);
268 269
        if (ret)
            FreeMediaType(&amt);
270 271
        TRACE("+%i\n", ret);
        return ret;
272
    } else if (!strcmp(typename, "video/x-raw")) {
273 274
        if (!pin->isvid) {
            ERR("Setting video caps on non-video pad?\n");
275
            return FALSE;
276 277
        }
        ret = amt_from_gst_caps_video(caps, &amt);
278 279
        if (ret)
            FreeMediaType(&amt);
280 281 282 283
        TRACE("-%i\n", ret);
        return ret;
    } else {
        FIXME("Unhandled type \"%s\"\n", typename);
284
        return FALSE;
285
    }
286 287
}

288 289
static gboolean setcaps_sink(GstPad *pad, GstCaps *caps)
{
290 291 292
    GSTOutPin *pin = gst_pad_get_element_private(pad);
    GSTImpl *This = (GSTImpl *)pin->pin.pin.pinInfo.pFilter;
    AM_MEDIA_TYPE amt;
293 294
    GstStructure *arg;
    const char *typename;
295
    gboolean ret;
296 297 298

    TRACE("%p %p\n", pad, caps);

299 300
    arg = gst_caps_get_structure(caps, 0);
    typename = gst_structure_get_name(arg);
301
    if (!strcmp(typename, "audio/x-raw")) {
302 303
        if (!pin->isaud) {
            ERR("Setting audio caps on non-audio pad?\n");
304
            return FALSE;
305 306
        }
        ret = amt_from_gst_caps_audio(caps, &amt);
307
    } else if (!strcmp(typename, "video/x-raw")) {
308 309
        if (!pin->isvid) {
            ERR("Setting video caps on non-video pad?\n");
310
            return FALSE;
311 312 313 314 315 316
        }
        ret = amt_from_gst_caps_video(caps, &amt);
        if (ret)
            This->props.cbBuffer = max(This->props.cbBuffer, ((VIDEOINFOHEADER*)amt.pbFormat)->bmiHeader.biSizeImage);
    } else {
        FIXME("Unhandled type \"%s\"\n", typename);
317
        return FALSE;
318 319 320
    }
    TRACE("Linking returned %i for %s\n", ret, typename);
    if (!ret)
321
        return FALSE;
322 323
    FreeMediaType(pin->pmt);
    *pin->pmt = amt;
324
    return TRUE;
325 326
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
static gboolean query_sink(GstPad *pad, GstObject *parent, GstQuery *query)
{
    switch (GST_QUERY_TYPE (query)) {
        case GST_QUERY_ACCEPT_CAPS:
        {
            GstCaps *caps;
            gboolean res;
            gst_query_parse_accept_caps(query, &caps);
            res = accept_caps_sink(pad, caps);
            gst_query_set_accept_caps_result(query, res);
            return TRUE; /* FIXME */
        }
        default:
            return gst_pad_query_default (pad, parent, query);
    }
}

344 345 346 347 348 349 350 351 352 353 354
static gboolean gst_base_src_perform_seek(GSTImpl *This, GstEvent *event)
{
    gboolean res = TRUE;
    gdouble rate;
    GstFormat seek_format;
    GstSeekFlags flags;
    GstSeekType cur_type, stop_type;
    gint64 cur, stop;
    gboolean flush;
    guint32 seqnum;
    GstEvent *tevent;
355
    BOOL thread = !!This->push_thread;
356

357 358
    TRACE("%p %p\n", This, event);

359 360 361 362 363
    gst_event_parse_seek(event, &rate, &seek_format, &flags,
                         &cur_type, &cur, &stop_type, &stop);

    if (seek_format != GST_FORMAT_BYTES) {
        FIXME("Not handling other format %i\n", seek_format);
364
        return FALSE;
365 366 367 368 369 370 371 372 373 374 375 376
    }

    flush = flags & GST_SEEK_FLAG_FLUSH;
    seqnum = gst_event_get_seqnum(event);

    /* send flush start */
    if (flush) {
        tevent = gst_event_new_flush_start();
        gst_event_set_seqnum(tevent, seqnum);
        gst_pad_push_event(This->my_src, tevent);
        if (This->pInputPin.pReader)
            IAsyncReader_BeginFlush(This->pInputPin.pReader);
377
        if (thread)
378
            gst_pad_set_active(This->my_src, 1);
379 380
    }

381
    This->nextofs = This->start = cur;
382 383 384

    /* and prepare to continue streaming */
    if (flush) {
385
        tevent = gst_event_new_flush_stop(TRUE);
386 387 388 389
        gst_event_set_seqnum(tevent, seqnum);
        gst_pad_push_event(This->my_src, tevent);
        if (This->pInputPin.pReader)
            IAsyncReader_EndFlush(This->pInputPin.pReader);
390
        if (thread)
391
            gst_pad_set_active(This->my_src, 1);
392 393 394 395 396
    }

    return res;
}

397
static gboolean event_src(GstPad *pad, GstObject *parent, GstEvent *event)
398
{
399
    GSTImpl *This = gst_pad_get_element_private(pad);
400 401 402

    TRACE("%p %p\n", pad, event);

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    switch (event->type) {
        case GST_EVENT_SEEK:
            return gst_base_src_perform_seek(This, event);
        case GST_EVENT_FLUSH_START:
            EnterCriticalSection(&This->filter.csFilter);
            if (This->pInputPin.pReader)
                IAsyncReader_BeginFlush(This->pInputPin.pReader);
            LeaveCriticalSection(&This->filter.csFilter);
            break;
        case GST_EVENT_FLUSH_STOP:
            EnterCriticalSection(&This->filter.csFilter);
            if (This->pInputPin.pReader)
                IAsyncReader_EndFlush(This->pInputPin.pReader);
            LeaveCriticalSection(&This->filter.csFilter);
            break;
        default:
419 420 421
            FIXME("%p (%u) stub\n", event, event->type);
        case GST_EVENT_TAG:
        case GST_EVENT_QOS:
422
            return gst_pad_event_default(pad, parent, event);
423
    }
424
    return TRUE;
425 426
}

427
static gboolean event_sink(GstPad *pad, GstObject *parent, GstEvent *event)
428
{
429
    GSTOutPin *pin = gst_pad_get_element_private(pad);
430 431 432

    TRACE("%p %p\n", pad, event);

433
    switch (event->type) {
434
        case GST_EVENT_SEGMENT: {
435
            gdouble rate, applied_rate;
436 437 438 439 440 441 442 443 444 445 446 447
            gint64 stop, pos;
            const GstSegment *segment;

            gst_event_parse_segment(event, &segment);

            pos = segment->position;
            stop = segment->stop;
            rate = segment->rate;
            applied_rate = segment->applied_rate;

            if (segment->format != GST_FORMAT_TIME) {
                FIXME("Ignoring new segment because of format %i\n", segment->format);
448
                return TRUE;
449
            }
450 451 452

            gst_segment_copy_into(segment, pin->segment);

453
            pos /= 100;
454

455 456
            if (stop > 0)
                stop /= 100;
457

458 459
            if (pin->pin.pin.pConnectedTo)
                IPin_NewSegment(pin->pin.pin.pConnectedTo, pos, stop, rate*applied_rate);
460

461
            return TRUE;
462 463 464 465
        }
        case GST_EVENT_EOS:
            if (pin->pin.pin.pConnectedTo)
                IPin_EndOfStream(pin->pin.pin.pConnectedTo);
466
            return TRUE;
467
        case GST_EVENT_FLUSH_START:
468 469 470 471 472 473 474 475 476 477 478
            if (((GSTImpl *)pin->pin.pin.pinInfo.pFilter)->ignore_flush) {
                /* gst-plugins-base prior to 1.7 contains a bug which causes
                 * our sink pins to receive a flush-start event when the
                 * decodebin changes from PAUSED to READY (including
                 * PLAYING->PAUSED->READY), but no matching flush-stop event is
                 * sent. See <gst-plugins-base.git:60bad4815db966a8e4). Here we
                 * unset the flushing flag to avoid the problem. */
                TRACE("Working around gst <1.7 bug, ignoring FLUSH_START\n");
                GST_PAD_UNSET_FLUSHING (pad);
                return TRUE;
            }
479 480
            if (pin->pin.pin.pConnectedTo)
                IPin_BeginFlush(pin->pin.pin.pConnectedTo);
481
            return TRUE;
482
        case GST_EVENT_FLUSH_STOP:
483
            gst_segment_init(pin->segment, GST_FORMAT_TIME);
484 485
            if (pin->pin.pin.pConnectedTo)
                IPin_EndFlush(pin->pin.pin.pConnectedTo);
486
            return TRUE;
487 488 489 490 491
        case GST_EVENT_CAPS: {
            GstCaps *caps;
            gst_event_parse_caps(event, &caps);
            return setcaps_sink(pad, caps);
        }
492
        default:
493 494
            TRACE("%p stub %s\n", event, gst_event_type_get_name(event->type));
            return gst_pad_event_default(pad, parent, event);
495 496 497
    }
}

498 499
static void release_sample(void *data)
{
500 501 502 503 504
    ULONG ret;
    ret = IMediaSample_Release((IMediaSample *)data);
    TRACE("Releasing %p returns %u\n", data, ret);
}

505 506
static DWORD CALLBACK push_data(LPVOID iface)
{
507
    LONGLONG maxlen, curlen;
508 509 510 511 512
    GSTImpl *This = iface;
    IMediaSample *buf;
    DWORD_PTR user;
    HRESULT hr;

513 514 515 516
    if (!This->stop)
        IAsyncReader_Length(This->pInputPin.pReader, &maxlen, &curlen);
    else
        maxlen = This->stop;
517

518 519 520 521
    TRACE("Waiting..\n");

    WaitForSingleObject(This->event, INFINITE);

522 523 524 525 526
    TRACE("Starting..\n");
    for (;;) {
        REFERENCE_TIME tStart, tStop;
        ULONG len;
        GstBuffer *gstbuf;
527
        gsize bufsize;
528 529 530
        BYTE *data;
        int ret;

531
        TRACE("pAlloc: %p\n", This->pInputPin.pAlloc);
532 533 534 535
        hr = IMemAllocator_GetBuffer(This->pInputPin.pAlloc, &buf, NULL, NULL, 0);
        if (FAILED(hr))
            break;

536 537
        if (This->nextofs >= maxlen)
            break;
538
        len = IMediaSample_GetSize(buf);
539 540
        if (This->nextofs + len > maxlen)
            len = maxlen - This->nextofs;
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

        tStart = MEDIATIME_FROM_BYTES(This->nextofs);
        tStop = tStart + MEDIATIME_FROM_BYTES(len);
        IMediaSample_SetTime(buf, &tStart, &tStop);

        hr = IAsyncReader_Request(This->pInputPin.pReader, buf, 0);
        if (FAILED(hr)) {
            IMediaSample_Release(buf);
            break;
        }
        This->nextofs += len;
        hr = IAsyncReader_WaitForNext(This->pInputPin.pReader, -1, &buf, &user);
        if (FAILED(hr) || !buf) {
            if (buf)
                IMediaSample_Release(buf);
            break;
        }

        IMediaSample_GetPointer(buf, &data);
560 561 562 563
        bufsize = IMediaSample_GetActualDataLength(buf);
        gstbuf = gst_buffer_new_wrapped_full(0, data, bufsize, 0, bufsize, buf, release_sample_wrapper);
        IMediaSample_AddRef(buf);
        gst_mini_object_set_qdata(GST_MINI_OBJECT(gstbuf), g_quark_from_static_string(media_quark_string), buf, release_sample_wrapper);
564 565
        if (!gstbuf) {
            IMediaSample_Release(buf);
566
            break;
567
        }
568
        gstbuf->duration = gstbuf->pts = -1;
569 570 571 572 573 574 575
        ret = gst_pad_push(This->my_src, gstbuf);
        if (ret >= 0)
            hr = S_OK;
        else
            ERR("Sending returned: %i\n", ret);
        if (ret == GST_FLOW_ERROR)
            hr = E_FAIL;
576
        else if (ret == GST_FLOW_FLUSHING)
577 578 579 580 581
            hr = VFW_E_WRONG_STATE;
        if (hr != S_OK)
            break;
    }

582 583
    gst_pad_push_event(This->my_src, gst_event_new_eos());

584 585 586 587 588 589 590 591 592 593 594
    TRACE("Almost stopping.. %08x\n", hr);
    do {
        IAsyncReader_WaitForNext(This->pInputPin.pReader, 0, &buf, &user);
        if (buf)
            IMediaSample_Release(buf);
    } while (buf);

    TRACE("Stopping.. %08x\n", hr);
    return 0;
}

595 596
static HRESULT WINAPI GST_OutPin_QueryAccept(IPin *iface, const AM_MEDIA_TYPE *pmt)
{
597 598 599 600 601
    GSTOutPin *pin = (GSTOutPin*)iface;
    FIXME("stub %p\n", pin);
    return S_OK;
}

602
static GstFlowReturn got_data_sink(GstPad *pad, GstObject *parent, GstBuffer *buf)
603
{
604 605 606
    GSTOutPin *pin = gst_pad_get_element_private(pad);
    GSTImpl *This = (GSTImpl *)pin->pin.pin.pinInfo.pFilter;
    HRESULT hr;
607 608 609
    BYTE *ptr = NULL;
    IMediaSample *sample;
    GstMapInfo info;
610

611 612
    TRACE("%p %p\n", pad, buf);

613 614
    if (This->initial) {
        gst_buffer_unref(buf);
615
        TRACE("Triggering %p %p\n", pad, pin->caps_event);
616
        SetEvent(pin->caps_event);
617 618 619 620 621 622 623
        return GST_FLOW_OK;
    }

    hr = BaseOutputPinImpl_GetDeliveryBuffer(&pin->pin, &sample, NULL, NULL, 0);

    if (hr == VFW_E_NOT_CONNECTED) {
        gst_buffer_unref(buf);
624 625 626
        return GST_FLOW_NOT_LINKED;
    }

627 628 629 630 631 632 633 634 635 636 637 638
    if (FAILED(hr)) {
        gst_buffer_unref(buf);
        ERR("Could not get a delivery buffer (%x), returning GST_FLOW_FLUSHING\n", hr);
        return GST_FLOW_FLUSHING;
    }

    gst_buffer_map(buf, &info, GST_MAP_READ);

    hr = IMediaSample_SetActualDataLength(sample, info.size);
    if(FAILED(hr)){
        WARN("SetActualDataLength failed: %08x\n", hr);
        return GST_FLOW_FLUSHING;
639 640
    }

641 642 643 644 645 646 647 648
    IMediaSample_GetPointer(sample, &ptr);

    memcpy(ptr, info.data, info.size);

    gst_buffer_unmap(buf, &info);

    if (GST_BUFFER_PTS_IS_VALID(buf)) {
        REFERENCE_TIME rtStart = gst_segment_to_running_time(pin->segment, GST_FORMAT_TIME, buf->pts);
649 650 651 652
        if (rtStart >= 0)
            rtStart /= 100;

        if (GST_BUFFER_DURATION_IS_VALID(buf)) {
653 654
            REFERENCE_TIME tStart = buf->pts / 100;
            REFERENCE_TIME tStop = (buf->pts + buf->duration) / 100;
655
            REFERENCE_TIME rtStop;
656
            rtStop = gst_segment_to_running_time(pin->segment, GST_FORMAT_TIME, buf->pts + buf->duration);
657 658
            if (rtStop >= 0)
                rtStop /= 100;
659
            TRACE("Current time on %p: %i to %i ms\n", pin, (int)(rtStart / 10000), (int)(rtStop / 10000));
660 661 662 663 664 665 666
            IMediaSample_SetTime(sample, &rtStart, rtStop >= 0 ? &rtStop : NULL);
            IMediaSample_SetMediaTime(sample, &tStart, &tStop);
        } else {
            IMediaSample_SetTime(sample, rtStart >= 0 ? &rtStart : NULL, NULL);
            IMediaSample_SetMediaTime(sample, NULL, NULL);
        }
    } else {
667
        IMediaSample_SetTime(sample, NULL, NULL);
668 669
        IMediaSample_SetMediaTime(sample, NULL, NULL);
    }
670 671

    IMediaSample_SetDiscontinuity(sample, GST_BUFFER_FLAG_IS_SET(buf, GST_BUFFER_FLAG_DISCONT));
672
    IMediaSample_SetPreroll(sample, GST_BUFFER_FLAG_IS_SET(buf, GST_BUFFER_FLAG_LIVE));
673 674 675 676 677 678 679
    IMediaSample_SetSyncPoint(sample, !GST_BUFFER_FLAG_IS_SET(buf, GST_BUFFER_FLAG_DELTA_UNIT));

    if (!pin->pin.pin.pConnectedTo)
        hr = VFW_E_NOT_CONNECTED;
    else
        hr = IMemInputPin_Receive(pin->pin.pMemInputPin, sample);

680
    TRACE("sending sample returned: %08x\n", hr);
681

682 683
    gst_buffer_unref(buf);
    IMediaSample_Release(sample);
684 685 686

    if (hr == VFW_E_NOT_CONNECTED)
        return GST_FLOW_NOT_LINKED;
687 688 689 690

    if (FAILED(hr))
        return GST_FLOW_FLUSHING;

691 692 693
    return GST_FLOW_OK;
}

694
static GstFlowReturn request_buffer_src(GstPad *pad, GstObject *parent, guint64 ofs, guint len, GstBuffer **buf)
695
{
696
    GSTImpl *This = gst_pad_get_element_private(pad);
697 698
    HRESULT hr;
    GstMapInfo info;
699

700 701
    TRACE("%p %s %i %p\n", pad, wine_dbgstr_longlong(ofs), len, buf);

702
    *buf = NULL;
703
    if (ofs == GST_BUFFER_OFFSET_NONE)
704 705 706
        ofs = This->nextpullofs;
    if (ofs >= This->filesize) {
        WARN("Reading past eof: %s, %u\n", wine_dbgstr_longlong(ofs), len);
707
        return GST_FLOW_EOS;
708 709 710 711 712
    }
    if (len + ofs > This->filesize)
        len = This->filesize - ofs;
    This->nextpullofs = ofs + len;

713 714 715 716 717 718 719
    *buf = gst_buffer_new_and_alloc(len);
    gst_buffer_map(*buf, &info, GST_MAP_WRITE);
    hr = IAsyncReader_SyncRead(This->pInputPin.pReader, ofs, len, info.data);
    gst_buffer_unmap(*buf, &info);
    if (FAILED(hr)) {
        ERR("Returned %08x\n", hr);
        return GST_FLOW_ERROR;
720
    }
721 722

    GST_BUFFER_OFFSET(*buf) = ofs;
723
    return GST_FLOW_OK;
724 725
}

726 727
static DWORD CALLBACK push_data_init(LPVOID iface)
{
728 729 730 731 732 733
    GSTImpl *This = iface;
    DWORD64 ofs = 0;

    TRACE("Starting..\n");
    for (;;) {
        GstBuffer *buf;
734
        GstFlowReturn ret = request_buffer_src(This->my_src, NULL, ofs, 4096, &buf);
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        if (ret < 0) {
            ERR("Obtaining buffer returned: %i\n", ret);
            break;
        }
        ret = gst_pad_push(This->my_src, buf);
        ofs += 4096;
        if (ret)
            TRACE("Sending returned: %i\n", ret);
        if (ret < 0)
            break;
    }
    TRACE("Stopping..\n");
    return 0;
}

750 751
static void removed_decoded_pad(GstElement *bin, GstPad *pad, gpointer user)
{
752
    GSTImpl *This = (GSTImpl*)user;
753 754 755
    int x;
    GSTOutPin *pin;

756 757
    TRACE("%p %p %p\n", This, bin, pad);

758 759 760 761 762 763 764
    EnterCriticalSection(&This->filter.csFilter);
    for (x = 0; x < This->cStreams; ++x) {
        if (This->ppPins[x]->their_src == pad)
            break;
    }
    if (x == This->cStreams)
        goto out;
765

766
    pin = This->ppPins[x];
767 768 769 770 771 772

    if(pin->flipfilter)
        gst_pad_unlink(pin->their_src, pin->flip_sink);
    else
        gst_pad_unlink(pin->their_src, pin->my_sink);

773 774 775 776 777 778 779
    gst_object_unref(pin->their_src);
    pin->their_src = NULL;
out:
    TRACE("Removed %i/%i\n", x, This->cStreams);
    LeaveCriticalSection(&This->filter.csFilter);
}

780
static void init_new_decoded_pad(GstElement *bin, GstPad *pad, GSTImpl *This)
781
{
782
    HRESULT hr;
783 784 785
    PIN_INFO piOutput;
    const char *typename;
    char *name;
786
    AM_MEDIA_TYPE amt = {{0}};
787 788 789
    GstCaps *caps;
    GstStructure *arg;
    GstPad *mypad;
790 791
    GSTOutPin *pin;
    int ret;
792
    BOOL isvid = FALSE, isaud = FALSE;
793
    gchar my_name[1024];
794

795
    TRACE("%p %p %p\n", This, bin, pad);
796

797
    piOutput.dir = PINDIR_OUTPUT;
798
    piOutput.pFilter = &This->filter.IBaseFilter_iface;
799 800 801
    name = gst_pad_get_name(pad);
    MultiByteToWideChar(CP_UNIXCP, 0, name, -1, piOutput.achName, sizeof(piOutput.achName) / sizeof(piOutput.achName[0]) - 1);
    TRACE("Name: %s\n", name);
802 803
    strcpy(my_name, "qz_sink_");
    strcat(my_name, name);
804 805 806
    g_free(name);
    piOutput.achName[sizeof(piOutput.achName) / sizeof(piOutput.achName[0]) - 1] = 0;

807 808
    caps = gst_pad_query_caps(pad, NULL);
    caps = gst_caps_make_writable(caps);
809 810 811
    arg = gst_caps_get_structure(caps, 0);
    typename = gst_structure_get_name(arg);

812
    mypad = gst_pad_new(my_name, GST_PAD_SINK);
813 814
    gst_pad_set_chain_function(mypad, got_data_sink_wrapper);
    gst_pad_set_event_function(mypad, event_sink_wrapper);
815
    gst_pad_set_query_function(mypad, query_sink_wrapper);
816

817
    if (!strcmp(typename, "audio/x-raw")) {
818
        isaud = TRUE;
819
    } else if (!strcmp(typename, "video/x-raw")) {
820
        isvid = TRUE;
821 822 823 824
    } else {
        FIXME("Unknown type \'%s\'\n", typename);
        return;
    }
825

826 827 828 829 830
    hr = GST_AddPin(This, &piOutput, &amt);
    if (FAILED(hr)) {
        ERR("%08x\n", hr);
        return;
    }
831

832 833 834
    pin = This->ppPins[This->cStreams - 1];
    gst_pad_set_element_private(mypad, pin);
    pin->my_sink = mypad;
835
    pin->isaud = isaud;
836 837
    pin->isvid = isvid;

838
    gst_segment_init(pin->segment, GST_FORMAT_TIME);
839 840

    if (isvid) {
841 842
        GstElement *vconv;

843 844 845 846 847
        TRACE("setting up videoflip filter for pin %p, my_sink: %p, their_src: %p\n",
                pin, pin->my_sink, pad);

        /* gstreamer outputs video top-down, but dshow expects bottom-up, so
         * make new transform filter to invert video */
848 849 850 851 852 853 854
        vconv = gst_element_factory_make("videoconvert", NULL);
        if(!vconv){
            ERR("Missing videoconvert filter?\n");
            ret = -1;
            goto exit;
        }

855 856 857 858 859 860 861 862 863
        pin->flipfilter = gst_element_factory_make("videoflip", NULL);
        if(!pin->flipfilter){
            ERR("Missing videoflip filter?\n");
            ret = -1;
            goto exit;
        }

        gst_util_set_object_arg(G_OBJECT(pin->flipfilter), "method", "vertical-flip");

864 865 866
        gst_bin_add(GST_BIN(This->container), vconv); /* bin takes ownership */
        gst_element_sync_state_with_parent(vconv);
        gst_bin_add(GST_BIN(This->container), pin->flipfilter); /* bin takes ownership */
867 868
        gst_element_sync_state_with_parent(pin->flipfilter);

869 870 871
        gst_element_link (vconv, pin->flipfilter);

        pin->flip_sink = gst_element_get_static_pad(vconv, "sink");
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
        if(!pin->flip_sink){
            WARN("Couldn't find sink on flip filter\n");
            pin->flipfilter = NULL;
            ret = -1;
            goto exit;
        }

        ret = gst_pad_link(pad, pin->flip_sink);
        if(ret < 0){
            WARN("gst_pad_link failed: %d\n", ret);
            gst_object_unref(pin->flip_sink);
            pin->flip_sink = NULL;
            pin->flipfilter = NULL;
            goto exit;
        }

        pin->flip_src = gst_element_get_static_pad(pin->flipfilter, "src");
        if(!pin->flip_src){
            WARN("Couldn't find src on flip filter\n");
            gst_object_unref(pin->flip_sink);
            pin->flip_sink = NULL;
            pin->flipfilter = NULL;
            ret = -1;
            goto exit;
        }

        ret = gst_pad_link(pin->flip_src, pin->my_sink);
        if(ret < 0){
            WARN("gst_pad_link failed: %d\n", ret);
            gst_object_unref(pin->flip_src);
            pin->flip_src = NULL;
            gst_object_unref(pin->flip_sink);
            pin->flip_sink = NULL;
            pin->flipfilter = NULL;
            goto exit;
        }
    } else
        ret = gst_pad_link(pad, mypad);
910 911 912

    gst_pad_set_active(mypad, 1);

913
exit:
914
    TRACE("Linking: %i\n", ret);
915

916 917 918 919
    if (ret >= 0) {
        pin->their_src = pad;
        gst_object_ref(pin->their_src);
    }
920 921
}

922
static void existing_new_pad(GstElement *bin, GstPad *pad, gpointer user)
923
{
924
    GSTImpl *This = (GSTImpl*)user;
925
    int x, ret;
926

927
    TRACE("%p %p %p\n", This, bin, pad);
928

929 930 931 932 933
    if (gst_pad_is_linked(pad))
        return;

    /* Still holding our own lock */
    if (This->initial) {
934
        init_new_decoded_pad(bin, pad, This);
935 936 937 938 939 940 941
        return;
    }

    EnterCriticalSection(&This->filter.csFilter);
    for (x = 0; x < This->cStreams; ++x) {
        GSTOutPin *pin = This->ppPins[x];
        if (!pin->their_src) {
942
            gst_segment_init(pin->segment, GST_FORMAT_TIME);
943 944 945 946 947 948 949

            if (pin->flipfilter)
                ret = gst_pad_link(pad, pin->flip_sink);
            else
                ret = gst_pad_link(pad, pin->my_sink);

            if (ret >= 0) {
950 951 952 953 954 955 956 957
                pin->their_src = pad;
                gst_object_ref(pin->their_src);
                TRACE("Relinked\n");
                LeaveCriticalSection(&This->filter.csFilter);
                return;
            }
        }
    }
958
    init_new_decoded_pad(bin, pad, This);
959 960 961
    LeaveCriticalSection(&This->filter.csFilter);
}

962
static gboolean query_function(GstPad *pad, GstObject *parent, GstQuery *query)
963
{
964 965 966 967 968
    GSTImpl *This = gst_pad_get_element_private(pad);
    GstFormat format;
    int ret;
    LONGLONG duration;

969 970
    TRACE("%p %p %p\n", This, pad, query);

971 972 973 974 975
    switch (GST_QUERY_TYPE(query)) {
        case GST_QUERY_DURATION:
            gst_query_parse_duration (query, &format, NULL);
            if (format == GST_FORMAT_PERCENT) {
                gst_query_set_duration (query, GST_FORMAT_PERCENT, GST_FORMAT_PERCENT_MAX);
976
                return TRUE;
977
            }
978
            ret = gst_pad_query_convert (pad, GST_FORMAT_BYTES, This->filesize, format, &duration);
979 980 981 982 983 984
            gst_query_set_duration(query, format, duration);
            return ret;
        case GST_QUERY_SEEKING:
            gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
            TRACE("Seeking %i %i\n", format, GST_FORMAT_BYTES);
            if (format != GST_FORMAT_BYTES)
985
                return FALSE;
986
            gst_query_set_seeking(query, GST_FORMAT_BYTES, 1, 0, This->filesize);
987
            return TRUE;
988 989 990 991 992
        case GST_QUERY_SCHEDULING:
            gst_query_set_scheduling(query, GST_SCHEDULING_FLAG_SEEKABLE, 1, -1, 0);
            gst_query_add_scheduling_mode(query, GST_PAD_MODE_PUSH);
            gst_query_add_scheduling_mode(query, GST_PAD_MODE_PULL);
            return TRUE;
993
        default:
994
            TRACE("Unhandled query type: %s\n", GST_QUERY_TYPE_NAME(query));
995
            return FALSE;
996 997 998
    }
}

999 1000
static gboolean activate_push(GstPad *pad, gboolean activate)
{
1001
    GSTImpl *This = gst_pad_get_element_private(pad);
1002 1003 1004

    TRACE("%p %p %u\n", This, pad, activate);

1005 1006 1007
    EnterCriticalSection(&This->filter.csFilter);
    if (!activate) {
        TRACE("Deactivating\n");
1008 1009
        if (!This->initial)
            IAsyncReader_BeginFlush(This->pInputPin.pReader);
1010 1011 1012 1013 1014
        if (This->push_thread) {
            WaitForSingleObject(This->push_thread, -1);
            CloseHandle(This->push_thread);
            This->push_thread = NULL;
        }
1015 1016
        if (!This->initial)
            IAsyncReader_EndFlush(This->pInputPin.pReader);
1017 1018
        if (This->filter.state == State_Stopped)
            This->nextofs = This->start;
1019 1020 1021 1022 1023 1024 1025 1026
    } else if (!This->push_thread) {
        TRACE("Activating\n");
        if (This->initial)
            This->push_thread = CreateThread(NULL, 0, push_data_init, This, 0, NULL);
        else
            This->push_thread = CreateThread(NULL, 0, push_data, This, 0, NULL);
    }
    LeaveCriticalSection(&This->filter.csFilter);
1027
    return TRUE;
1028 1029
}

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
static gboolean activate_mode(GstPad *pad, GstObject *parent, GstPadMode mode, gboolean activate)
{
    TRACE("%p %p 0x%x %u\n", pad, parent, mode, activate);
    switch (mode) {
      case GST_PAD_MODE_PULL:
        return TRUE;
      case GST_PAD_MODE_PUSH:
        return activate_push(pad, activate);
      default:
        return FALSE;
    }
    return FALSE;
}

1044 1045
static void no_more_pads(GstElement *decodebin, gpointer user)
{
1046
    GSTImpl *This = (GSTImpl*)user;
1047
    TRACE("%p %p\n", This, decodebin);
1048 1049 1050
    SetEvent(This->event);
}

1051 1052
static GstAutoplugSelectResult autoplug_blacklist(GstElement *bin, GstPad *pad, GstCaps *caps, GstElementFactory *fact, gpointer user)
{
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    const char *name = gst_element_factory_get_longname(fact);

    if (strstr(name, "Player protection")) {
        WARN("Blacklisted a/52 decoder because it only works in Totem\n");
        return GST_AUTOPLUG_SELECT_SKIP;
    }
    if (!strcmp(name, "Fluendo Hardware Accelerated Video Decoder")) {
        WARN("Disabled video acceleration since it breaks in wine\n");
        return GST_AUTOPLUG_SELECT_SKIP;
    }
    TRACE("using \"%s\"\n", name);
    return GST_AUTOPLUG_SELECT_TRY;
}

1067 1068
static GstBusSyncReply watch_bus(GstBus *bus, GstMessage *msg, gpointer data)
{
1069 1070 1071
    GSTImpl *This = data;
    GError *err = NULL;
    gchar *dbg_info = NULL;
1072 1073 1074

    TRACE("%p %p %p\n", This, bus, msg);

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    if (GST_MESSAGE_TYPE(msg) & GST_MESSAGE_ERROR) {
        gst_message_parse_error(msg, &err, &dbg_info);
        FIXME("%s: %s\n", GST_OBJECT_NAME(msg->src), err->message);
        WARN("%s\n", dbg_info);
        SetEvent(This->event);
    } else if (GST_MESSAGE_TYPE(msg) & GST_MESSAGE_WARNING) {
        gst_message_parse_warning(msg, &err, &dbg_info);
        WARN("%s: %s\n", GST_OBJECT_NAME(msg->src), err->message);
        WARN("%s\n", dbg_info);
    }
1085 1086
    if (err)
        g_error_free(err);
1087 1088 1089 1090
    g_free(dbg_info);
    return GST_BUS_DROP;
}

1091 1092
static void unknown_type(GstElement *bin, GstPad *pad, GstCaps *caps, gpointer user)
{
1093 1094 1095 1096 1097
    gchar *strcaps = gst_caps_to_string(caps);
    FIXME("Could not find a filter for caps: %s\n", strcaps);
    g_free(strcaps);
}

1098 1099
static HRESULT GST_Connect(GSTInPin *pPin, IPin *pConnectPin, ALLOCATOR_PROPERTIES *props)
{
1100 1101 1102
    GSTImpl *This = (GSTImpl*)pPin->pin.pinInfo.pFilter;
    HRESULT hr;
    int ret, i;
1103
    LONGLONG avail, duration;
1104 1105 1106 1107 1108
    GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE(
        "quartz_src",
        GST_PAD_SRC,
        GST_PAD_ALWAYS,
        GST_STATIC_CAPS_ANY);
1109
    GstElement *gstfilter;
1110 1111

    TRACE("%p %p %p\n", pPin, pConnectPin, props);
1112

1113 1114 1115
    This->props = *props;
    IAsyncReader_Length(pPin->pReader, &This->filesize, &avail);

1116 1117
    if (!This->bus) {
        This->bus = gst_bus_new();
1118
        gst_bus_set_sync_handler(This->bus, watch_bus_wrapper, This, NULL);
1119 1120
    }

1121
    This->container = gst_bin_new(NULL);
1122
    gst_element_set_bus(This->container, This->bus);
1123

1124 1125
    gstfilter = gst_element_factory_make("decodebin", NULL);
    if (!gstfilter) {
1126 1127
        FIXME("Could not make source filter, are gstreamer-plugins-* installed for %u bits?\n",
              8 * (int)sizeof(void*));
1128 1129
        return E_FAIL;
    }
1130

1131
    gst_bin_add(GST_BIN(This->container), gstfilter);
1132

1133 1134 1135 1136
    g_signal_connect(gstfilter, "pad-added", G_CALLBACK(existing_new_pad_wrapper), This);
    g_signal_connect(gstfilter, "pad-removed", G_CALLBACK(removed_decoded_pad_wrapper), This);
    g_signal_connect(gstfilter, "autoplug-select", G_CALLBACK(autoplug_blacklist_wrapper), This);
    g_signal_connect(gstfilter, "unknown-type", G_CALLBACK(unknown_type_wrapper), This);
1137 1138

    This->my_src = gst_pad_new_from_static_template(&src_template, "quartz-src");
1139 1140
    gst_pad_set_getrange_function(This->my_src, request_buffer_src_wrapper);
    gst_pad_set_query_function(This->my_src, query_function_wrapper);
1141
    gst_pad_set_activatemode_function(This->my_src, activate_mode_wrapper);
1142
    gst_pad_set_event_function(This->my_src, event_src_wrapper);
1143
    gst_pad_set_element_private (This->my_src, This);
1144
    This->their_sink = gst_element_get_static_pad(gstfilter, "sink");
1145

1146
    g_signal_connect(gstfilter, "no-more-pads", G_CALLBACK(no_more_pads_wrapper), This);
1147 1148 1149 1150 1151
    ret = gst_pad_link(This->my_src, This->their_sink);
    if (ret < 0) {
        ERR("Returns: %i\n", ret);
        return E_FAIL;
    }
1152
    This->start = This->nextofs = This->nextpullofs = This->stop = 0;
1153 1154

    /* Add initial pins */
1155
    This->initial = This->discont = TRUE;
1156
    ResetEvent(This->event);
1157
    gst_element_set_state(This->container, GST_STATE_PLAYING);
1158
    WaitForSingleObject(This->event, -1);
1159
    gst_element_get_state(This->container, NULL, NULL, -1);
1160 1161 1162 1163 1164

    if (ret < 0) {
        WARN("Ret: %i\n", ret);
        hr = E_FAIL;
    } else if (!This->cStreams) {
1165
        FIXME("GStreamer could not find any streams\n");
1166 1167
        hr = E_FAIL;
    } else {
1168
        gst_pad_query_duration(This->ppPins[0]->their_src, GST_FORMAT_TIME, &duration);
1169 1170
        for (i = 0; i < This->cStreams; ++i) {
            This->ppPins[i]->seek.llDuration = This->ppPins[i]->seek.llStop = duration / 100;
1171
            This->ppPins[i]->seek.llCurrent = 0;
1172 1173
            if (!This->ppPins[i]->seek.llDuration)
                This->ppPins[i]->seek.dwCapabilities = 0;
1174
            WaitForSingleObject(This->ppPins[i]->caps_event, -1);
1175
        }
1176 1177 1178
        hr = S_OK;
    }
    *props = This->props;
1179 1180

    This->ignore_flush = TRUE;
1181 1182
    gst_element_set_state(This->container, GST_STATE_READY);
    gst_element_get_state(This->container, NULL, NULL, -1);
1183
    This->ignore_flush = FALSE;
1184

1185
    This->initial = FALSE;
1186 1187 1188 1189 1190

    /* don't set active during test-play, as we don't want to push/pull data
     * from the source yet */
    gst_pad_set_active(This->my_src, 1);

1191 1192 1193 1194
    This->nextofs = This->nextpullofs = 0;
    return hr;
}

1195 1196
static inline GSTOutPin *impl_from_IMediaSeeking( IMediaSeeking *iface )
{
1197
    return CONTAINING_RECORD(iface, GSTOutPin, seek.IMediaSeeking_iface);
1198 1199
}

1200 1201 1202
static IPin* WINAPI GST_GetPin(BaseFilter *iface, int pos)
{
    GSTImpl *This = (GSTImpl *)iface;
1203 1204
    IPin *pin;

1205
    TRACE("%p: Asking for pos %x\n", This, pos);
1206 1207 1208

    if (pos > This->cStreams || pos < 0)
        return NULL;
1209

1210
    if (!pos)
1211
        pin = &This->pInputPin.pin.IPin_iface;
1212
    else
1213 1214 1215 1216
        pin = &This->ppPins[pos - 1]->pin.pin.IPin_iface;

    IPin_AddRef(pin);
    return pin;
1217 1218 1219 1220 1221
}

static LONG WINAPI GST_GetPinCount(BaseFilter *iface)
{
    GSTImpl *This = (GSTImpl *)iface;
1222
    TRACE("%p -> %u\n", This, This->cStreams + 1);
1223 1224 1225 1226 1227 1228 1229 1230
    return (This->cStreams + 1);
}

static const BaseFilterFuncTable BaseFuncTable = {
    GST_GetPin,
    GST_GetPinCount
};

1231 1232
IUnknown * CALLBACK Gstreamer_Splitter_create(IUnknown *pUnkOuter, HRESULT *phr)
{
1233 1234 1235 1236
    IUnknown *obj = NULL;
    PIN_INFO *piInput;
    GSTImpl *This;

1237 1238
    TRACE("%p %p\n", pUnkOuter, phr);

1239 1240 1241 1242 1243 1244
    if (!Gstreamer_init())
    {
        *phr = E_FAIL;
        return NULL;
    }

1245 1246
    mark_wine_thread();

1247 1248 1249 1250 1251 1252 1253
    This = CoTaskMemAlloc(sizeof(*This));
    if (!This)
    {
        *phr = E_OUTOFMEMORY;
        return NULL;
    }

1254
    obj = (IUnknown*)&This->filter.IBaseFilter_iface;
1255 1256 1257 1258
    BaseFilter_Init(&This->filter, &GST_Vtbl, &CLSID_Gstreamer_Splitter, (DWORD_PTR)(__FILE__ ": GSTImpl.csFilter"), &BaseFuncTable);

    This->cStreams = 0;
    This->ppPins = NULL;
1259
    This->push_thread = NULL;
1260
    This->event = CreateEventW(NULL, 0, 0, NULL);
1261
    This->bus = NULL;
1262 1263 1264

    piInput = &This->pInputPin.pin.pinInfo;
    piInput->dir = PINDIR_INPUT;
1265
    piInput->pFilter = &This->filter.IBaseFilter_iface;
1266
    lstrcpynW(piInput->achName, wcsInputPinName, sizeof(piInput->achName) / sizeof(piInput->achName[0]));
1267
    This->pInputPin.pin.IPin_iface.lpVtbl = &GST_InputPin_Vtbl;
1268 1269 1270 1271 1272
    This->pInputPin.pin.refCount = 1;
    This->pInputPin.pin.pConnectedTo = NULL;
    This->pInputPin.pin.pCritSec = &This->filter.csFilter;
    ZeroMemory(&This->pInputPin.pin.mtCurrent, sizeof(AM_MEDIA_TYPE));
    *phr = S_OK;
1273 1274 1275

    TRACE("returning %p\n", obj);

1276 1277 1278
    return obj;
}

1279 1280
static void GST_Destroy(GSTImpl *This)
{
1281 1282
    IPin *connected = NULL;
    ULONG pinref;
1283
    HRESULT hr;
1284

1285
    TRACE("Destroying %p\n", This);
1286 1287 1288 1289 1290 1291

    CloseHandle(This->event);

    /* Don't need to clean up output pins, disconnecting input pin will do that */
    IPin_ConnectedTo((IPin *)&This->pInputPin, &connected);
    if (connected) {
1292 1293
        hr = IPin_Disconnect(connected);
        assert(hr == S_OK);
1294
        IPin_Release(connected);
1295
        hr = IPin_Disconnect(&This->pInputPin.pin.IPin_iface);
1296
        assert(hr == S_OK);
1297
    }
1298
    pinref = IPin_Release(&This->pInputPin.pin.IPin_iface);
1299 1300 1301 1302 1303 1304
    if (pinref) {
        /* Valgrind could find this, if I kill it here */
        ERR("pinref should be null, is %u, destroying anyway\n", pinref);
        assert((LONG)pinref > 0);

        while (pinref)
1305
            pinref = IPin_Release(&This->pInputPin.pin.IPin_iface);
1306
    }
1307
    if (This->bus) {
1308
        gst_bus_set_sync_handler(This->bus, NULL, NULL, NULL);
1309 1310
        gst_object_unref(This->bus);
    }
1311
    BaseFilter_Destroy(&This->filter);
1312 1313 1314
    CoTaskMemFree(This);
}

1315 1316
static HRESULT WINAPI GST_QueryInterface(IBaseFilter *iface, REFIID riid, LPVOID *ppv)
{
1317
    GSTImpl *This = (GSTImpl *)iface;
1318 1319

    TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
1320 1321 1322

    *ppv = NULL;

1323 1324 1325 1326 1327 1328 1329
    if (IsEqualIID(riid, &IID_IUnknown) ||
        IsEqualIID(riid, &IID_IPersist) ||
        IsEqualIID(riid, &IID_IMediaFilter) ||
        IsEqualIID(riid, &IID_IBaseFilter))
    {
        *ppv = &This->filter.IBaseFilter_iface;
    }
1330 1331 1332 1333 1334 1335

    if (*ppv) {
        IUnknown_AddRef((IUnknown *)(*ppv));
        return S_OK;
    }

1336 1337
    if (!IsEqualIID(riid, &IID_IPin) && !IsEqualIID(riid, &IID_IVideoWindow) &&
        !IsEqualIID(riid, &IID_IAMFilterMiscFlags))
1338 1339 1340 1341 1342
        FIXME("No interface for %s!\n", debugstr_guid(riid));

    return E_NOINTERFACE;
}

1343 1344
static ULONG WINAPI GST_Release(IBaseFilter *iface)
{
1345
    GSTImpl *This = (GSTImpl *)iface;
1346
    ULONG refCount = InterlockedDecrement(&This->filter.refCount);
1347 1348 1349 1350 1351 1352 1353 1354 1355

    TRACE("(%p)->() Release from %d\n", This, refCount + 1);

    if (!refCount)
        GST_Destroy(This);

    return refCount;
}

1356 1357
static HRESULT WINAPI GST_Stop(IBaseFilter *iface)
{
1358 1359
    GSTImpl *This = (GSTImpl *)iface;

1360
    TRACE("(%p)\n", This);
1361

1362 1363
    mark_wine_thread();

1364
    if (This->container) {
1365
        This->ignore_flush = TRUE;
1366 1367
        gst_element_set_state(This->container, GST_STATE_READY);
        gst_element_get_state(This->container, NULL, NULL, -1);
1368 1369
        This->ignore_flush = FALSE;
    }
1370 1371 1372
    return S_OK;
}

1373 1374
static HRESULT WINAPI GST_Pause(IBaseFilter *iface)
{
1375 1376 1377 1378
    HRESULT hr = S_OK;
    GSTImpl *This = (GSTImpl *)iface;
    GstState now;
    GstStateChangeReturn ret;
1379 1380

    TRACE("(%p)\n", This);
1381

1382
    if (!This->container)
1383 1384
        return VFW_E_NOT_CONNECTED;

1385 1386
    mark_wine_thread();

1387
    gst_element_get_state(This->container, &now, NULL, -1);
1388 1389 1390 1391 1392 1393
    if (now == GST_STATE_PAUSED)
        return S_OK;
    if (now != GST_STATE_PLAYING)
        hr = IBaseFilter_Run(iface, -1);
    if (FAILED(hr))
        return hr;
1394
    ret = gst_element_set_state(This->container, GST_STATE_PAUSED);
1395 1396 1397 1398 1399
    if (ret == GST_STATE_CHANGE_ASYNC)
        hr = S_FALSE;
    return hr;
}

1400 1401
static HRESULT WINAPI GST_Run(IBaseFilter *iface, REFERENCE_TIME tStart)
{
1402 1403 1404 1405 1406 1407
    HRESULT hr = S_OK;
    GSTImpl *This = (GSTImpl *)iface;
    ULONG i;
    GstState now;
    HRESULT hr_any = VFW_E_NOT_CONNECTED;

1408
    TRACE("(%p)->(%s)\n", This, wine_dbgstr_longlong(tStart));
1409

1410 1411
    mark_wine_thread();

1412
    if (!This->container)
1413 1414
        return VFW_E_NOT_CONNECTED;

1415 1416 1417 1418
    EnterCriticalSection(&This->filter.csFilter);
    This->filter.rtStreamStart = tStart;
    LeaveCriticalSection(&This->filter.csFilter);

1419
    gst_element_get_state(This->container, &now, NULL, -1);
1420 1421 1422 1423
    if (now == GST_STATE_PLAYING)
        return S_OK;
    if (now == GST_STATE_PAUSED) {
        GstStateChangeReturn ret;
1424
        ret = gst_element_set_state(This->container, GST_STATE_PLAYING);
1425 1426 1427 1428 1429 1430
        if (ret == GST_STATE_CHANGE_ASYNC)
            return S_FALSE;
        return S_OK;
    }

    EnterCriticalSection(&This->filter.csFilter);
1431
    gst_element_set_state(This->container, GST_STATE_PLAYING);
1432 1433 1434
    This->filter.rtStreamStart = tStart;

    for (i = 0; i < This->cStreams; i++) {
1435
        hr = BaseOutputPinImpl_Active(&This->ppPins[i]->pin);
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
        if (SUCCEEDED(hr)) {
            hr_any = hr;
        }
    }
    hr = hr_any;
    LeaveCriticalSection(&This->filter.csFilter);

    return hr;
}

1446 1447
static HRESULT WINAPI GST_GetState(IBaseFilter *iface, DWORD dwMilliSecsTimeout, FILTER_STATE *pState)
{
1448 1449 1450 1451 1452
    GSTImpl *This = (GSTImpl *)iface;
    HRESULT hr = S_OK;
    GstState now, pending;
    GstStateChangeReturn ret;

1453
    TRACE("(%p)->(%d, %p)\n", This, dwMilliSecsTimeout, pState);
1454

1455 1456
    mark_wine_thread();

1457
    if (!This->container) {
1458
        *pState = State_Stopped;
1459 1460 1461
        return S_OK;
    }

1462
    ret = gst_element_get_state(This->container, &now, &pending, dwMilliSecsTimeout == INFINITE ? -1 : dwMilliSecsTimeout * 1000);
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475

    if (ret == GST_STATE_CHANGE_ASYNC)
        hr = VFW_S_STATE_INTERMEDIATE;
    else
        pending = now;

    switch (pending) {
        case GST_STATE_PAUSED: *pState = State_Paused; return hr;
        case GST_STATE_PLAYING: *pState = State_Running; return hr;
        default: *pState = State_Stopped; return hr;
    }
}

1476 1477
static HRESULT WINAPI GST_FindPin(IBaseFilter *iface, LPCWSTR Id, IPin **ppPin)
{
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
    FIXME("(%p)->(%s,%p) stub\n", iface, debugstr_w(Id), ppPin);
    return E_NOTIMPL;
}

static const IBaseFilterVtbl GST_Vtbl = {
    GST_QueryInterface,
    BaseFilterImpl_AddRef,
    GST_Release,
    BaseFilterImpl_GetClassID,
    GST_Stop,
    GST_Pause,
    GST_Run,
    GST_GetState,
    BaseFilterImpl_SetSyncSource,
    BaseFilterImpl_GetSyncSource,
    BaseFilterImpl_EnumPins,
    GST_FindPin,
    BaseFilterImpl_QueryFilterInfo,
    BaseFilterImpl_JoinFilterGraph,
    BaseFilterImpl_QueryVendorInfo
};

1500 1501 1502 1503
static HRESULT WINAPI GST_ChangeCurrent(IMediaSeeking *iface)
{
    GSTOutPin *This = impl_from_IMediaSeeking(iface);
    TRACE("(%p)\n", This);
1504 1505 1506
    return S_OK;
}

1507 1508 1509 1510
static HRESULT WINAPI GST_ChangeStop(IMediaSeeking *iface)
{
    GSTOutPin *This = impl_from_IMediaSeeking(iface);
    TRACE("(%p)\n", This);
1511 1512 1513
    return S_OK;
}

1514 1515
static HRESULT WINAPI GST_ChangeRate(IMediaSeeking *iface)
{
1516 1517
    GSTOutPin *This = impl_from_IMediaSeeking(iface);
    GstEvent *ev = gst_event_new_seek(This->seek.dRate, GST_FORMAT_TIME, 0, GST_SEEK_TYPE_NONE, -1, GST_SEEK_TYPE_NONE, -1);
1518
    TRACE("(%p) New rate %g\n", This, This->seek.dRate);
1519
    mark_wine_thread();
1520
    gst_pad_push_event(This->my_sink, ev);
1521 1522 1523
    return S_OK;
}

1524 1525
static HRESULT WINAPI GST_Seeking_QueryInterface(IMediaSeeking *iface, REFIID riid, void **ppv)
{
1526
    GSTOutPin *This = impl_from_IMediaSeeking(iface);
1527
    return IPin_QueryInterface(&This->pin.pin.IPin_iface, riid, ppv);
1528 1529
}

1530 1531
static ULONG WINAPI GST_Seeking_AddRef(IMediaSeeking *iface)
{
1532
    GSTOutPin *This = impl_from_IMediaSeeking(iface);
1533
    return IPin_AddRef(&This->pin.pin.IPin_iface);
1534 1535
}

1536 1537
static ULONG WINAPI GST_Seeking_Release(IMediaSeeking *iface)
{
1538
    GSTOutPin *This = impl_from_IMediaSeeking(iface);
1539
    return IPin_Release(&This->pin.pin.IPin_iface);
1540 1541
}

1542 1543
static HRESULT WINAPI GST_Seeking_GetCurrentPosition(IMediaSeeking *iface, REFERENCE_TIME *pos)
{
1544 1545
    GSTOutPin *This = impl_from_IMediaSeeking(iface);

1546 1547
    TRACE("(%p)->(%p)\n", This, pos);

1548 1549 1550
    if (!pos)
        return E_POINTER;

1551 1552
    mark_wine_thread();

1553 1554 1555 1556 1557 1558 1559 1560 1561
    if (!This->their_src) {
        *pos = This->seek.llCurrent;
        TRACE("Cached value\n");
        if (This->seek.llDuration)
            return S_OK;
        else
            return E_NOTIMPL;
    }

1562
    if (!gst_pad_query_position(This->their_src, GST_FORMAT_TIME, pos)) {
1563 1564 1565 1566
        WARN("Could not query position\n");
        return E_NOTIMPL;
    }
    *pos /= 100;
1567
    This->seek.llCurrent = *pos;
1568 1569 1570
    return S_OK;
}

1571 1572
static GstSeekType type_from_flags(DWORD flags)
{
1573
    switch (flags & AM_SEEKING_PositioningBitsMask) {
1574 1575 1576 1577 1578 1579 1580
    case AM_SEEKING_NoPositioning:
        return GST_SEEK_TYPE_NONE;
    case AM_SEEKING_AbsolutePositioning:
    case AM_SEEKING_RelativePositioning:
        return GST_SEEK_TYPE_SET;
    case AM_SEEKING_IncrementalPositioning:
        return GST_SEEK_TYPE_END;
1581 1582 1583 1584
    }
    return GST_SEEK_TYPE_NONE;
}

1585 1586 1587 1588
static HRESULT WINAPI GST_Seeking_SetPositions(IMediaSeeking *iface,
        REFERENCE_TIME *pCur, DWORD curflags, REFERENCE_TIME *pStop,
        DWORD stopflags)
{
1589 1590 1591 1592 1593
    HRESULT hr;
    GSTOutPin *This = impl_from_IMediaSeeking(iface);
    GstSeekFlags f = 0;
    GstSeekType curtype, stoptype;
    GstEvent *e;
1594
    gint64 stop_pos = 0, curr_pos = 0;
1595

1596 1597
    TRACE("(%p)->(%p, 0x%x, %p, 0x%x)\n", This, pCur, curflags, pStop, stopflags);

1598 1599
    mark_wine_thread();

1600 1601 1602 1603 1604
    if (!This->seek.llDuration)
        return E_NOTIMPL;

    hr = SourceSeekingImpl_SetPositions(iface, pCur, curflags, pStop, stopflags);
    if (!This->their_src)
1605
        return hr;
1606

1607 1608
    curtype = type_from_flags(curflags);
    stoptype = type_from_flags(stopflags);
1609 1610 1611 1612 1613 1614 1615
    if (curflags & AM_SEEKING_SeekToKeyFrame)
        f |= GST_SEEK_FLAG_KEY_UNIT;
    if (curflags & AM_SEEKING_Segment)
        f |= GST_SEEK_FLAG_SEGMENT;
    if (!(curflags & AM_SEEKING_NoFlush))
        f |= GST_SEEK_FLAG_FLUSH;

1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    if (((curflags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_RelativePositioning) ||
        ((stopflags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_RelativePositioning)) {
        gint64 tmp_pos;
        gst_pad_query_position (This->my_sink, GST_FORMAT_TIME, &tmp_pos);
        if ((curflags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_RelativePositioning)
            curr_pos = tmp_pos;
        if ((stopflags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_RelativePositioning)
            stop_pos = tmp_pos;
    }

    e = gst_event_new_seek(This->seek.dRate, GST_FORMAT_TIME, f, curtype, pCur ? curr_pos + *pCur * 100 : -1, stoptype, pStop ? stop_pos + *pStop * 100 : -1);
1627 1628 1629 1630 1631 1632
    if (gst_pad_push_event(This->my_sink, e))
        return S_OK;
    else
        return E_NOTIMPL;
}

1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
static const IMediaSeekingVtbl GST_Seeking_Vtbl =
{
    GST_Seeking_QueryInterface,
    GST_Seeking_AddRef,
    GST_Seeking_Release,
    SourceSeekingImpl_GetCapabilities,
    SourceSeekingImpl_CheckCapabilities,
    SourceSeekingImpl_IsFormatSupported,
    SourceSeekingImpl_QueryPreferredFormat,
    SourceSeekingImpl_GetTimeFormat,
    SourceSeekingImpl_IsUsingTimeFormat,
    SourceSeekingImpl_SetTimeFormat,
    SourceSeekingImpl_GetDuration,
    SourceSeekingImpl_GetStopPosition,
1647
    GST_Seeking_GetCurrentPosition,
1648
    SourceSeekingImpl_ConvertTimeFormat,
1649
    GST_Seeking_SetPositions,
1650 1651 1652 1653 1654 1655 1656
    SourceSeekingImpl_GetPositions,
    SourceSeekingImpl_GetAvailable,
    SourceSeekingImpl_SetRate,
    SourceSeekingImpl_GetRate,
    SourceSeekingImpl_GetPreroll
};

1657 1658
static inline GSTOutPin *impl_from_IQualityControl( IQualityControl *iface )
{
1659
    return CONTAINING_RECORD(iface, GSTOutPin, IQualityControl_iface);
1660 1661
}

1662
static HRESULT WINAPI GST_QualityControl_QueryInterface(IQualityControl *iface, REFIID riid, void **ppv)
1663 1664
{
    GSTOutPin *pin = impl_from_IQualityControl(iface);
1665
    return IPin_QueryInterface(&pin->pin.pin.IPin_iface, riid, ppv);
1666 1667
}

1668
static ULONG WINAPI GST_QualityControl_AddRef(IQualityControl *iface)
1669 1670
{
    GSTOutPin *pin = impl_from_IQualityControl(iface);
1671
    return IPin_AddRef(&pin->pin.pin.IPin_iface);
1672 1673
}

1674
static ULONG WINAPI GST_QualityControl_Release(IQualityControl *iface)
1675 1676
{
    GSTOutPin *pin = impl_from_IQualityControl(iface);
1677
    return IPin_Release(&pin->pin.pin.IPin_iface);
1678 1679
}

1680 1681
static HRESULT WINAPI GST_QualityControl_Notify(IQualityControl *iface, IBaseFilter *sender, Quality qm)
{
1682
    GSTOutPin *pin = impl_from_IQualityControl(iface);
1683 1684
    GstEvent *evt;

1685 1686 1687 1688
    TRACE("(%p)->(%p, { 0x%x %u %s %s })\n", pin, sender,
            qm.Type, qm.Proportion,
            wine_dbgstr_longlong(qm.Late),
            wine_dbgstr_longlong(qm.TimeStamp));
1689

1690
    mark_wine_thread();
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704

    if (qm.Type == Flood)
        qm.Late = 0;

    evt = gst_event_new_qos(qm.Type == Famine ? GST_QOS_TYPE_UNDERFLOW : GST_QOS_TYPE_OVERFLOW,
            qm.Proportion / 1000., qm.Late * 100, qm.TimeStamp * 100);

    if (!evt) {
        WARN("Failed to create QOS event\n");
        return E_INVALIDARG;
    }

    gst_pad_push_event(pin->my_sink, evt);

1705 1706 1707
    return S_OK;
}

1708
static HRESULT WINAPI GST_QualityControl_SetSink(IQualityControl *iface, IQualityControl *tonotify)
1709
{
1710 1711
    GSTOutPin *pin = impl_from_IQualityControl(iface);
    TRACE("(%p)->(%p)\n", pin, pin);
1712 1713 1714 1715
    /* Do nothing */
    return S_OK;
}

1716
static const IQualityControlVtbl GSTOutPin_QualityControl_Vtbl = {
1717 1718 1719
    GST_QualityControl_QueryInterface,
    GST_QualityControl_AddRef,
    GST_QualityControl_Release,
1720
    GST_QualityControl_Notify,
1721
    GST_QualityControl_SetSink
1722 1723
};

1724 1725
static HRESULT WINAPI GSTOutPin_QueryInterface(IPin *iface, REFIID riid, void **ppv)
{
1726 1727
    GSTOutPin *This = (GSTOutPin *)iface;

1728
    TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
1729 1730 1731 1732 1733 1734 1735 1736

    *ppv = NULL;

    if (IsEqualIID(riid, &IID_IUnknown))
        *ppv = iface;
    else if (IsEqualIID(riid, &IID_IPin))
        *ppv = iface;
    else if (IsEqualIID(riid, &IID_IMediaSeeking))
1737
        *ppv = &This->seek;
1738
    else if (IsEqualIID(riid, &IID_IQualityControl))
1739
        *ppv = &This->IQualityControl_iface;
1740 1741 1742 1743 1744 1745 1746 1747 1748

    if (*ppv) {
        IUnknown_AddRef((IUnknown *)(*ppv));
        return S_OK;
    }
    FIXME("No interface for %s!\n", debugstr_guid(riid));
    return E_NOINTERFACE;
}

1749 1750
static ULONG WINAPI GSTOutPin_Release(IPin *iface)
{
1751 1752
    GSTOutPin *This = (GSTOutPin *)iface;
    ULONG refCount = InterlockedDecrement(&This->pin.pin.refCount);
1753 1754

    TRACE("(%p)->() Release from %d\n", This, refCount + 1);
1755

1756 1757
    mark_wine_thread();

1758
    if (!refCount) {
1759
        if (This->their_src) {
1760 1761 1762 1763 1764
            if (This->flipfilter) {
                gst_pad_unlink(This->their_src, This->flip_sink);
                gst_pad_unlink(This->flip_src, This->my_sink);
                gst_object_unref(This->flip_src);
                gst_object_unref(This->flip_sink);
1765 1766
                This->flipfilter = NULL;
                This->flip_src = This->flip_sink = NULL;
1767 1768
            } else
                gst_pad_unlink(This->their_src, This->my_sink);
1769 1770
            gst_object_unref(This->their_src);
        }
1771 1772 1773 1774
        gst_object_unref(This->my_sink);
        CloseHandle(This->caps_event);
        DeleteMediaType(This->pmt);
        FreeMediaType(&This->pin.pin.mtCurrent);
1775
        gst_segment_free(This->segment);
1776 1777
        if(This->gstpool)
            gst_object_unref(This->gstpool);
1778 1779
        if (This->pin.pAllocator)
            IMemAllocator_Release(This->pin.pAllocator);
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
        CoTaskMemFree(This);
        return 0;
    }
    return refCount;
}

static HRESULT WINAPI GSTOutPin_GetMediaType(BasePin *iface, int iPosition, AM_MEDIA_TYPE *pmt)
{
    GSTOutPin *This = (GSTOutPin *)iface;

1790 1791
    TRACE("(%p)->(%i, %p)\n", This, iPosition, pmt);

1792 1793
    if (iPosition < 0)
        return E_INVALIDARG;
1794

1795 1796
    if (iPosition > 0)
        return VFW_S_NO_MORE_ITEMS;
1797

1798
    CopyMediaType(pmt, This->pmt);
1799

1800 1801 1802 1803 1804
    return S_OK;
}

static HRESULT WINAPI GSTOutPin_DecideBufferSize(BaseOutputPin *iface, IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *ppropInputRequest)
{
1805 1806
    GSTOutPin *This = (GSTOutPin *)iface;
    TRACE("(%p)->(%p, %p)\n", This, pAlloc, ppropInputRequest);
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
    /* Unused */
    return S_OK;
}

static HRESULT WINAPI GSTOutPin_DecideAllocator(BaseOutputPin *iface, IMemInputPin *pPin, IMemAllocator **pAlloc)
{
    HRESULT hr;
    GSTOutPin *This = (GSTOutPin *)iface;
    GSTImpl *GSTfilter = (GSTImpl*)This->pin.pin.pinInfo.pFilter;

1817 1818
    TRACE("(%p)->(%p, %p)\n", This, pPin, pAlloc);

1819
    *pAlloc = NULL;
1820
    if (GSTfilter->pInputPin.pAlloc)
1821
    {
1822
        hr = IMemInputPin_NotifyAllocator(pPin, GSTfilter->pInputPin.pAlloc, FALSE);
1823 1824 1825 1826 1827 1828
        if (SUCCEEDED(hr))
        {
            *pAlloc = GSTfilter->pInputPin.pAlloc;
            IMemAllocator_AddRef(*pAlloc);
        }
    }
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
    else
        hr = VFW_E_NO_ALLOCATOR;

    return hr;
}

static HRESULT WINAPI GSTOutPin_BreakConnect(BaseOutputPin *This)
{
    HRESULT hr;

    TRACE("(%p)->()\n", This);

    EnterCriticalSection(This->pin.pCritSec);
    if (!This->pin.pConnectedTo || !This->pMemInputPin)
        hr = VFW_E_NOT_CONNECTED;
    else
    {
        hr = IPin_Disconnect(This->pin.pConnectedTo);
        IPin_Disconnect((IPin *)This);
    }
    LeaveCriticalSection(This->pin.pCritSec);

    return hr;
}

static const IPinVtbl GST_OutputPin_Vtbl = {
    GSTOutPin_QueryInterface,
    BasePinImpl_AddRef,
    GSTOutPin_Release,
    BaseOutputPinImpl_Connect,
    BaseOutputPinImpl_ReceiveConnection,
    BaseOutputPinImpl_Disconnect,
    BasePinImpl_ConnectedTo,
    BasePinImpl_ConnectionMediaType,
    BasePinImpl_QueryPinInfo,
    BasePinImpl_QueryDirection,
    BasePinImpl_QueryId,
    GST_OutPin_QueryAccept,
    BasePinImpl_EnumMediaTypes,
    BasePinImpl_QueryInternalConnections,
    BaseOutputPinImpl_EndOfStream,
    BaseOutputPinImpl_BeginFlush,
    BaseOutputPinImpl_EndFlush,
1872
    BasePinImpl_NewSegment
1873 1874 1875
};

static const BaseOutputPinFuncTable output_BaseOutputFuncTable = {
1876 1877 1878 1879 1880 1881
    {
        NULL,
        BaseOutputPinImpl_AttemptConnection,
        BasePinImpl_GetMediaTypeVersion,
        GSTOutPin_GetMediaType
    },
1882 1883 1884 1885 1886
    GSTOutPin_DecideBufferSize,
    GSTOutPin_DecideAllocator,
    GSTOutPin_BreakConnect
};

1887 1888
static HRESULT GST_AddPin(GSTImpl *This, const PIN_INFO *piOutput, const AM_MEDIA_TYPE *amt)
{
1889 1890 1891
    HRESULT hr;
    This->ppPins = CoTaskMemRealloc(This->ppPins, (This->cStreams + 1) * sizeof(IPin *));

1892
    hr = BaseOutputPin_Construct(&GST_OutputPin_Vtbl, sizeof(GSTOutPin), piOutput, &output_BaseOutputFuncTable, &This->filter.csFilter, (IPin**)(This->ppPins + This->cStreams));
1893 1894
    if (SUCCEEDED(hr)) {
        GSTOutPin *pin = This->ppPins[This->cStreams];
1895
        memset((char*)pin + sizeof(pin->pin), 0, sizeof(GSTOutPin) - sizeof(pin->pin));
1896 1897
        pin->pmt = CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
        CopyMediaType(pin->pmt, amt);
1898
        pin->pin.pin.pinInfo.pFilter = &This->filter.IBaseFilter_iface;
1899
        pin->caps_event = CreateEventW(NULL, 0, 0, NULL);
1900
        pin->segment = gst_segment_new();
1901
        This->cStreams++;
1902
        pin->IQualityControl_iface.lpVtbl = &GSTOutPin_QualityControl_Vtbl;
1903
        SourceSeeking_Init(&pin->seek, &GST_Seeking_Vtbl, GST_ChangeStop, GST_ChangeCurrent, GST_ChangeRate, &This->filter.csFilter);
1904
        BaseFilterImpl_IncrementPinVersion(&This->filter);
1905 1906 1907 1908 1909
    } else
        ERR("Failed with error %x\n", hr);
    return hr;
}

1910 1911
static HRESULT GST_RemoveOutputPins(GSTImpl *This)
{
1912 1913 1914
    HRESULT hr;
    ULONG i;
    GSTOutPin **ppOldPins = This->ppPins;
1915

1916
    TRACE("(%p)\n", This);
1917
    mark_wine_thread();
1918

1919
    if (!This->container)
1920
        return S_OK;
1921
    gst_element_set_state(This->container, GST_STATE_NULL);
1922
    gst_pad_unlink(This->my_src, This->their_sink);
1923
    gst_object_unref(This->my_src);
1924
    gst_object_unref(This->their_sink);
1925 1926 1927 1928 1929
    This->my_src = This->their_sink = NULL;

    for (i = 0; i < This->cStreams; i++) {
        hr = BaseOutputPinImpl_BreakConnect(&ppOldPins[i]->pin);
        TRACE("Disconnect: %08x\n", hr);
1930
        IPin_Release(&ppOldPins[i]->pin.pin.IPin_iface);
1931 1932 1933
    }
    This->cStreams = 0;
    This->ppPins = NULL;
1934
    gst_element_set_bus(This->container, NULL);
1935 1936
    gst_object_unref(This->container);
    This->container = NULL;
1937
    BaseFilterImpl_IncrementPinVersion(&This->filter);
1938 1939 1940 1941
    CoTaskMemFree(ppOldPins);
    return S_OK;
}

1942 1943
static ULONG WINAPI GSTInPin_Release(IPin *iface)
{
1944 1945 1946 1947 1948 1949 1950 1951 1952
    GSTInPin *This = (GSTInPin*)iface;
    ULONG refCount = InterlockedDecrement(&This->pin.refCount);

    TRACE("(%p)->() Release from %d\n", iface, refCount + 1);
    if (!refCount) {
        FreeMediaType(&This->pin.mtCurrent);
        if (This->pAlloc)
            IMemAllocator_Release(This->pAlloc);
        This->pAlloc = NULL;
1953 1954 1955
        if (This->pReader)
            IAsyncReader_Release(This->pReader);
        This->pReader = NULL;
1956
        This->pin.IPin_iface.lpVtbl = NULL;
1957 1958 1959 1960 1961
        return 0;
    } else
        return refCount;
}

1962 1963
static HRESULT WINAPI GSTInPin_ReceiveConnection(IPin *iface, IPin *pReceivePin, const AM_MEDIA_TYPE *pmt)
{
1964 1965 1966 1967 1968 1969 1970
    PIN_DIRECTION pindirReceive;
    HRESULT hr = S_OK;
    GSTInPin *This = (GSTInPin*)iface;

    TRACE("(%p/%p)->(%p, %p)\n", This, iface, pReceivePin, pmt);
    dump_AM_MEDIA_TYPE(pmt);

1971 1972
    mark_wine_thread();

1973 1974 1975
    EnterCriticalSection(This->pin.pCritSec);
    if (!This->pin.pConnectedTo) {
        ALLOCATOR_PROPERTIES props;
1976
        IMemAllocator *pAlloc = NULL;
1977

1978
        props.cBuffers = 8;
1979 1980 1981 1982
        props.cbBuffer = 16384;
        props.cbAlign = 1;
        props.cbPrefix = 0;

1983
        if (IPin_QueryAccept(iface, pmt) != S_OK)
1984
            hr = VFW_E_TYPE_NOT_ACCEPTED;
1985

1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
        if (SUCCEEDED(hr)) {
            IPin_QueryDirection(pReceivePin, &pindirReceive);
            if (pindirReceive != PINDIR_OUTPUT) {
                ERR("Can't connect from non-output pin\n");
                hr = VFW_E_INVALID_DIRECTION;
            }
        }

        This->pReader = NULL;
        This->pAlloc = NULL;
        if (SUCCEEDED(hr))
            hr = IPin_QueryInterface(pReceivePin, &IID_IAsyncReader, (LPVOID *)&This->pReader);
        if (SUCCEEDED(hr))
            hr = GST_Connect(This, pReceivePin, &props);
2000 2001 2002

        /* A certain IAsyncReader::RequestAllocator expects to be passed
           non-NULL preferred allocator */
2003
        if (SUCCEEDED(hr))
2004 2005 2006 2007 2008 2009 2010 2011 2012
            hr = CoCreateInstance(&CLSID_MemoryAllocator, NULL, CLSCTX_INPROC,
                                  &IID_IMemAllocator, (LPVOID *)&pAlloc);
        if (SUCCEEDED(hr)) {
            hr = IAsyncReader_RequestAllocator(This->pReader, pAlloc, &props, &This->pAlloc);
            if (FAILED(hr))
                WARN("Can't get an allocator, got %08x\n", hr);
        }
        if (pAlloc)
            IMemAllocator_Release(pAlloc);
2013 2014 2015 2016 2017
        if (SUCCEEDED(hr)) {
            CopyMediaType(&This->pin.mtCurrent, pmt);
            This->pin.pConnectedTo = pReceivePin;
            IPin_AddRef(pReceivePin);
            hr = IMemAllocator_Commit(This->pAlloc);
2018
            SetEvent(((GSTImpl*)This->pin.pinInfo.pFilter)->event);
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
        } else {
            GST_RemoveOutputPins((GSTImpl *)This->pin.pinInfo.pFilter);
            if (This->pReader)
                IAsyncReader_Release(This->pReader);
            This->pReader = NULL;
            if (This->pAlloc)
                IMemAllocator_Release(This->pAlloc);
            This->pAlloc = NULL;
        }
        TRACE("Size: %i\n", props.cbBuffer);
    } else
        hr = VFW_E_ALREADY_CONNECTED;
    LeaveCriticalSection(This->pin.pCritSec);
    return hr;
}

2035 2036
static HRESULT WINAPI GSTInPin_Disconnect(IPin *iface)
{
2037 2038 2039
    HRESULT hr;
    GSTInPin *This = (GSTInPin*)iface;
    FILTER_STATE state;
2040 2041

    TRACE("(%p)\n", This);
2042

2043 2044
    mark_wine_thread();

2045 2046 2047 2048 2049 2050 2051 2052
    hr = IBaseFilter_GetState(This->pin.pinInfo.pFilter, INFINITE, &state);
    EnterCriticalSection(This->pin.pCritSec);
    if (This->pin.pConnectedTo) {
        GSTImpl *Parser = (GSTImpl *)This->pin.pinInfo.pFilter;

        if (SUCCEEDED(hr) && state == State_Stopped) {
            IMemAllocator_Decommit(This->pAlloc);
            IPin_Disconnect(This->pin.pConnectedTo);
2053
            IPin_Release(This->pin.pConnectedTo);
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
            This->pin.pConnectedTo = NULL;
            hr = GST_RemoveOutputPins(Parser);
        } else
            hr = VFW_E_NOT_STOPPED;
    } else
        hr = S_FALSE;
    LeaveCriticalSection(This->pin.pCritSec);
    return hr;
}

2064 2065
static HRESULT WINAPI GSTInPin_QueryAccept(IPin *iface, const AM_MEDIA_TYPE *pmt)
{
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
    GSTInPin *This = (GSTInPin*)iface;

    TRACE("(%p)->(%p)\n", This, pmt);
    dump_AM_MEDIA_TYPE(pmt);

    if (IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream))
        return S_OK;
    return S_FALSE;
}

2076 2077
static HRESULT WINAPI GSTInPin_EndOfStream(IPin *iface)
{
2078 2079 2080 2081 2082 2083 2084
    GSTInPin *pin = (GSTInPin*)iface;
    GSTImpl *This = (GSTImpl*)pin->pin.pinInfo.pFilter;

    FIXME("Propagate message on %p\n", This);
    return S_OK;
}

2085 2086
static HRESULT WINAPI GSTInPin_BeginFlush(IPin *iface)
{
2087 2088 2089 2090 2091 2092 2093
    GSTInPin *pin = (GSTInPin*)iface;
    GSTImpl *This = (GSTImpl*)pin->pin.pinInfo.pFilter;

    FIXME("Propagate message on %p\n", This);
    return S_OK;
}

2094 2095
static HRESULT WINAPI GSTInPin_EndFlush(IPin *iface)
{
2096 2097 2098 2099 2100 2101 2102
    GSTInPin *pin = (GSTInPin*)iface;
    GSTImpl *This = (GSTImpl*)pin->pin.pinInfo.pFilter;

    FIXME("Propagate message on %p\n", This);
    return S_OK;
}

2103 2104
static HRESULT WINAPI GSTInPin_NewSegment(IPin *iface, REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
2105 2106 2107
    GSTInPin *pin = (GSTInPin*)iface;
    GSTImpl *This = (GSTImpl*)pin->pin.pinInfo.pFilter;

2108
    BasePinImpl_NewSegment(iface, tStart, tStop, dRate);
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
    FIXME("Propagate message on %p\n", This);
    return S_OK;
}

static HRESULT WINAPI GSTInPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
{
    GSTInPin *This = (GSTInPin*)iface;

    TRACE("(%p/%p)->(%s, %p)\n", This, iface, debugstr_guid(riid), ppv);

    *ppv = NULL;

    if (IsEqualIID(riid, &IID_IUnknown))
        *ppv = iface;
    else if (IsEqualIID(riid, &IID_IPin))
        *ppv = iface;
    else if (IsEqualIID(riid, &IID_IMediaSeeking))
    {
        return IBaseFilter_QueryInterface(This->pin.pinInfo.pFilter, &IID_IMediaSeeking, ppv);
    }

    if (*ppv)
    {
        IUnknown_AddRef((IUnknown *)(*ppv));
        return S_OK;
    }

    FIXME("No interface for %s!\n", debugstr_guid(riid));

    return E_NOINTERFACE;
}

2141 2142 2143 2144 2145 2146 2147 2148 2149
static HRESULT WINAPI GSTInPin_EnumMediaTypes(IPin *iface, IEnumMediaTypes **ppEnum)
{
    BasePin *This = (BasePin *)iface;

    TRACE("(%p/%p)->(%p)\n", This, iface, ppEnum);

    return EnumMediaTypes_Construct(This, BasePinImpl_GetMediaType, BasePinImpl_GetMediaTypeVersion, ppEnum);
}

2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
static const IPinVtbl GST_InputPin_Vtbl = {
    GSTInPin_QueryInterface,
    BasePinImpl_AddRef,
    GSTInPin_Release,
    BaseInputPinImpl_Connect,
    GSTInPin_ReceiveConnection,
    GSTInPin_Disconnect,
    BasePinImpl_ConnectedTo,
    BasePinImpl_ConnectionMediaType,
    BasePinImpl_QueryPinInfo,
    BasePinImpl_QueryDirection,
    BasePinImpl_QueryId,
    GSTInPin_QueryAccept,
2163
    GSTInPin_EnumMediaTypes,
2164 2165 2166 2167 2168 2169
    BasePinImpl_QueryInternalConnections,
    GSTInPin_EndOfStream,
    GSTInPin_BeginFlush,
    GSTInPin_EndFlush,
    GSTInPin_NewSegment
};
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191

pthread_mutex_t cb_list_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cb_list_cond = PTHREAD_COND_INITIALIZER;
struct list cb_list = LIST_INIT(cb_list);

void CALLBACK perform_cb(TP_CALLBACK_INSTANCE *instance, void *user)
{
    struct cb_data *cbdata = user;

    TRACE("got cb type: 0x%x\n", cbdata->type);

    switch(cbdata->type)
    {
    case WATCH_BUS:
        {
            struct watch_bus_data *data = &cbdata->u.watch_bus_data;
            cbdata->u.watch_bus_data.ret = watch_bus(data->bus, data->msg, data->user);
            break;
        }
    case EXISTING_NEW_PAD:
        {
            struct existing_new_pad_data *data = &cbdata->u.existing_new_pad_data;
2192
            existing_new_pad(data->bin, data->pad, data->user);
2193 2194 2195 2196 2197
            break;
        }
    case QUERY_FUNCTION:
        {
            struct query_function_data *data = &cbdata->u.query_function_data;
2198
            cbdata->u.query_function_data.ret = query_function(data->pad, data->parent, data->query);
2199 2200
            break;
        }
2201
    case ACTIVATE_MODE:
2202
        {
2203 2204
            struct activate_mode_data *data = &cbdata->u.activate_mode_data;
            cbdata->u.activate_mode_data.ret = activate_mode(data->pad, data->parent, data->mode, data->activate);
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
            break;
        }
    case NO_MORE_PADS:
        {
            struct no_more_pads_data *data = &cbdata->u.no_more_pads_data;
            no_more_pads(data->decodebin, data->user);
            break;
        }
    case REQUEST_BUFFER_SRC:
        {
            struct request_buffer_src_data *data = &cbdata->u.request_buffer_src_data;
2216
            cbdata->u.request_buffer_src_data.ret = request_buffer_src(data->pad, data->parent,
2217 2218 2219 2220 2221 2222
                    data->ofs, data->len, data->buf);
            break;
        }
    case EVENT_SRC:
        {
            struct event_src_data *data = &cbdata->u.event_src_data;
2223
            cbdata->u.event_src_data.ret = event_src(data->pad, data->parent, data->event);
2224 2225 2226 2227 2228
            break;
        }
    case EVENT_SINK:
        {
            struct event_sink_data *data = &cbdata->u.event_sink_data;
2229
            cbdata->u.event_sink_data.ret = event_sink(data->pad, data->parent, data->event);
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
            break;
        }
    case ACCEPT_CAPS_SINK:
        {
            struct accept_caps_sink_data *data = &cbdata->u.accept_caps_sink_data;
            cbdata->u.accept_caps_sink_data.ret = accept_caps_sink(data->pad, data->caps);
            break;
        }
    case SETCAPS_SINK:
        {
            struct setcaps_sink_data *data = &cbdata->u.setcaps_sink_data;
            cbdata->u.setcaps_sink_data.ret = setcaps_sink(data->pad, data->caps);
            break;
        }
    case GOT_DATA_SINK:
        {
            struct got_data_sink_data *data = &cbdata->u.got_data_sink_data;
2247
            cbdata->u.got_data_sink_data.ret = got_data_sink(data->pad, data->parent, data->buf);
2248 2249 2250 2251 2252
            break;
        }
    case GOT_DATA:
        {
            struct got_data_data *data = &cbdata->u.got_data_data;
2253
            cbdata->u.got_data_data.ret = got_data(data->pad, data->parent, data->buf);
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
            break;
        }
    case REMOVED_DECODED_PAD:
        {
            struct removed_decoded_pad_data *data = &cbdata->u.removed_decoded_pad_data;
            removed_decoded_pad(data->bin, data->pad, data->user);
            break;
        }
    case AUTOPLUG_BLACKLIST:
        {
            struct autoplug_blacklist_data *data = &cbdata->u.autoplug_blacklist_data;
            cbdata->u.autoplug_blacklist_data.ret = autoplug_blacklist(data->bin,
                    data->pad, data->caps, data->fact, data->user);
            break;
        }
    case UNKNOWN_TYPE:
        {
            struct unknown_type_data *data = &cbdata->u.unknown_type_data;
            unknown_type(data->bin, data->pad, data->caps, data->user);
            break;
        }
    case RELEASE_SAMPLE:
        {
            struct release_sample_data *data = &cbdata->u.release_sample_data;
            release_sample(data->data);
            break;
        }
    case TRANSFORM_PAD_ADDED:
        {
            struct transform_pad_added_data *data = &cbdata->u.transform_pad_added_data;
            Gstreamer_transform_pad_added(data->filter, data->pad, data->user);
            break;
        }
2287 2288 2289 2290 2291 2292 2293
    case QUERY_SINK:
        {
            struct query_sink_data *data = &cbdata->u.query_sink_data;
            cbdata->u.query_sink_data.ret = query_sink(data->pad, data->parent,
                    data->query);
            break;
        }
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
    }

    pthread_mutex_lock(&cbdata->lock);
    cbdata->finished = 1;
    pthread_cond_broadcast(&cbdata->cond);
    pthread_mutex_unlock(&cbdata->lock);
}

static DWORD WINAPI dispatch_thread(void *user)
{
    struct cb_data *cbdata;

    pthread_mutex_lock(&cb_list_lock);

    while(1){
        pthread_cond_wait(&cb_list_cond, &cb_list_lock);

        while(!list_empty(&cb_list)){
            cbdata = LIST_ENTRY(list_head(&cb_list), struct cb_data, entry);
            list_remove(&cbdata->entry);

            TrySubmitThreadpoolCallback(&perform_cb, cbdata, NULL);
        }
    }

    pthread_mutex_unlock(&cb_list_lock);

    return 0;
}

void start_dispatch_thread(void)
{
    pthread_key_create(&wine_gst_key, NULL);
    CloseHandle(CreateThread(NULL, 0, &dispatch_thread, NULL, 0, NULL));
}