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