richedit: Prevented underlining the end of paragraph character.
[wine] / dlls / quartz / avisplit.c
1 /*
2  * AVI Splitter Filter
3  *
4  * Copyright 2003 Robert Shearman
5  * Copyright 2004-2005 Christian Costa
6  * Copyright 2008 Maarten Lankhorst
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22 /* FIXME:
23  * - Reference leaks, if they are still existant
24  * - Files without an index are not handled correctly yet.
25  * - When stopping/starting, a sample is lost. This should be compensated by
26  *   keeping track of previous index/position.
27  * - Debugging channels are noisy at the moment, especially with thread
28  *   related messages, however this is the only correct thing to do right now,
29  *   since wine doesn't correctly handle all messages yet.
30  */
31
32 #include "quartz_private.h"
33 #include "control_private.h"
34 #include "pin.h"
35
36 #include "uuids.h"
37 #include "vfw.h"
38 #include "aviriff.h"
39 #include "vfwmsgs.h"
40 #include "amvideo.h"
41
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
44
45 #include <math.h>
46 #include <assert.h>
47
48 #include "parser.h"
49
50 #define TWOCCFromFOURCC(fcc) HIWORD(fcc)
51
52 /* four character codes used in AVI files */
53 #define ckidINFO       mmioFOURCC('I','N','F','O')
54 #define ckidREC        mmioFOURCC('R','E','C',' ')
55
56 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
57
58 typedef struct StreamData
59 {
60     DWORD dwSampleSize;
61     FLOAT fSamplesPerSec;
62     DWORD dwLength;
63
64     AVISTREAMHEADER streamheader;
65     DWORD entries;
66     AVISTDINDEX **stdindex;
67     DWORD frames;
68     DWORD seek;
69
70     /* Position, in index units */
71     DWORD pos, pos_next, index, index_next;
72
73     /* Packet handling: a thread is created and waits on the packet event handle
74      * On an event acquire the sample lock, addref the sample and set it to NULL,
75      * then queue a new packet.
76      */
77     HANDLE thread, packet_queued;
78     IMediaSample *sample;
79
80     /* Amount of preroll samples for this stream */
81     DWORD preroll;
82 } StreamData;
83
84 typedef struct AVISplitterImpl
85 {
86     ParserImpl Parser;
87     RIFFCHUNK CurrentChunk;
88     LONGLONG CurrentChunkOffset; /* in media time */
89     LONGLONG EndOfFile;
90     AVIMAINHEADER AviHeader;
91     AVIEXTHEADER ExtHeader;
92
93     AVIOLDINDEX *oldindex;
94     DWORD offset;
95
96     StreamData *streams;
97 } AVISplitterImpl;
98
99 struct thread_args {
100     AVISplitterImpl *This;
101     DWORD stream;
102 };
103
104 /* The threading stuff cries for an explanation
105  *
106  * PullPin starts processing and calls AVISplitter_first_request
107  * AVISplitter_first_request creates a thread for each stream
108  * A stream can be audio, video, subtitles or something undefined.
109  *
110  * AVISplitter_first_request loads a single packet to each but one stream,
111  * and queues it for that last stream. This is to prevent WaitForNext to time
112  * out badly.
113  *
114  * The processing loop is entered. It calls IAsyncReader_WaitForNext in the
115  * PullPin. Every time it receives a packet, it will call AVISplitter_Sample
116  * AVISplitter_Sample will signal the relevant thread that a new sample is
117  * arrived, when that thread is ready it will read the packet and transmits
118  * it downstream with AVISplitter_Receive
119  *
120  * Threads terminate upon receiving NULL as packet or when ANY error code
121  * != S_OK occurs. This means that any error is fatal to processing.
122  */
123
124 static HRESULT AVISplitter_SendEndOfFile(AVISplitterImpl *This, DWORD streamnumber)
125 {
126     IPin* ppin = NULL;
127     HRESULT hr;
128
129     TRACE("End of file reached\n");
130
131     hr = IPin_ConnectedTo(This->Parser.ppPins[streamnumber+1], &ppin);
132     if (SUCCEEDED(hr))
133     {
134         hr = IPin_EndOfStream(ppin);
135         IPin_Release(ppin);
136     }
137     TRACE("--> %x\n", hr);
138
139     /* Force the pullpin thread to stop */
140     return S_FALSE;
141 }
142
143 /* Thread worker horse */
144 static HRESULT AVISplitter_next_request(AVISplitterImpl *This, DWORD streamnumber)
145 {
146     StreamData *stream = This->streams + streamnumber;
147     PullPin *pin = This->Parser.pInputPin;
148     IMediaSample *sample = NULL;
149     HRESULT hr;
150     BOOL endofstream = FALSE;
151
152     TRACE("(%p, %u)->()\n", This, streamnumber);
153
154     hr = IMemAllocator_GetBuffer(pin->pAlloc, &sample, NULL, NULL, 0);
155     if (hr != S_OK)
156         ERR("... %08x?\n", hr);
157
158     if (SUCCEEDED(hr))
159     {
160         LONGLONG rtSampleStart;
161         /* Add 4 for the next header, which should hopefully work */
162         LONGLONG rtSampleStop;
163
164         stream->pos = stream->pos_next;
165         stream->index = stream->index_next;
166
167         IMediaSample_SetDiscontinuity(sample, stream->seek);
168         stream->seek = FALSE;
169         if (stream->preroll)
170         {
171             --stream->preroll;
172             IMediaSample_SetPreroll(sample, TRUE);
173         }
174         else
175             IMediaSample_SetPreroll(sample, FALSE);
176         IMediaSample_SetSyncPoint(sample, TRUE);
177
178         if (stream->stdindex)
179         {
180             AVISTDINDEX *index = stream->stdindex[stream->index];
181             AVISTDINDEX_ENTRY *entry = &index->aIndex[stream->pos];
182             BOOL keyframe;
183
184             rtSampleStart = index->qwBaseOffset;
185             keyframe = !(entry->dwSize >> 31);
186             rtSampleStart += entry->dwOffset;
187             rtSampleStart = MEDIATIME_FROM_BYTES(rtSampleStart);
188
189             ++stream->pos_next;
190             if (index->nEntriesInUse == stream->pos_next)
191             {
192                 stream->pos_next = 0;
193                 ++stream->index_next;
194             }
195
196             rtSampleStop = rtSampleStart + MEDIATIME_FROM_BYTES(entry->dwSize & ~(1 << 31));
197
198             TRACE("offset(%u) size(%u)\n", (DWORD)BYTES_FROM_MEDIATIME(rtSampleStart), (DWORD)BYTES_FROM_MEDIATIME(rtSampleStop - rtSampleStart));
199
200             /* End of file */
201             if (stream->index_next >= stream->entries)
202             {
203                 ERR("END OF STREAM ON %u\n", streamnumber);
204                 hr = AVISplitter_SendEndOfFile(This, streamnumber);
205                 return S_FALSE;
206             }
207         }
208         else if (This->oldindex)
209         {
210             DWORD flags = This->oldindex->aIndex[stream->pos].dwFlags;
211             DWORD size = This->oldindex->aIndex[stream->pos].dwSize;
212             BOOL keyframe;
213             keyframe = !!(flags & AVIIF_KEYFRAME);
214
215             rtSampleStart = MEDIATIME_FROM_BYTES(This->offset);
216             rtSampleStart += MEDIATIME_FROM_BYTES(This->oldindex->aIndex[stream->pos].dwOffset);
217             rtSampleStop = rtSampleStart + MEDIATIME_FROM_BYTES(size);
218             if (flags & AVIIF_MIDPART)
219             {
220                 FIXME("Only stand alone frames are currently handled correctly!\n");
221             }
222             if (flags & AVIIF_LIST)
223             {
224                 FIXME("Not sure if this is handled correctly\n");
225                 rtSampleStart += MEDIATIME_FROM_BYTES(sizeof(RIFFLIST));
226                 rtSampleStop += MEDIATIME_FROM_BYTES(sizeof(RIFFLIST));
227             }
228             else
229             {
230                 rtSampleStart += MEDIATIME_FROM_BYTES(sizeof(RIFFCHUNK));
231                 rtSampleStop += MEDIATIME_FROM_BYTES(sizeof(RIFFCHUNK));
232             }
233
234             /* Slow way of finding next index */
235             do {
236                 stream->pos_next++;
237             } while (stream->pos_next * sizeof(This->oldindex->aIndex[0]) < This->oldindex->cb
238                      && StreamFromFOURCC(This->oldindex->aIndex[stream->pos_next].dwChunkId) != streamnumber);
239
240             /* End of file */
241             if (stream->pos_next * sizeof(This->oldindex->aIndex[0]) >= This->oldindex->cb)
242             {
243                 stream->pos_next = 0;
244                 ++stream->index_next;
245                 ERR("END OF STREAM ON %u\n", streamnumber);
246                 hr = AVISplitter_SendEndOfFile(This, streamnumber);
247                 endofstream = TRUE;
248             }
249         }
250         else /* TODO: Generate an index automagically */
251         {
252             ERR("CAN'T PLAY WITHOUT AN INDEX! SOS! SOS! SOS!\n");
253             assert(0);
254         }
255
256         hr = IMediaSample_SetTime(sample, &rtSampleStart, &rtSampleStop);
257
258         hr = IAsyncReader_Request(pin->pReader, sample, streamnumber);
259
260         if (FAILED(hr))
261             assert(IMediaSample_Release(sample) == 0);
262     }
263     else
264     {
265         if (sample)
266         {
267             ERR("There should be no sample!\n");
268             assert(IMediaSample_Release(sample) == 0);
269         }
270     }
271     TRACE("--> %08x\n", hr);
272
273     if (endofstream && hr == S_OK)
274         return S_FALSE;
275
276     return hr;
277 }
278
279 static HRESULT AVISplitter_Receive(AVISplitterImpl *This, IMediaSample *sample, DWORD streamnumber)
280 {
281     Parser_OutputPin *pin = (Parser_OutputPin *)This->Parser.ppPins[1+streamnumber];
282     HRESULT hr;
283     LONGLONG start, stop;
284     StreamData *stream = &This->streams[streamnumber];
285
286     start = pin->dwSamplesProcessed;
287     start *= stream->streamheader.dwScale;
288     start *= 10000000;
289     start /= stream->streamheader.dwRate;
290
291     if (stream->streamheader.dwSampleSize)
292     {
293         ULONG len = IMediaSample_GetActualDataLength(sample);
294         ULONG size = stream->streamheader.dwSampleSize;
295
296         pin->dwSamplesProcessed += len / size;
297     }
298     else
299         ++pin->dwSamplesProcessed;
300
301     stop = pin->dwSamplesProcessed;
302     stop *= stream->streamheader.dwScale;
303     stop *= 10000000;
304     stop /= stream->streamheader.dwRate;
305
306     IMediaSample_SetTime(sample, &start, &stop);
307
308     hr = OutputPin_SendSample(&pin->pin, sample);
309
310 /* Uncomment this if you want to debug the time differences between the
311  * different streams, it is useful for that
312  *
313     FIXME("stream %u, hr: %08x, Start: %u.%03u, Stop: %u.%03u\n", streamnumber, hr,
314            (DWORD)(start / 10000000), (DWORD)((start / 10000)%1000),
315            (DWORD)(stop / 10000000), (DWORD)((stop / 10000)%1000));
316 */
317     return hr;
318 }
319
320 static DWORD WINAPI AVISplitter_thread_reader(LPVOID data)
321 {
322     struct thread_args *args = data;
323     AVISplitterImpl *This = args->This;
324     DWORD streamnumber = args->stream;
325     HRESULT hr = S_OK;
326
327     do
328     {
329         HRESULT nexthr = S_FALSE;
330         IMediaSample *sample;
331
332         WaitForSingleObject(This->streams[streamnumber].packet_queued, INFINITE);
333         sample = This->streams[streamnumber].sample;
334         This->streams[streamnumber].sample = NULL;
335         if (!sample)
336             break;
337
338         nexthr = AVISplitter_next_request(This, streamnumber);
339
340         hr = AVISplitter_Receive(This, sample, streamnumber);
341         if (hr != S_OK)
342             FIXME("Receiving error: %08x\n", hr);
343
344         IMediaSample_Release(sample);
345         if (hr == S_OK)
346             hr = nexthr;
347     } while (hr == S_OK);
348
349     FIXME("Thread %u terminated with hr %08x!\n", streamnumber, hr);
350
351     return hr;
352 }
353
354 static HRESULT AVISplitter_Sample(LPVOID iface, IMediaSample * pSample, DWORD_PTR cookie)
355 {
356     AVISplitterImpl *This = iface;
357     StreamData *stream = This->streams + cookie;
358     HRESULT hr = S_OK;
359
360     if (!IMediaSample_GetActualDataLength(pSample))
361         return S_OK;
362
363     /* Send the sample to whatever thread is appropiate
364      * That thread should also not have a sample queued at the moment
365      */
366     /* Debugging */
367     TRACE("(%p)->(%p size: %u, %lu)\n", This, pSample, IMediaSample_GetActualDataLength(pSample), cookie);
368     assert(cookie < This->Parser.cStreams);
369     assert(!stream->sample);
370     assert(WaitForSingleObject(stream->packet_queued, 0) == WAIT_TIMEOUT);
371
372     IMediaSample_AddRef(pSample);
373
374     stream->sample = pSample;
375     SetEvent(stream->packet_queued);
376
377     return hr;
378 }
379
380 /* On the first request we have to be sure that (cStreams-1) samples have
381  * already been processed, because otherwise some pins might not ever finish
382  * a Pause state change
383  */
384 static HRESULT AVISplitter_first_request(LPVOID iface)
385 {
386     AVISplitterImpl *This = (AVISplitterImpl *)iface;
387     HRESULT hr = S_OK;
388     int x;
389     IMediaSample *sample = NULL;
390     BOOL have_sample = FALSE;
391
392     TRACE("(%p)->()\n", This);
393
394     for (x = 0; x < This->Parser.cStreams; ++x)
395     {
396         StreamData *stream = This->streams + x;
397
398         /* Nothing should be running at this point */
399         assert(!stream->thread);
400
401         assert(!sample);
402         /* It could be we asked the thread to terminate, and the thread
403          * already terminated before receiving the deathwish */
404         ResetEvent(stream->packet_queued);
405
406         stream->pos_next = stream->pos;
407         stream->index_next = stream->index;
408
409         /* There should be a a packet queued from AVISplitter_next_request last time
410          * It needs to be done now because this is the only way to ensure that every
411          * stream will have at least 1 packet processed
412          * If this is done after the threads start it could go all awkward and we
413          * would have no guarantees that it's successful at all
414          */
415
416         if (have_sample)
417         {
418             DWORD_PTR dwUser = ~0;
419             hr = IAsyncReader_WaitForNext(This->Parser.pInputPin->pReader, 10000, &sample, &dwUser);
420             assert(hr == S_OK);
421             assert(sample);
422
423             /* This should not happen! (Maybe the threads didn't terminate?) */
424             if (dwUser != x - 1)
425             {
426                 ERR("dwUser: %lu, x-1: %u\n", dwUser, x-1);
427                 assert(dwUser == x - 1);
428             }
429             AVISplitter_Sample(iface, sample, dwUser);
430             IMediaSample_Release(sample);
431         }
432
433         hr = AVISplitter_next_request(This, x);
434         TRACE("-->%08x\n", hr);
435         /* assert(SUCCEEDED(hr)); * With quick transitions this might not be the case (eg stop->running->stop) */
436
437         /* Could be an EOF instead */
438         have_sample = (hr == S_OK);
439     }
440
441     /* FIXME: Don't do this for each pin that sent an EOF */
442     for (x = 0; x < This->Parser.cStreams; ++x)
443     {
444         struct thread_args *args;
445         DWORD tid;
446
447         if ((This->streams[x].stdindex && This->streams[x].index_next >= This->streams[x].entries) ||
448             (!This->streams[x].stdindex && This->streams[x].index_next))
449         {
450             This->streams[x].thread = NULL;
451             continue;
452         }
453
454         args = CoTaskMemAlloc(sizeof(*args));
455         args->This = This;
456         args->stream = x;
457         This->streams[x].thread = CreateThread(NULL, 0, AVISplitter_thread_reader, args, 0, &tid);
458         FIXME("Created stream %u thread 0x%08x\n", x, tid);
459     }
460
461     if (FAILED(hr))
462         ERR("Horsemen of the apocalypse came to bring error 0x%08x\n", hr);
463
464     return hr;
465 }
466
467 static HRESULT AVISplitter_done_process(LPVOID iface)
468 {
469     AVISplitterImpl *This = iface;
470
471     DWORD x;
472
473     for (x = 0; x < This->Parser.cStreams; ++x)
474     {
475         StreamData *stream = This->streams + x;
476
477         FIXME("Waiting for %u to terminate\n", x);
478         /* Make the thread return first */
479         SetEvent(stream->packet_queued);
480         assert(WaitForSingleObject(stream->thread, 100000) != WAIT_TIMEOUT);
481         CloseHandle(stream->thread);
482         stream->thread = NULL;
483
484         if (stream->sample)
485             assert(IMediaSample_Release(stream->sample) == 0);
486         stream->sample = NULL;
487
488         ResetEvent(stream->packet_queued);
489     }
490
491     return S_OK;
492 }
493
494 static HRESULT AVISplitter_QueryAccept(LPVOID iface, const AM_MEDIA_TYPE * pmt)
495 {
496     if (IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream) && IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_Avi))
497         return S_OK;
498     return S_FALSE;
499 }
500
501 static HRESULT AVISplitter_ProcessIndex(AVISplitterImpl *This, AVISTDINDEX **index, LONGLONG qwOffset, DWORD cb)
502 {
503     AVISTDINDEX *pIndex;
504     int x;
505     long rest;
506
507     *index = NULL;
508     if (cb < sizeof(AVISTDINDEX))
509     {
510         FIXME("size %u too small\n", cb);
511         return E_INVALIDARG;
512     }
513
514     pIndex = CoTaskMemAlloc(cb);
515     if (!pIndex)
516         return E_OUTOFMEMORY;
517
518     IAsyncReader_SyncRead(((PullPin *)This->Parser.ppPins[0])->pReader, qwOffset, cb, (BYTE *)pIndex);
519     pIndex = CoTaskMemRealloc(pIndex, pIndex->cb);
520     if (!pIndex)
521         return E_OUTOFMEMORY;
522
523     IAsyncReader_SyncRead(((PullPin *)This->Parser.ppPins[0])->pReader, qwOffset, pIndex->cb, (BYTE *)pIndex);
524     rest = pIndex->cb - sizeof(AVISUPERINDEX) + sizeof(RIFFCHUNK) + sizeof(pIndex->aIndex[0]) * ANYSIZE_ARRAY;
525
526     TRACE("FOURCC: %s\n", debugstr_an((char *)&pIndex->fcc, 4));
527     TRACE("wLongsPerEntry: %hd\n", pIndex->wLongsPerEntry);
528     TRACE("bIndexSubType: %hd\n", pIndex->bIndexSubType);
529     TRACE("bIndexType: %hd\n", pIndex->bIndexType);
530     TRACE("nEntriesInUse: %u\n", pIndex->nEntriesInUse);
531     TRACE("dwChunkId: %.4s\n", (char *)&pIndex->dwChunkId);
532     TRACE("qwBaseOffset: %x%08x\n", (DWORD)(pIndex->qwBaseOffset >> 32), (DWORD)pIndex->qwBaseOffset);
533     TRACE("dwReserved_3: %u\n", pIndex->dwReserved_3);
534
535     if (pIndex->bIndexType != AVI_INDEX_OF_CHUNKS
536         || pIndex->wLongsPerEntry != 2
537         || rest < (pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry)
538         || (pIndex->bIndexSubType != AVI_INDEX_SUB_DEFAULT))
539     {
540         FIXME("Invalid index chunk encountered\n");
541         return E_INVALIDARG;
542     }
543
544     for (x = 0; x < pIndex->nEntriesInUse; ++x)
545     {
546         BOOL keyframe = !(pIndex->aIndex[x].dwSize >> 31);
547         DWORDLONG offset = pIndex->qwBaseOffset + pIndex->aIndex[x].dwOffset;
548         TRACE("dwOffset: %x%08x\n", (DWORD)(offset >> 32), (DWORD)offset);
549         TRACE("dwSize: %u\n", (pIndex->aIndex[x].dwSize & ~(1<<31)));
550         TRACE("Frame is a keyframe: %s\n", keyframe ? "yes" : "no");
551     }
552
553     *index = pIndex;
554     return S_OK;
555 }
556
557 static HRESULT AVISplitter_ProcessOldIndex(AVISplitterImpl *This)
558 {
559     ULONGLONG mov_pos = BYTES_FROM_MEDIATIME(This->CurrentChunkOffset) - sizeof(DWORD);
560     AVIOLDINDEX *pAviOldIndex = This->oldindex;
561     int relative = -1;
562     int x;
563
564     for (x = 0; x < pAviOldIndex->cb / sizeof(pAviOldIndex->aIndex[0]); ++x)
565     {
566         DWORD temp, temp2 = 0, offset, chunkid;
567         PullPin *pin = This->Parser.pInputPin;
568
569         offset = pAviOldIndex->aIndex[x].dwOffset;
570         chunkid = pAviOldIndex->aIndex[x].dwChunkId;
571
572         TRACE("dwChunkId: %.4s\n", (char *)&chunkid);
573         TRACE("dwFlags: %08x\n", pAviOldIndex->aIndex[x].dwFlags);
574         TRACE("dwOffset (%s): %08x\n", relative ? "relative" : "absolute", offset);
575         TRACE("dwSize: %08x\n", pAviOldIndex->aIndex[x].dwSize);
576
577         /* Only scan once, or else this will take too long */
578         if (relative == -1)
579         {
580             IAsyncReader_SyncRead(pin->pReader, offset, sizeof(DWORD), (BYTE *)&temp);
581             relative = (chunkid != temp);
582
583             if (chunkid == mmioFOURCC('7','F','x','x')
584                 && ((char *)&temp)[0] == 'i' && ((char *)&temp)[1] == 'x')
585                 relative = FALSE;
586
587             if (relative)
588             {
589                 if (offset + mov_pos < BYTES_FROM_MEDIATIME(This->EndOfFile))
590                     IAsyncReader_SyncRead(pin->pReader, offset + mov_pos, sizeof(DWORD), (BYTE *)&temp2);
591
592                 if (chunkid == mmioFOURCC('7','F','x','x')
593                     && ((char *)&temp2)[0] == 'i' && ((char *)&temp2)[1] == 'x')
594                 {
595                     /* Do nothing, all is great */
596                 }
597                 else if (temp2 != chunkid)
598                 {
599                     ERR("Faulty index or bug in handling: Wanted FCC: %s, Abs FCC: %s (@ %x), Rel FCC: %s (@ %.0x%08x)\n",
600                         debugstr_an((char *)&chunkid, 4), debugstr_an((char *)&temp, 4), offset,
601                         debugstr_an((char *)&temp2, 4), (DWORD)((mov_pos + offset) >> 32), (DWORD)(mov_pos + offset));
602                     relative = -1;
603                 }
604                 else
605                     TRACE("Scanned dwChunkId: %s\n", debugstr_an((char *)&temp2, 4));
606             }
607             else if (!relative)
608                 TRACE("Scanned dwChunkId: %s\n", debugstr_an((char *)&temp, 4));
609         }
610         /* Only dump one packet */
611         else break;
612     }
613
614     if (relative == -1)
615     {
616         FIXME("Dropping index: no idea whether it is relative or absolute\n");
617         CoTaskMemFree(This->oldindex);
618         This->oldindex = NULL;
619     }
620     else if (!relative)
621         This->offset = 0;
622     else
623         This->offset = (DWORD)mov_pos;
624
625     return S_OK;
626 }
627
628 static HRESULT AVISplitter_ProcessStreamList(AVISplitterImpl * This, const BYTE * pData, DWORD cb, ALLOCATOR_PROPERTIES *props)
629 {
630     PIN_INFO piOutput;
631     const RIFFCHUNK * pChunk;
632     HRESULT hr;
633     AM_MEDIA_TYPE amt;
634     float fSamplesPerSec = 0.0f;
635     DWORD dwSampleSize = 0;
636     DWORD dwLength = 0;
637     DWORD nstdindex = 0;
638     static const WCHAR wszStreamTemplate[] = {'S','t','r','e','a','m',' ','%','0','2','d',0};
639     StreamData *stream;
640
641     ZeroMemory(&amt, sizeof(amt));
642     piOutput.dir = PINDIR_OUTPUT;
643     piOutput.pFilter = (IBaseFilter *)This;
644     wsprintfW(piOutput.achName, wszStreamTemplate, This->Parser.cStreams);
645     This->streams = CoTaskMemRealloc(This->streams, sizeof(StreamData) * (This->Parser.cStreams+1));
646     stream = This->streams + This->Parser.cStreams;
647     ZeroMemory(stream, sizeof(*stream));
648
649     for (pChunk = (const RIFFCHUNK *)pData; 
650          ((const BYTE *)pChunk >= pData) && ((const BYTE *)pChunk + sizeof(RIFFCHUNK) < pData + cb) && (pChunk->cb > 0); 
651          pChunk = (const RIFFCHUNK *)((const BYTE*)pChunk + sizeof(RIFFCHUNK) + pChunk->cb)     
652         )
653     {
654         switch (pChunk->fcc)
655         {
656         case ckidSTREAMHEADER:
657             {
658                 const AVISTREAMHEADER * pStrHdr = (const AVISTREAMHEADER *)pChunk;
659                 TRACE("processing stream header\n");
660                 stream->streamheader = *pStrHdr;
661
662                 fSamplesPerSec = (float)pStrHdr->dwRate / (float)pStrHdr->dwScale;
663                 CoTaskMemFree(amt.pbFormat);
664                 amt.pbFormat = NULL;
665                 amt.cbFormat = 0;
666
667                 switch (pStrHdr->fccType)
668                 {
669                 case streamtypeVIDEO:
670                     amt.formattype = FORMAT_VideoInfo;
671                     break;
672                 case streamtypeAUDIO:
673                     amt.formattype = FORMAT_WaveFormatEx;
674                     break;
675                 default:
676                     FIXME("fccType %.4s not handled yet\n", (char *)&pStrHdr->fccType);
677                     amt.formattype = FORMAT_None;
678                 }
679                 amt.majortype = MEDIATYPE_Video;
680                 amt.majortype.Data1 = pStrHdr->fccType;
681                 amt.subtype = MEDIATYPE_Video;
682                 amt.subtype.Data1 = pStrHdr->fccHandler;
683                 TRACE("Subtype FCC: %.04s\n", (LPCSTR)&pStrHdr->fccHandler);
684                 amt.lSampleSize = pStrHdr->dwSampleSize;
685                 amt.bFixedSizeSamples = (amt.lSampleSize != 0);
686
687                 /* FIXME: Is this right? */
688                 if (!amt.lSampleSize)
689                 {
690                     amt.lSampleSize = 1;
691                     dwSampleSize = 1;
692                 }
693
694                 amt.bTemporalCompression = IsEqualGUID(&amt.majortype, &MEDIATYPE_Video); /* FIXME? */
695                 dwSampleSize = pStrHdr->dwSampleSize;
696                 dwLength = pStrHdr->dwLength;
697                 if (!dwLength)
698                     dwLength = This->AviHeader.dwTotalFrames;
699
700                 if (pStrHdr->dwSuggestedBufferSize && pStrHdr->dwSuggestedBufferSize > props->cbBuffer)
701                     props->cbBuffer = pStrHdr->dwSuggestedBufferSize;
702
703                 break;
704             }
705         case ckidSTREAMFORMAT:
706             TRACE("processing stream format data\n");
707             if (IsEqualIID(&amt.formattype, &FORMAT_VideoInfo))
708             {
709                 VIDEOINFOHEADER * pvi;
710                 /* biCompression member appears to override the value in the stream header.
711                  * i.e. the stream header can say something completely contradictory to what
712                  * is in the BITMAPINFOHEADER! */
713                 if (pChunk->cb < sizeof(BITMAPINFOHEADER))
714                 {
715                     ERR("Not enough bytes for BITMAPINFOHEADER\n");
716                     return E_FAIL;
717                 }
718                 amt.cbFormat = sizeof(VIDEOINFOHEADER) - sizeof(BITMAPINFOHEADER) + pChunk->cb;
719                 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
720                 ZeroMemory(amt.pbFormat, amt.cbFormat);
721                 pvi = (VIDEOINFOHEADER *)amt.pbFormat;
722                 pvi->AvgTimePerFrame = (LONGLONG)(10000000.0 / fSamplesPerSec);
723
724                 CopyMemory(&pvi->bmiHeader, (const BYTE *)(pChunk + 1), pChunk->cb);
725                 if (pvi->bmiHeader.biCompression)
726                     amt.subtype.Data1 = pvi->bmiHeader.biCompression;
727             }
728             else
729             {
730                 amt.cbFormat = pChunk->cb;
731                 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
732                 CopyMemory(amt.pbFormat, (const BYTE *)(pChunk + 1), amt.cbFormat);
733             }
734             break;
735         case ckidSTREAMNAME:
736             TRACE("processing stream name\n");
737             /* FIXME: this doesn't exactly match native version (we omit the "##)" prefix), but hey... */
738             MultiByteToWideChar(CP_ACP, 0, (LPCSTR)(pChunk + 1), pChunk->cb, piOutput.achName, sizeof(piOutput.achName) / sizeof(piOutput.achName[0]));
739             break;
740         case ckidSTREAMHANDLERDATA:
741             FIXME("process stream handler data\n");
742             break;
743         case ckidAVIPADDING:
744             TRACE("JUNK chunk ignored\n");
745             break;
746         case ckidAVISUPERINDEX:
747         {
748             const AVISUPERINDEX *pIndex = (const AVISUPERINDEX *)pChunk;
749             int x;
750             long rest = pIndex->cb - sizeof(AVISUPERINDEX) + sizeof(RIFFCHUNK) + sizeof(pIndex->aIndex[0]) * ANYSIZE_ARRAY;
751
752             if (pIndex->cb < sizeof(AVISUPERINDEX) - sizeof(RIFFCHUNK))
753             {
754                 FIXME("size %u\n", pIndex->cb);
755                 break;
756             }
757
758             if (nstdindex++ > 0)
759             {
760                 ERR("Stream %d got more than 1 superindex?\n", This->Parser.cStreams);
761                 break;
762             }
763
764             TRACE("wLongsPerEntry: %hd\n", pIndex->wLongsPerEntry);
765             TRACE("bIndexSubType: %hd\n", pIndex->bIndexSubType);
766             TRACE("bIndexType: %hd\n", pIndex->bIndexType);
767             TRACE("nEntriesInUse: %u\n", pIndex->nEntriesInUse);
768             TRACE("dwChunkId: %.4s\n", (char *)&pIndex->dwChunkId);
769             if (pIndex->dwReserved[0])
770                 TRACE("dwReserved[0]: %u\n", pIndex->dwReserved[0]);
771             if (pIndex->dwReserved[2])
772                 TRACE("dwReserved[1]: %u\n", pIndex->dwReserved[1]);
773             if (pIndex->dwReserved[2])
774                 TRACE("dwReserved[2]: %u\n", pIndex->dwReserved[2]);
775
776             if (pIndex->bIndexType != AVI_INDEX_OF_INDEXES
777                 || pIndex->wLongsPerEntry != 4
778                 || rest < (pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry)
779                 || (pIndex->bIndexSubType != AVI_INDEX_SUB_2FIELD && pIndex->bIndexSubType != AVI_INDEX_SUB_DEFAULT))
780             {
781                 FIXME("Invalid index chunk encountered\n");
782                 break;
783             }
784
785             stream->entries = pIndex->nEntriesInUse;
786             stream->stdindex = CoTaskMemRealloc(stream->stdindex, sizeof(*stream->stdindex) * stream->entries);
787             for (x = 0; x < pIndex->nEntriesInUse; ++x)
788             {
789                 TRACE("qwOffset: %x%08x\n", (DWORD)(pIndex->aIndex[x].qwOffset >> 32), (DWORD)pIndex->aIndex[x].qwOffset);
790                 TRACE("dwSize: %u\n", pIndex->aIndex[x].dwSize);
791                 TRACE("dwDuration: %u (unreliable)\n", pIndex->aIndex[x].dwDuration);
792
793                 AVISplitter_ProcessIndex(This, &stream->stdindex[nstdindex-1], pIndex->aIndex[x].qwOffset, pIndex->aIndex[x].dwSize);
794             }
795             break;
796         }
797         default:
798             FIXME("unknown chunk type \"%.04s\" ignored\n", (LPCSTR)&pChunk->fcc);
799         }
800     }
801
802     if (IsEqualGUID(&amt.formattype, &FORMAT_WaveFormatEx))
803     {
804         amt.subtype = MEDIATYPE_Video;
805         amt.subtype.Data1 = ((WAVEFORMATEX *)amt.pbFormat)->wFormatTag;
806     }
807
808     dump_AM_MEDIA_TYPE(&amt);
809     TRACE("fSamplesPerSec = %f\n", (double)fSamplesPerSec);
810     TRACE("dwSampleSize = %x\n", dwSampleSize);
811     TRACE("dwLength = %x\n", dwLength);
812
813     stream->fSamplesPerSec = fSamplesPerSec;
814     stream->dwSampleSize = dwSampleSize;
815     stream->dwLength = dwLength; /* TODO: Use this for mediaseeking */
816     stream->packet_queued = CreateEventW(NULL, 0, 0, NULL);
817
818     hr = Parser_AddPin(&(This->Parser), &piOutput, props, &amt);
819     CoTaskMemFree(amt.pbFormat);
820
821
822     return hr;
823 }
824
825 static HRESULT AVISplitter_ProcessODML(AVISplitterImpl * This, const BYTE * pData, DWORD cb)
826 {
827     const RIFFCHUNK * pChunk;
828
829     for (pChunk = (const RIFFCHUNK *)pData;
830          ((const BYTE *)pChunk >= pData) && ((const BYTE *)pChunk + sizeof(RIFFCHUNK) < pData + cb) && (pChunk->cb > 0);
831          pChunk = (const RIFFCHUNK *)((const BYTE*)pChunk + sizeof(RIFFCHUNK) + pChunk->cb)
832         )
833     {
834         switch (pChunk->fcc)
835         {
836         case ckidAVIEXTHEADER:
837             {
838                 int x;
839                 const AVIEXTHEADER * pExtHdr = (const AVIEXTHEADER *)pChunk;
840
841                 TRACE("processing extension header\n");
842                 if (pExtHdr->cb != sizeof(AVIEXTHEADER) - sizeof(RIFFCHUNK))
843                 {
844                     FIXME("Size: %u\n", pExtHdr->cb);
845                     break;
846                 }
847                 TRACE("dwGrandFrames: %u\n", pExtHdr->dwGrandFrames);
848                 for (x = 0; x < 61; ++x)
849                     if (pExtHdr->dwFuture[x])
850                         FIXME("dwFuture[%i] = %u (0x%08x)\n", x, pExtHdr->dwFuture[x], pExtHdr->dwFuture[x]);
851                 This->ExtHeader = *pExtHdr;
852                 break;
853             }
854         default:
855             FIXME("unknown chunk type \"%.04s\" ignored\n", (LPCSTR)&pChunk->fcc);
856         }
857     }
858
859     return S_OK;
860 }
861
862 static HRESULT AVISplitter_InitializeStreams(AVISplitterImpl *This)
863 {
864     int x;
865
866     if (This->oldindex)
867     {
868         DWORD nMax, n;
869
870         for (x = 0; x < This->Parser.cStreams; ++x)
871         {
872             This->streams[x].frames = 0;
873             This->streams[x].pos = ~0;
874             This->streams[x].index = 0;
875         }
876
877         nMax = This->oldindex->cb / sizeof(This->oldindex->aIndex[0]);
878
879         /* Ok, maybe this is more of an excercise to see if I interpret everything correctly or not, but that is useful for now. */
880         for (n = 0; n < nMax; ++n)
881         {
882             DWORD streamId = StreamFromFOURCC(This->oldindex->aIndex[n].dwChunkId);
883             if (streamId >= This->Parser.cStreams)
884             {
885                 FIXME("Stream id %s ignored\n", debugstr_an((char*)&This->oldindex->aIndex[n].dwChunkId, 4));
886                 continue;
887             }
888             if (This->streams[streamId].pos == ~0)
889                 This->streams[streamId].pos = n;
890
891             if (This->streams[streamId].streamheader.dwSampleSize)
892                 This->streams[streamId].frames += This->oldindex->aIndex[n].dwSize / This->streams[streamId].streamheader.dwSampleSize;
893             else
894                 ++This->streams[streamId].frames;
895         }
896
897         for (x = 0; x < This->Parser.cStreams; ++x)
898         {
899             if ((DWORD)This->streams[x].frames != This->streams[x].streamheader.dwLength)
900             {
901                 FIXME("stream %u: frames found: %u, frames meant to be found: %u\n", x, (DWORD)This->streams[x].frames, This->streams[x].streamheader.dwLength);
902             }
903         }
904
905     }
906     else if (!This->streams[0].entries)
907     {
908         for (x = 0; x < This->Parser.cStreams; ++x)
909         {
910             This->streams[x].frames = This->streams[x].streamheader.dwLength;
911         }
912         /* MS Avi splitter does seek through the whole file, we should! */
913         ERR("We should be manually seeking through the entire file to build an index, because the index is missing!!!\n");
914         return E_NOTIMPL;
915     }
916
917     /* Not much here yet */
918     for (x = 0; x < This->Parser.cStreams; ++x)
919     {
920         StreamData *stream = This->streams + x;
921         int y;
922         DWORD64 frames = 0;
923
924         stream->seek = 1;
925
926         if (stream->stdindex)
927         {
928             stream->index = 0;
929             stream->pos = 0;
930             for (y = 0; y < stream->entries; ++y)
931             {
932                 if (stream->streamheader.dwSampleSize)
933                 {
934                     int z;
935
936                     for (z = 0; z < stream->stdindex[y]->nEntriesInUse; ++z)
937                     {
938                         UINT len = stream->stdindex[y]->aIndex[z].dwSize & ~(1 << 31);
939                         frames += len / stream->streamheader.dwSampleSize + !!(len % stream->streamheader.dwSampleSize);
940                     }
941                 }
942                 else
943                     frames += stream->stdindex[y]->nEntriesInUse;
944             }
945         }
946         else frames = stream->frames;
947
948         frames *= stream->streamheader.dwScale;
949         /* Keep accuracy as high as possible for duration */
950         This->Parser.mediaSeeking.llDuration = frames * 10000000;
951         This->Parser.mediaSeeking.llDuration /= stream->streamheader.dwRate;
952         This->Parser.mediaSeeking.llStop = This->Parser.mediaSeeking.llDuration;
953         This->Parser.mediaSeeking.llCurrent = 0;
954
955         frames /= stream->streamheader.dwRate;
956
957         TRACE("Duration: %d days, %d hours, %d minutes and %d seconds\n", (DWORD)(frames / 86400),
958         (DWORD)((frames % 86400) / 3600), (DWORD)((frames % 3600) / 60), (DWORD)(frames % 60));
959     }
960
961     return S_OK;
962 }
963
964 static HRESULT AVISplitter_Disconnect(LPVOID iface);
965
966 /* FIXME: fix leaks on failure here */
967 static HRESULT AVISplitter_InputPin_PreConnect(IPin * iface, IPin * pConnectPin, ALLOCATOR_PROPERTIES *props)
968 {
969     PullPin *This = (PullPin *)iface;
970     HRESULT hr;
971     RIFFLIST list;
972     LONGLONG pos = 0; /* in bytes */
973     BYTE * pBuffer;
974     RIFFCHUNK * pCurrentChunk;
975     LONGLONG total, avail;
976     int x;
977     DWORD indexes;
978
979     AVISplitterImpl * pAviSplit = (AVISplitterImpl *)This->pin.pinInfo.pFilter;
980
981     hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
982     pos += sizeof(list);
983
984     if (list.fcc != FOURCC_RIFF)
985     {
986         ERR("Input stream not a RIFF file\n");
987         return E_FAIL;
988     }
989     if (list.fccListType != formtypeAVI)
990     {
991         ERR("Input stream not an AVI RIFF file\n");
992         return E_FAIL;
993     }
994
995     hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
996     if (list.fcc != FOURCC_LIST)
997     {
998         ERR("Expected LIST chunk, but got %.04s\n", (LPSTR)&list.fcc);
999         return E_FAIL;
1000     }
1001     if (list.fccListType != listtypeAVIHEADER)
1002     {
1003         ERR("Header list expected. Got: %.04s\n", (LPSTR)&list.fccListType);
1004         return E_FAIL;
1005     }
1006
1007     pBuffer = HeapAlloc(GetProcessHeap(), 0, list.cb - sizeof(RIFFLIST) + sizeof(RIFFCHUNK));
1008     hr = IAsyncReader_SyncRead(This->pReader, pos + sizeof(list), list.cb - sizeof(RIFFLIST) + sizeof(RIFFCHUNK), pBuffer);
1009
1010     pAviSplit->AviHeader.cb = 0;
1011
1012     /* Stream list will set the buffer size here, so set a default and allow an override */
1013     props->cbBuffer = 0x20000;
1014
1015     for (pCurrentChunk = (RIFFCHUNK *)pBuffer; (BYTE *)pCurrentChunk + sizeof(*pCurrentChunk) < pBuffer + list.cb; pCurrentChunk = (RIFFCHUNK *)(((BYTE *)pCurrentChunk) + sizeof(*pCurrentChunk) + pCurrentChunk->cb))
1016     {
1017         RIFFLIST * pList;
1018
1019         switch (pCurrentChunk->fcc)
1020         {
1021         case ckidMAINAVIHEADER:
1022             /* AVIMAINHEADER includes the structure that is pCurrentChunk at the moment */
1023             memcpy(&pAviSplit->AviHeader, pCurrentChunk, sizeof(pAviSplit->AviHeader));
1024             break;
1025         case FOURCC_LIST:
1026             pList = (RIFFLIST *)pCurrentChunk;
1027             switch (pList->fccListType)
1028             {
1029             case ckidSTREAMLIST:
1030                 hr = AVISplitter_ProcessStreamList(pAviSplit, (BYTE *)pCurrentChunk + sizeof(RIFFLIST), pCurrentChunk->cb + sizeof(RIFFCHUNK) - sizeof(RIFFLIST), props);
1031                 break;
1032             case ckidODML:
1033                 hr = AVISplitter_ProcessODML(pAviSplit, (BYTE *)pCurrentChunk + sizeof(RIFFLIST), pCurrentChunk->cb + sizeof(RIFFCHUNK) - sizeof(RIFFLIST));
1034                 break;
1035             }
1036             break;
1037         case ckidAVIPADDING:
1038             /* ignore */
1039             break;
1040         default:
1041             FIXME("unrecognised header list type: %.04s\n", (LPSTR)&pCurrentChunk->fcc);
1042         }
1043     }
1044     HeapFree(GetProcessHeap(), 0, pBuffer);
1045
1046     if (pAviSplit->AviHeader.cb != sizeof(pAviSplit->AviHeader) - sizeof(RIFFCHUNK))
1047     {
1048         ERR("Avi Header wrong size!\n");
1049         return E_FAIL;
1050     }
1051
1052     pos += sizeof(RIFFCHUNK) + list.cb;
1053     hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1054
1055     while (list.fcc == ckidAVIPADDING || (list.fcc == FOURCC_LIST && list.fccListType == ckidINFO))
1056     {
1057         pos += sizeof(RIFFCHUNK) + list.cb;
1058
1059         hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1060     }
1061
1062     if (list.fcc != FOURCC_LIST)
1063     {
1064         ERR("Expected LIST, but got %.04s\n", (LPSTR)&list.fcc);
1065         return E_FAIL;
1066     }
1067     if (list.fccListType != listtypeAVIMOVIE)
1068     {
1069         ERR("Expected AVI movie list, but got %.04s\n", (LPSTR)&list.fccListType);
1070         return E_FAIL;
1071     }
1072
1073     IAsyncReader_Length(This->pReader, &total, &avail);
1074
1075     /* FIXME: AVIX files are extended beyond the FOURCC chunk "AVI ", and thus won't be played here,
1076      * once I get one of the files I'll try to fix it */
1077     if (hr == S_OK)
1078     {
1079         This->rtStart = pAviSplit->CurrentChunkOffset = MEDIATIME_FROM_BYTES(pos + sizeof(RIFFLIST));
1080         pos += list.cb + sizeof(RIFFCHUNK);
1081
1082         pAviSplit->EndOfFile = This->rtStop = MEDIATIME_FROM_BYTES(pos);
1083         if (pos > total)
1084         {
1085             ERR("File smaller (%x%08x) then EndOfFile (%x%08x)\n", (DWORD)(total >> 32), (DWORD)total, (DWORD)(pAviSplit->EndOfFile >> 32), (DWORD)pAviSplit->EndOfFile);
1086             return E_FAIL;
1087         }
1088
1089         hr = IAsyncReader_SyncRead(This->pReader, BYTES_FROM_MEDIATIME(pAviSplit->CurrentChunkOffset), sizeof(pAviSplit->CurrentChunk), (BYTE *)&pAviSplit->CurrentChunk);
1090     }
1091
1092     props->cbAlign = 1;
1093     props->cbPrefix = 0;
1094     /* Comrades, prevent shortage of buffers, or you will feel the consequences! DA! */
1095     props->cBuffers = 3 * pAviSplit->Parser.cStreams;
1096
1097     /* Now peek into the idx1 index, if available */
1098     if (hr == S_OK && (total - pos) > sizeof(RIFFCHUNK))
1099     {
1100         memset(&list, 0, sizeof(list));
1101
1102         hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1103         if (list.fcc == ckidAVIOLDINDEX)
1104         {
1105             pAviSplit->oldindex = CoTaskMemRealloc(pAviSplit->oldindex, list.cb + sizeof(RIFFCHUNK));
1106             if (pAviSplit->oldindex)
1107             {
1108                 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(RIFFCHUNK) + list.cb, (BYTE *)pAviSplit->oldindex);
1109                 if (hr == S_OK)
1110                 {
1111                     hr = AVISplitter_ProcessOldIndex(pAviSplit);
1112                 }
1113                 else
1114                 {
1115                     CoTaskMemFree(pAviSplit->oldindex);
1116                     pAviSplit->oldindex = NULL;
1117                     hr = S_OK;
1118                 }
1119             }
1120         }
1121     }
1122
1123     indexes = 0;
1124     for (x = 0; x < pAviSplit->Parser.cStreams; ++x)
1125         if (pAviSplit->streams[x].entries)
1126             ++indexes;
1127
1128     if (indexes)
1129     {
1130         CoTaskMemFree(pAviSplit->oldindex);
1131         pAviSplit->oldindex = NULL;
1132         if (indexes < pAviSplit->Parser.cStreams)
1133         {
1134             /* This error could possible be survived by switching to old type index,
1135              * but I would rather find out why it doesn't find everything here
1136              */
1137             ERR("%d indexes expected, but only have %d\n", indexes, pAviSplit->Parser.cStreams);
1138             indexes = 0;
1139         }
1140     }
1141     else if (!indexes && pAviSplit->oldindex)
1142         indexes = pAviSplit->Parser.cStreams;
1143
1144     if (!indexes && pAviSplit->AviHeader.dwFlags & AVIF_MUSTUSEINDEX)
1145     {
1146         FIXME("No usable index was found!\n");
1147         hr = E_FAIL;
1148     }
1149
1150     /* Now, set up the streams */
1151     if (hr == S_OK)
1152         hr = AVISplitter_InitializeStreams(pAviSplit);
1153
1154     if (hr != S_OK)
1155     {
1156         AVISplitter_Disconnect(pAviSplit);
1157         return E_FAIL;
1158     }
1159
1160     TRACE("AVI File ok\n");
1161
1162     return hr;
1163 }
1164
1165 static HRESULT AVISplitter_Flush(LPVOID iface)
1166 {
1167     AVISplitterImpl *This = (AVISplitterImpl*)iface;
1168     DWORD x;
1169
1170     ERR("(%p)->()\n", This);
1171
1172     for (x = 0; x < This->Parser.cStreams; ++x)
1173     {
1174         StreamData *stream = This->streams + x;
1175
1176         if (stream->sample)
1177             assert(IMediaSample_Release(stream->sample) == 0);
1178         stream->sample = NULL;
1179
1180         ResetEvent(stream->packet_queued);
1181         assert(!stream->thread);
1182     }
1183
1184     return S_OK;
1185 }
1186
1187 static HRESULT AVISplitter_Disconnect(LPVOID iface)
1188 {
1189     AVISplitterImpl *This = iface;
1190     int x;
1191
1192     /* TODO: Remove other memory that's allocated during connect */
1193     CoTaskMemFree(This->oldindex);
1194     This->oldindex = NULL;
1195
1196     for (x = 0; x < This->Parser.cStreams; ++x)
1197     {
1198         int i;
1199
1200         StreamData *stream = &This->streams[x];
1201
1202         for (i = 0; i < stream->entries; ++i)
1203             CoTaskMemFree(stream->stdindex[i]);
1204
1205         CoTaskMemFree(stream->stdindex);
1206         CloseHandle(stream->packet_queued);
1207     }
1208     CoTaskMemFree(This->streams);
1209     This->streams = NULL;
1210     return S_OK;
1211 }
1212
1213 static ULONG WINAPI AVISplitter_Release(IBaseFilter *iface)
1214 {
1215     AVISplitterImpl *This = (AVISplitterImpl *)iface;
1216     ULONG ref;
1217
1218     ref = InterlockedDecrement(&This->Parser.refCount);
1219
1220     TRACE("(%p)->() Release from %d\n", This, ref + 1);
1221
1222     if (!ref)
1223     {
1224         AVISplitter_Flush(This);
1225         Parser_Destroy(&This->Parser);
1226     }
1227
1228     return ref;
1229 }
1230
1231 static HRESULT AVISplitter_seek(IBaseFilter *iface)
1232 {
1233     AVISplitterImpl *This = (AVISplitterImpl *)iface;
1234     PullPin *pPin = This->Parser.pInputPin;
1235     LONGLONG newpos, endpos;
1236     DWORD x;
1237
1238     newpos = This->Parser.mediaSeeking.llCurrent;
1239     endpos = This->Parser.mediaSeeking.llDuration;
1240
1241     if (newpos > endpos)
1242     {
1243         WARN("Requesting position %x%08x beyond end of stream %x%08x\n", (DWORD)(newpos>>32), (DWORD)newpos, (DWORD)(endpos>>32), (DWORD)endpos);
1244         return E_INVALIDARG;
1245     }
1246
1247     FIXME("Moving position to %u.%03u s!\n", (DWORD)(newpos / 10000000), (DWORD)((newpos / 10000)%1000));
1248
1249     EnterCriticalSection(&pPin->thread_lock);
1250     /* Send a flush to all output pins */
1251     IPin_BeginFlush((IPin *)pPin);
1252
1253     /* Make sure this is done while stopped, BeginFlush takes care of this */
1254     EnterCriticalSection(&This->Parser.csFilter);
1255     for (x = 0; x < This->Parser.cStreams; ++x)
1256     {
1257         Parser_OutputPin *pin = (Parser_OutputPin *)This->Parser.ppPins[1+x];
1258         StreamData *stream = This->streams + x;
1259         IPin *victim = NULL;
1260         LONGLONG wanted_frames;
1261         DWORD last_keyframe = 0, last_keyframeidx = 0, preroll = 0;
1262
1263         wanted_frames = newpos;
1264         wanted_frames *= stream->streamheader.dwRate;
1265         wanted_frames /= 10000000;
1266         wanted_frames /= stream->streamheader.dwScale;
1267
1268         IPin_ConnectedTo((IPin *)pin, &victim);
1269         if (victim)
1270         {
1271             IPin_NewSegment(victim, newpos, endpos, pPin->dRate);
1272             IPin_Release(victim);
1273         }
1274
1275         pin->dwSamplesProcessed = 0;
1276         stream->index = 0;
1277         stream->pos = 0;
1278         stream->seek = 1;
1279         if (stream->stdindex)
1280         {
1281             DWORD y, z = 0;
1282
1283             for (y = 0; y < stream->entries; ++y)
1284             {
1285                 for (z = 0; z < stream->stdindex[y]->nEntriesInUse; ++z)
1286                 {
1287                     if (stream->streamheader.dwSampleSize)
1288                     {
1289                         ULONG len = stream->stdindex[y]->aIndex[z].dwSize & ~(1 << 31);
1290                         ULONG size = stream->streamheader.dwSampleSize;
1291
1292                         pin->dwSamplesProcessed += len / size;
1293                         if (len % size)
1294                             ++pin->dwSamplesProcessed;
1295                     }
1296                     else ++pin->dwSamplesProcessed;
1297
1298                     if (!(stream->stdindex[y]->aIndex[z].dwSize >> 31))
1299                     {
1300                         last_keyframe = z;
1301                         last_keyframeidx = y;
1302                         preroll = 0;
1303                     }
1304                     else
1305                         ++preroll;
1306
1307                     if (pin->dwSamplesProcessed >= wanted_frames)
1308                         break;
1309                 }
1310                 if (pin->dwSamplesProcessed >= wanted_frames)
1311                     break;
1312             }
1313             stream->index = last_keyframeidx;
1314             stream->pos = last_keyframe;
1315         }
1316         else
1317         {
1318             DWORD nMax, n;
1319             nMax = This->oldindex->cb / sizeof(This->oldindex->aIndex[0]);
1320
1321             for (n = 0; n < nMax; ++n)
1322             {
1323                 DWORD streamId = StreamFromFOURCC(This->oldindex->aIndex[n].dwChunkId);
1324                 if (streamId != x)
1325                     continue;
1326
1327                 if (stream->streamheader.dwSampleSize)
1328                 {
1329                     ULONG len = This->oldindex->aIndex[n].dwSize;
1330                     ULONG size = stream->streamheader.dwSampleSize;
1331
1332                     pin->dwSamplesProcessed += len / size;
1333                     if (len % size)
1334                         ++pin->dwSamplesProcessed;
1335                 }
1336                 else ++pin->dwSamplesProcessed;
1337
1338                 if (This->oldindex->aIndex[n].dwFlags & AVIIF_KEYFRAME)
1339                 {
1340                     last_keyframe = n;
1341                     preroll = 0;
1342                 }
1343                 else
1344                     ++preroll;
1345
1346                 if (pin->dwSamplesProcessed >= wanted_frames)
1347                     break;
1348             }
1349             assert(n < nMax);
1350             stream->pos = last_keyframe;
1351             stream->index = 0;
1352         }
1353         stream->preroll = preroll;
1354         stream->seek = 1;
1355     }
1356     LeaveCriticalSection(&This->Parser.csFilter);
1357
1358     TRACE("Done flushing\n");
1359     IPin_EndFlush((IPin *)pPin);
1360     LeaveCriticalSection(&pPin->thread_lock);
1361
1362     return S_OK;
1363 }
1364
1365 static const IBaseFilterVtbl AVISplitterImpl_Vtbl =
1366 {
1367     Parser_QueryInterface,
1368     Parser_AddRef,
1369     AVISplitter_Release,
1370     Parser_GetClassID,
1371     Parser_Stop,
1372     Parser_Pause,
1373     Parser_Run,
1374     Parser_GetState,
1375     Parser_SetSyncSource,
1376     Parser_GetSyncSource,
1377     Parser_EnumPins,
1378     Parser_FindPin,
1379     Parser_QueryFilterInfo,
1380     Parser_JoinFilterGraph,
1381     Parser_QueryVendorInfo
1382 };
1383
1384 HRESULT AVISplitter_create(IUnknown * pUnkOuter, LPVOID * ppv)
1385 {
1386     HRESULT hr;
1387     AVISplitterImpl * This;
1388
1389     TRACE("(%p, %p)\n", pUnkOuter, ppv);
1390
1391     *ppv = NULL;
1392
1393     if (pUnkOuter)
1394         return CLASS_E_NOAGGREGATION;
1395
1396     /* Note: This memory is managed by the transform filter once created */
1397     This = CoTaskMemAlloc(sizeof(AVISplitterImpl));
1398
1399     This->streams = NULL;
1400     This->oldindex = NULL;
1401
1402     hr = Parser_Create(&(This->Parser), &AVISplitterImpl_Vtbl, &CLSID_AviSplitter, AVISplitter_Sample, AVISplitter_QueryAccept, AVISplitter_InputPin_PreConnect, AVISplitter_Flush, AVISplitter_Disconnect, AVISplitter_first_request, AVISplitter_done_process, NULL, AVISplitter_seek, NULL);
1403
1404     if (FAILED(hr))
1405         return hr;
1406
1407     *ppv = (LPVOID)This;
1408
1409     return hr;
1410 }