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