imm32: Sign-compare warnings fix.
[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             BOOL keyframe;
182
183             /* End of file */
184             if (stream->index >= stream->entries)
185             {
186                 TRACE("END OF STREAM ON %u\n", streamnumber);
187                 IMediaSample_Release(sample);
188                 return S_FALSE;
189             }
190
191             rtSampleStart = index->qwBaseOffset;
192             keyframe = !(entry->dwSize >> 31);
193             rtSampleStart += entry->dwOffset;
194             rtSampleStart = MEDIATIME_FROM_BYTES(rtSampleStart);
195
196             ++stream->pos_next;
197             if (index->nEntriesInUse == stream->pos_next)
198             {
199                 stream->pos_next = 0;
200                 ++stream->index_next;
201             }
202
203             rtSampleStop = rtSampleStart + MEDIATIME_FROM_BYTES(entry->dwSize & ~(1 << 31));
204
205             TRACE("offset(%u) size(%u)\n", (DWORD)BYTES_FROM_MEDIATIME(rtSampleStart), (DWORD)BYTES_FROM_MEDIATIME(rtSampleStop - rtSampleStart));
206         }
207         else if (This->oldindex)
208         {
209             DWORD flags = This->oldindex->aIndex[stream->pos].dwFlags;
210             DWORD size = This->oldindex->aIndex[stream->pos].dwSize;
211             BOOL keyframe;
212
213             /* End of file */
214             if (stream->index)
215             {
216                 TRACE("END OF STREAM ON %u\n", streamnumber);
217                 IMediaSample_Release(sample);
218                 return S_FALSE;
219             }
220
221             keyframe = !!(flags & AVIIF_KEYFRAME);
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;
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     IMediaSample_SetTime(sample, &start, &stop);
318
319     hr = OutputPin_SendSample(&pin->pin, sample);
320
321 /* Uncomment this if you want to debug the time differences between the
322  * different streams, it is useful for that
323  *
324     FIXME("stream %u, hr: %08x, Start: %u.%03u, Stop: %u.%03u\n", streamnumber, hr,
325            (DWORD)(start / 10000000), (DWORD)((start / 10000)%1000),
326            (DWORD)(stop / 10000000), (DWORD)((stop / 10000)%1000));
327 */
328     return hr;
329 }
330
331 static DWORD WINAPI AVISplitter_thread_reader(LPVOID data)
332 {
333     struct thread_args *args = data;
334     AVISplitterImpl *This = args->This;
335     DWORD streamnumber = args->stream;
336     HRESULT hr = S_OK;
337
338     do
339     {
340         HRESULT nexthr = S_FALSE;
341         IMediaSample *sample;
342
343         WaitForSingleObject(This->streams[streamnumber].packet_queued, INFINITE);
344         sample = This->streams[streamnumber].sample;
345         This->streams[streamnumber].sample = NULL;
346         if (!sample)
347             break;
348
349         nexthr = AVISplitter_next_request(This, streamnumber);
350
351         hr = AVISplitter_Receive(This, sample, streamnumber);
352         if (hr != S_OK)
353             FIXME("Receiving error: %08x\n", hr);
354
355         IMediaSample_Release(sample);
356         if (hr == S_OK)
357             hr = nexthr;
358         if (nexthr == S_FALSE)
359             AVISplitter_SendEndOfFile(This, streamnumber);
360     } while (hr == S_OK);
361
362     FIXME("Thread %u terminated with hr %08x!\n", streamnumber, hr);
363
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 = (AVISplitterImpl *)iface;
405     HRESULT hr = S_OK;
406     int 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         FIXME("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         FIXME("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     FIXME("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     int x, rest;
523
524     *index = NULL;
525     if (cb < sizeof(AVISTDINDEX))
526     {
527         FIXME("size %u too small\n", cb);
528         return E_INVALIDARG;
529     }
530
531     pIndex = CoTaskMemAlloc(cb);
532     if (!pIndex)
533         return E_OUTOFMEMORY;
534
535     IAsyncReader_SyncRead(((PullPin *)This->Parser.ppPins[0])->pReader, qwOffset, cb, (BYTE *)pIndex);
536     rest = cb - sizeof(AVISUPERINDEX) + sizeof(RIFFCHUNK) + sizeof(pIndex->aIndex);
537
538     TRACE("FOURCC: %s\n", debugstr_an((char *)&pIndex->fcc, 4));
539     TRACE("wLongsPerEntry: %hd\n", pIndex->wLongsPerEntry);
540     TRACE("bIndexSubType: %hd\n", pIndex->bIndexSubType);
541     TRACE("bIndexType: %hd\n", pIndex->bIndexType);
542     TRACE("nEntriesInUse: %u\n", pIndex->nEntriesInUse);
543     TRACE("dwChunkId: %.4s\n", (char *)&pIndex->dwChunkId);
544     TRACE("qwBaseOffset: %x%08x\n", (DWORD)(pIndex->qwBaseOffset >> 32), (DWORD)pIndex->qwBaseOffset);
545     TRACE("dwReserved_3: %u\n", pIndex->dwReserved_3);
546
547     if (pIndex->bIndexType != AVI_INDEX_OF_CHUNKS
548         || pIndex->wLongsPerEntry != 2
549         || rest < (pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry)
550         || (pIndex->bIndexSubType != AVI_INDEX_SUB_DEFAULT))
551     {
552         FIXME("Invalid index chunk encountered: %u/%u, %u/%u, %u/%u, %u/%u\n",
553               pIndex->bIndexType, AVI_INDEX_OF_CHUNKS, pIndex->wLongsPerEntry, 2,
554               rest, (DWORD)(pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry),
555               pIndex->bIndexSubType, AVI_INDEX_SUB_DEFAULT);
556         *index = NULL;
557         return E_INVALIDARG;
558     }
559
560     for (x = 0; x < pIndex->nEntriesInUse; ++x)
561     {
562         BOOL keyframe = !(pIndex->aIndex[x].dwSize >> 31);
563         DWORDLONG offset = pIndex->qwBaseOffset + pIndex->aIndex[x].dwOffset;
564         TRACE("dwOffset: %x%08x\n", (DWORD)(offset >> 32), (DWORD)offset);
565         TRACE("dwSize: %u\n", (pIndex->aIndex[x].dwSize & ~(1<<31)));
566         TRACE("Frame is a keyframe: %s\n", keyframe ? "yes" : "no");
567     }
568
569     *index = pIndex;
570     return S_OK;
571 }
572
573 static HRESULT AVISplitter_ProcessOldIndex(AVISplitterImpl *This)
574 {
575     ULONGLONG mov_pos = BYTES_FROM_MEDIATIME(This->CurrentChunkOffset) - sizeof(DWORD);
576     AVIOLDINDEX *pAviOldIndex = This->oldindex;
577     int relative = -1;
578     int x;
579
580     for (x = 0; x < pAviOldIndex->cb / sizeof(pAviOldIndex->aIndex[0]); ++x)
581     {
582         DWORD temp, temp2 = 0, offset, chunkid;
583         PullPin *pin = This->Parser.pInputPin;
584
585         offset = pAviOldIndex->aIndex[x].dwOffset;
586         chunkid = pAviOldIndex->aIndex[x].dwChunkId;
587
588         TRACE("dwChunkId: %.4s\n", (char *)&chunkid);
589         TRACE("dwFlags: %08x\n", pAviOldIndex->aIndex[x].dwFlags);
590         TRACE("dwOffset (%s): %08x\n", relative ? "relative" : "absolute", offset);
591         TRACE("dwSize: %08x\n", pAviOldIndex->aIndex[x].dwSize);
592
593         /* Only scan once, or else this will take too long */
594         if (relative == -1)
595         {
596             IAsyncReader_SyncRead(pin->pReader, offset, sizeof(DWORD), (BYTE *)&temp);
597             relative = (chunkid != temp);
598
599             if (chunkid == mmioFOURCC('7','F','x','x')
600                 && ((char *)&temp)[0] == 'i' && ((char *)&temp)[1] == 'x')
601                 relative = FALSE;
602
603             if (relative)
604             {
605                 if (offset + mov_pos < BYTES_FROM_MEDIATIME(This->EndOfFile))
606                     IAsyncReader_SyncRead(pin->pReader, offset + mov_pos, sizeof(DWORD), (BYTE *)&temp2);
607
608                 if (chunkid == mmioFOURCC('7','F','x','x')
609                     && ((char *)&temp2)[0] == 'i' && ((char *)&temp2)[1] == 'x')
610                 {
611                     /* Do nothing, all is great */
612                 }
613                 else if (temp2 != chunkid)
614                 {
615                     ERR("Faulty index or bug in handling: Wanted FCC: %s, Abs FCC: %s (@ %x), Rel FCC: %s (@ %.0x%08x)\n",
616                         debugstr_an((char *)&chunkid, 4), debugstr_an((char *)&temp, 4), offset,
617                         debugstr_an((char *)&temp2, 4), (DWORD)((mov_pos + offset) >> 32), (DWORD)(mov_pos + offset));
618                     relative = -1;
619                 }
620                 else
621                     TRACE("Scanned dwChunkId: %s\n", debugstr_an((char *)&temp2, 4));
622             }
623             else if (!relative)
624                 TRACE("Scanned dwChunkId: %s\n", debugstr_an((char *)&temp, 4));
625         }
626         /* Only dump one packet */
627         else break;
628     }
629
630     if (relative == -1)
631     {
632         FIXME("Dropping index: no idea whether it is relative or absolute\n");
633         CoTaskMemFree(This->oldindex);
634         This->oldindex = NULL;
635     }
636     else if (!relative)
637         This->offset = 0;
638     else
639         This->offset = (DWORD)mov_pos;
640
641     return S_OK;
642 }
643
644 static HRESULT AVISplitter_ProcessStreamList(AVISplitterImpl * This, const BYTE * pData, DWORD cb, ALLOCATOR_PROPERTIES *props)
645 {
646     PIN_INFO piOutput;
647     const RIFFCHUNK * pChunk;
648     HRESULT hr;
649     AM_MEDIA_TYPE amt;
650     float fSamplesPerSec = 0.0f;
651     DWORD dwSampleSize = 0;
652     DWORD dwLength = 0;
653     DWORD nstdindex = 0;
654     static const WCHAR wszStreamTemplate[] = {'S','t','r','e','a','m',' ','%','0','2','d',0};
655     StreamData *stream;
656
657     ZeroMemory(&amt, sizeof(amt));
658     piOutput.dir = PINDIR_OUTPUT;
659     piOutput.pFilter = (IBaseFilter *)This;
660     wsprintfW(piOutput.achName, wszStreamTemplate, This->Parser.cStreams);
661     This->streams = CoTaskMemRealloc(This->streams, sizeof(StreamData) * (This->Parser.cStreams+1));
662     stream = This->streams + This->Parser.cStreams;
663     ZeroMemory(stream, sizeof(*stream));
664
665     for (pChunk = (const RIFFCHUNK *)pData; 
666          ((const BYTE *)pChunk >= pData) && ((const BYTE *)pChunk + sizeof(RIFFCHUNK) < pData + cb) && (pChunk->cb > 0); 
667          pChunk = (const RIFFCHUNK *)((const BYTE*)pChunk + sizeof(RIFFCHUNK) + pChunk->cb)     
668         )
669     {
670         switch (pChunk->fcc)
671         {
672         case ckidSTREAMHEADER:
673             {
674                 const AVISTREAMHEADER * pStrHdr = (const AVISTREAMHEADER *)pChunk;
675                 TRACE("processing stream header\n");
676                 stream->streamheader = *pStrHdr;
677
678                 fSamplesPerSec = (float)pStrHdr->dwRate / (float)pStrHdr->dwScale;
679                 CoTaskMemFree(amt.pbFormat);
680                 amt.pbFormat = NULL;
681                 amt.cbFormat = 0;
682
683                 switch (pStrHdr->fccType)
684                 {
685                 case streamtypeVIDEO:
686                     amt.formattype = FORMAT_VideoInfo;
687                     break;
688                 case streamtypeAUDIO:
689                     amt.formattype = FORMAT_WaveFormatEx;
690                     break;
691                 default:
692                     FIXME("fccType %.4s not handled yet\n", (char *)&pStrHdr->fccType);
693                     amt.formattype = FORMAT_None;
694                 }
695                 amt.majortype = MEDIATYPE_Video;
696                 amt.majortype.Data1 = pStrHdr->fccType;
697                 amt.subtype = MEDIATYPE_Video;
698                 amt.subtype.Data1 = pStrHdr->fccHandler;
699                 TRACE("Subtype FCC: %.04s\n", (LPCSTR)&pStrHdr->fccHandler);
700                 amt.lSampleSize = pStrHdr->dwSampleSize;
701                 amt.bFixedSizeSamples = (amt.lSampleSize != 0);
702
703                 /* FIXME: Is this right? */
704                 if (!amt.lSampleSize)
705                 {
706                     amt.lSampleSize = 1;
707                     dwSampleSize = 1;
708                 }
709
710                 amt.bTemporalCompression = IsEqualGUID(&amt.majortype, &MEDIATYPE_Video); /* FIXME? */
711                 dwSampleSize = pStrHdr->dwSampleSize;
712                 dwLength = pStrHdr->dwLength;
713                 if (!dwLength)
714                     dwLength = This->AviHeader.dwTotalFrames;
715
716                 if (pStrHdr->dwSuggestedBufferSize && pStrHdr->dwSuggestedBufferSize > props->cbBuffer)
717                     props->cbBuffer = pStrHdr->dwSuggestedBufferSize;
718
719                 break;
720             }
721         case ckidSTREAMFORMAT:
722             TRACE("processing stream format data\n");
723             if (IsEqualIID(&amt.formattype, &FORMAT_VideoInfo))
724             {
725                 VIDEOINFOHEADER * pvi;
726                 /* biCompression member appears to override the value in the stream header.
727                  * i.e. the stream header can say something completely contradictory to what
728                  * is in the BITMAPINFOHEADER! */
729                 if (pChunk->cb < sizeof(BITMAPINFOHEADER))
730                 {
731                     ERR("Not enough bytes for BITMAPINFOHEADER\n");
732                     return E_FAIL;
733                 }
734                 amt.cbFormat = sizeof(VIDEOINFOHEADER) - sizeof(BITMAPINFOHEADER) + pChunk->cb;
735                 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
736                 ZeroMemory(amt.pbFormat, amt.cbFormat);
737                 pvi = (VIDEOINFOHEADER *)amt.pbFormat;
738                 pvi->AvgTimePerFrame = (LONGLONG)(10000000.0 / fSamplesPerSec);
739
740                 CopyMemory(&pvi->bmiHeader, (const BYTE *)(pChunk + 1), pChunk->cb);
741                 if (pvi->bmiHeader.biCompression)
742                     amt.subtype.Data1 = pvi->bmiHeader.biCompression;
743             }
744             else if (IsEqualIID(&amt.formattype, &FORMAT_WaveFormatEx))
745             {
746                 amt.cbFormat = pChunk->cb;
747                 if (amt.cbFormat < sizeof(WAVEFORMATEX))
748                     amt.cbFormat = sizeof(WAVEFORMATEX);
749                 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
750                 ZeroMemory(amt.pbFormat, amt.cbFormat);
751                 CopyMemory(amt.pbFormat, (const BYTE *)(pChunk + 1), pChunk->cb);
752             }
753             else
754             {
755                 amt.cbFormat = pChunk->cb;
756                 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
757                 CopyMemory(amt.pbFormat, (const BYTE *)(pChunk + 1), amt.cbFormat);
758             }
759             break;
760         case ckidSTREAMNAME:
761             TRACE("processing stream name\n");
762             /* FIXME: this doesn't exactly match native version (we omit the "##)" prefix), but hey... */
763             MultiByteToWideChar(CP_ACP, 0, (LPCSTR)(pChunk + 1), pChunk->cb, piOutput.achName, sizeof(piOutput.achName) / sizeof(piOutput.achName[0]));
764             break;
765         case ckidSTREAMHANDLERDATA:
766             FIXME("process stream handler data\n");
767             break;
768         case ckidAVIPADDING:
769             TRACE("JUNK chunk ignored\n");
770             break;
771         case ckidAVISUPERINDEX:
772         {
773             const AVISUPERINDEX *pIndex = (const AVISUPERINDEX *)pChunk;
774             int x;
775             long rest = pIndex->cb - sizeof(AVISUPERINDEX) + sizeof(RIFFCHUNK) + sizeof(pIndex->aIndex[0]) * ANYSIZE_ARRAY;
776
777             if (pIndex->cb < sizeof(AVISUPERINDEX) - sizeof(RIFFCHUNK))
778             {
779                 FIXME("size %u\n", pIndex->cb);
780                 break;
781             }
782
783             if (nstdindex++ > 0)
784             {
785                 ERR("Stream %d got more than 1 superindex?\n", This->Parser.cStreams);
786                 break;
787             }
788
789             TRACE("wLongsPerEntry: %hd\n", pIndex->wLongsPerEntry);
790             TRACE("bIndexSubType: %hd\n", pIndex->bIndexSubType);
791             TRACE("bIndexType: %hd\n", pIndex->bIndexType);
792             TRACE("nEntriesInUse: %u\n", pIndex->nEntriesInUse);
793             TRACE("dwChunkId: %.4s\n", (char *)&pIndex->dwChunkId);
794             if (pIndex->dwReserved[0])
795                 TRACE("dwReserved[0]: %u\n", pIndex->dwReserved[0]);
796             if (pIndex->dwReserved[2])
797                 TRACE("dwReserved[1]: %u\n", pIndex->dwReserved[1]);
798             if (pIndex->dwReserved[2])
799                 TRACE("dwReserved[2]: %u\n", pIndex->dwReserved[2]);
800
801             if (pIndex->bIndexType != AVI_INDEX_OF_INDEXES
802                 || pIndex->wLongsPerEntry != 4
803                 || rest < (pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry)
804                 || (pIndex->bIndexSubType != AVI_INDEX_SUB_2FIELD && pIndex->bIndexSubType != AVI_INDEX_SUB_DEFAULT))
805             {
806                 FIXME("Invalid index chunk encountered\n");
807                 break;
808             }
809
810             stream->entries = pIndex->nEntriesInUse;
811             stream->stdindex = CoTaskMemRealloc(stream->stdindex, sizeof(*stream->stdindex) * stream->entries);
812             for (x = 0; x < pIndex->nEntriesInUse; ++x)
813             {
814                 TRACE("qwOffset: %x%08x\n", (DWORD)(pIndex->aIndex[x].qwOffset >> 32), (DWORD)pIndex->aIndex[x].qwOffset);
815                 TRACE("dwSize: %u\n", pIndex->aIndex[x].dwSize);
816                 TRACE("dwDuration: %u (unreliable)\n", pIndex->aIndex[x].dwDuration);
817
818                 AVISplitter_ProcessIndex(This, &stream->stdindex[x], pIndex->aIndex[x].qwOffset, pIndex->aIndex[x].dwSize);
819             }
820             break;
821         }
822         default:
823             FIXME("unknown chunk type \"%.04s\" ignored\n", (LPCSTR)&pChunk->fcc);
824         }
825     }
826
827     if (IsEqualGUID(&amt.formattype, &FORMAT_WaveFormatEx))
828     {
829         amt.subtype = MEDIATYPE_Video;
830         amt.subtype.Data1 = ((WAVEFORMATEX *)amt.pbFormat)->wFormatTag;
831     }
832
833     dump_AM_MEDIA_TYPE(&amt);
834     TRACE("fSamplesPerSec = %f\n", (double)fSamplesPerSec);
835     TRACE("dwSampleSize = %x\n", dwSampleSize);
836     TRACE("dwLength = %x\n", dwLength);
837
838     stream->fSamplesPerSec = fSamplesPerSec;
839     stream->dwSampleSize = dwSampleSize;
840     stream->dwLength = dwLength; /* TODO: Use this for mediaseeking */
841     stream->packet_queued = CreateEventW(NULL, 0, 0, NULL);
842
843     hr = Parser_AddPin(&(This->Parser), &piOutput, props, &amt);
844     CoTaskMemFree(amt.pbFormat);
845
846
847     return hr;
848 }
849
850 static HRESULT AVISplitter_ProcessODML(AVISplitterImpl * This, const BYTE * pData, DWORD cb)
851 {
852     const RIFFCHUNK * pChunk;
853
854     for (pChunk = (const RIFFCHUNK *)pData;
855          ((const BYTE *)pChunk >= pData) && ((const BYTE *)pChunk + sizeof(RIFFCHUNK) < pData + cb) && (pChunk->cb > 0);
856          pChunk = (const RIFFCHUNK *)((const BYTE*)pChunk + sizeof(RIFFCHUNK) + pChunk->cb)
857         )
858     {
859         switch (pChunk->fcc)
860         {
861         case ckidAVIEXTHEADER:
862             {
863                 int x;
864                 const AVIEXTHEADER * pExtHdr = (const AVIEXTHEADER *)pChunk;
865
866                 TRACE("processing extension header\n");
867                 if (pExtHdr->cb != sizeof(AVIEXTHEADER) - sizeof(RIFFCHUNK))
868                 {
869                     FIXME("Size: %u\n", pExtHdr->cb);
870                     break;
871                 }
872                 TRACE("dwGrandFrames: %u\n", pExtHdr->dwGrandFrames);
873                 for (x = 0; x < 61; ++x)
874                     if (pExtHdr->dwFuture[x])
875                         FIXME("dwFuture[%i] = %u (0x%08x)\n", x, pExtHdr->dwFuture[x], pExtHdr->dwFuture[x]);
876                 This->ExtHeader = *pExtHdr;
877                 break;
878             }
879         default:
880             FIXME("unknown chunk type \"%.04s\" ignored\n", (LPCSTR)&pChunk->fcc);
881         }
882     }
883
884     return S_OK;
885 }
886
887 static HRESULT AVISplitter_InitializeStreams(AVISplitterImpl *This)
888 {
889     int x;
890
891     if (This->oldindex)
892     {
893         DWORD nMax, n;
894
895         for (x = 0; x < This->Parser.cStreams; ++x)
896         {
897             This->streams[x].frames = 0;
898             This->streams[x].pos = ~0;
899             This->streams[x].index = 0;
900         }
901
902         nMax = This->oldindex->cb / sizeof(This->oldindex->aIndex[0]);
903
904         /* Ok, maybe this is more of an excercise to see if I interpret everything correctly or not, but that is useful for now. */
905         for (n = 0; n < nMax; ++n)
906         {
907             DWORD streamId = StreamFromFOURCC(This->oldindex->aIndex[n].dwChunkId);
908             if (streamId >= This->Parser.cStreams)
909             {
910                 FIXME("Stream id %s ignored\n", debugstr_an((char*)&This->oldindex->aIndex[n].dwChunkId, 4));
911                 continue;
912             }
913             if (This->streams[streamId].pos == ~0)
914                 This->streams[streamId].pos = n;
915
916             if (This->streams[streamId].streamheader.dwSampleSize)
917                 This->streams[streamId].frames += This->oldindex->aIndex[n].dwSize / This->streams[streamId].streamheader.dwSampleSize;
918             else
919                 ++This->streams[streamId].frames;
920         }
921
922         for (x = 0; x < This->Parser.cStreams; ++x)
923         {
924             if ((DWORD)This->streams[x].frames != This->streams[x].streamheader.dwLength)
925             {
926                 FIXME("stream %u: frames found: %u, frames meant to be found: %u\n", x, (DWORD)This->streams[x].frames, This->streams[x].streamheader.dwLength);
927             }
928         }
929
930     }
931     else if (!This->streams[0].entries)
932     {
933         for (x = 0; x < This->Parser.cStreams; ++x)
934         {
935             This->streams[x].frames = This->streams[x].streamheader.dwLength;
936         }
937         /* MS Avi splitter does seek through the whole file, we should! */
938         ERR("We should be manually seeking through the entire file to build an index, because the index is missing!!!\n");
939         return E_NOTIMPL;
940     }
941
942     /* Not much here yet */
943     for (x = 0; x < This->Parser.cStreams; ++x)
944     {
945         StreamData *stream = This->streams + x;
946         int y;
947         DWORD64 frames = 0;
948
949         stream->seek = 1;
950
951         if (stream->stdindex)
952         {
953             stream->index = 0;
954             stream->pos = 0;
955             for (y = 0; y < stream->entries; ++y)
956             {
957                 if (stream->streamheader.dwSampleSize)
958                 {
959                     int z;
960
961                     for (z = 0; z < stream->stdindex[y]->nEntriesInUse; ++z)
962                     {
963                         UINT len = stream->stdindex[y]->aIndex[z].dwSize & ~(1 << 31);
964                         frames += len / stream->streamheader.dwSampleSize + !!(len % stream->streamheader.dwSampleSize);
965                     }
966                 }
967                 else
968                     frames += stream->stdindex[y]->nEntriesInUse;
969             }
970         }
971         else frames = stream->frames;
972
973         frames *= stream->streamheader.dwScale;
974         /* Keep accuracy as high as possible for duration */
975         This->Parser.mediaSeeking.llDuration = frames * 10000000;
976         This->Parser.mediaSeeking.llDuration /= stream->streamheader.dwRate;
977         This->Parser.mediaSeeking.llStop = This->Parser.mediaSeeking.llDuration;
978         This->Parser.mediaSeeking.llCurrent = 0;
979
980         frames /= stream->streamheader.dwRate;
981
982         TRACE("Duration: %d days, %d hours, %d minutes and %d.%03u seconds\n", (DWORD)(frames / 86400),
983         (DWORD)((frames % 86400) / 3600), (DWORD)((frames % 3600) / 60), (DWORD)(frames % 60),
984         (DWORD)(This->Parser.mediaSeeking.llDuration/10000) % 1000);
985     }
986
987     return S_OK;
988 }
989
990 static HRESULT AVISplitter_Disconnect(LPVOID iface);
991
992 /* FIXME: fix leaks on failure here */
993 static HRESULT AVISplitter_InputPin_PreConnect(IPin * iface, IPin * pConnectPin, ALLOCATOR_PROPERTIES *props)
994 {
995     PullPin *This = (PullPin *)iface;
996     HRESULT hr;
997     RIFFLIST list;
998     LONGLONG pos = 0; /* in bytes */
999     BYTE * pBuffer;
1000     RIFFCHUNK * pCurrentChunk;
1001     LONGLONG total, avail;
1002     int x;
1003     DWORD indexes;
1004
1005     AVISplitterImpl * pAviSplit = (AVISplitterImpl *)This->pin.pinInfo.pFilter;
1006
1007     hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1008     pos += sizeof(list);
1009
1010     if (list.fcc != FOURCC_RIFF)
1011     {
1012         ERR("Input stream not a RIFF file\n");
1013         return E_FAIL;
1014     }
1015     if (list.fccListType != formtypeAVI)
1016     {
1017         ERR("Input stream not an AVI RIFF file\n");
1018         return E_FAIL;
1019     }
1020
1021     hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1022     if (list.fcc != FOURCC_LIST)
1023     {
1024         ERR("Expected LIST chunk, but got %.04s\n", (LPSTR)&list.fcc);
1025         return E_FAIL;
1026     }
1027     if (list.fccListType != listtypeAVIHEADER)
1028     {
1029         ERR("Header list expected. Got: %.04s\n", (LPSTR)&list.fccListType);
1030         return E_FAIL;
1031     }
1032
1033     pBuffer = HeapAlloc(GetProcessHeap(), 0, list.cb - sizeof(RIFFLIST) + sizeof(RIFFCHUNK));
1034     hr = IAsyncReader_SyncRead(This->pReader, pos + sizeof(list), list.cb - sizeof(RIFFLIST) + sizeof(RIFFCHUNK), pBuffer);
1035
1036     pAviSplit->AviHeader.cb = 0;
1037
1038     /* Stream list will set the buffer size here, so set a default and allow an override */
1039     props->cbBuffer = 0x20000;
1040
1041     for (pCurrentChunk = (RIFFCHUNK *)pBuffer; (BYTE *)pCurrentChunk + sizeof(*pCurrentChunk) < pBuffer + list.cb; pCurrentChunk = (RIFFCHUNK *)(((BYTE *)pCurrentChunk) + sizeof(*pCurrentChunk) + pCurrentChunk->cb))
1042     {
1043         RIFFLIST * pList;
1044
1045         switch (pCurrentChunk->fcc)
1046         {
1047         case ckidMAINAVIHEADER:
1048             /* AVIMAINHEADER includes the structure that is pCurrentChunk at the moment */
1049             memcpy(&pAviSplit->AviHeader, pCurrentChunk, sizeof(pAviSplit->AviHeader));
1050             break;
1051         case FOURCC_LIST:
1052             pList = (RIFFLIST *)pCurrentChunk;
1053             switch (pList->fccListType)
1054             {
1055             case ckidSTREAMLIST:
1056                 hr = AVISplitter_ProcessStreamList(pAviSplit, (BYTE *)pCurrentChunk + sizeof(RIFFLIST), pCurrentChunk->cb + sizeof(RIFFCHUNK) - sizeof(RIFFLIST), props);
1057                 break;
1058             case ckidODML:
1059                 hr = AVISplitter_ProcessODML(pAviSplit, (BYTE *)pCurrentChunk + sizeof(RIFFLIST), pCurrentChunk->cb + sizeof(RIFFCHUNK) - sizeof(RIFFLIST));
1060                 break;
1061             }
1062             break;
1063         case ckidAVIPADDING:
1064             /* ignore */
1065             break;
1066         default:
1067             FIXME("unrecognised header list type: %.04s\n", (LPSTR)&pCurrentChunk->fcc);
1068         }
1069     }
1070     HeapFree(GetProcessHeap(), 0, pBuffer);
1071
1072     if (pAviSplit->AviHeader.cb != sizeof(pAviSplit->AviHeader) - sizeof(RIFFCHUNK))
1073     {
1074         ERR("Avi Header wrong size!\n");
1075         return E_FAIL;
1076     }
1077
1078     pos += sizeof(RIFFCHUNK) + list.cb;
1079     hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1080
1081     while (list.fcc == ckidAVIPADDING || (list.fcc == FOURCC_LIST && list.fccListType == ckidINFO))
1082     {
1083         pos += sizeof(RIFFCHUNK) + list.cb;
1084
1085         hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1086     }
1087
1088     if (list.fcc != FOURCC_LIST)
1089     {
1090         ERR("Expected LIST, but got %.04s\n", (LPSTR)&list.fcc);
1091         return E_FAIL;
1092     }
1093     if (list.fccListType != listtypeAVIMOVIE)
1094     {
1095         ERR("Expected AVI movie list, but got %.04s\n", (LPSTR)&list.fccListType);
1096         return E_FAIL;
1097     }
1098
1099     IAsyncReader_Length(This->pReader, &total, &avail);
1100
1101     /* FIXME: AVIX files are extended beyond the FOURCC chunk "AVI ", and thus won't be played here,
1102      * once I get one of the files I'll try to fix it */
1103     if (hr == S_OK)
1104     {
1105         This->rtStart = pAviSplit->CurrentChunkOffset = MEDIATIME_FROM_BYTES(pos + sizeof(RIFFLIST));
1106         pos += list.cb + sizeof(RIFFCHUNK);
1107
1108         pAviSplit->EndOfFile = This->rtStop = MEDIATIME_FROM_BYTES(pos);
1109         if (pos > total)
1110         {
1111             ERR("File smaller (%x%08x) then EndOfFile (%x%08x)\n", (DWORD)(total >> 32), (DWORD)total, (DWORD)(pAviSplit->EndOfFile >> 32), (DWORD)pAviSplit->EndOfFile);
1112             return E_FAIL;
1113         }
1114
1115         hr = IAsyncReader_SyncRead(This->pReader, BYTES_FROM_MEDIATIME(pAviSplit->CurrentChunkOffset), sizeof(pAviSplit->CurrentChunk), (BYTE *)&pAviSplit->CurrentChunk);
1116     }
1117
1118     props->cbAlign = 1;
1119     props->cbPrefix = 0;
1120     /* Comrades, prevent shortage of buffers, or you will feel the consequences! DA! */
1121     props->cBuffers = 2 * pAviSplit->Parser.cStreams;
1122
1123     /* Now peek into the idx1 index, if available */
1124     if (hr == S_OK && (total - pos) > sizeof(RIFFCHUNK))
1125     {
1126         memset(&list, 0, sizeof(list));
1127
1128         hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1129         if (list.fcc == ckidAVIOLDINDEX)
1130         {
1131             pAviSplit->oldindex = CoTaskMemRealloc(pAviSplit->oldindex, list.cb + sizeof(RIFFCHUNK));
1132             if (pAviSplit->oldindex)
1133             {
1134                 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(RIFFCHUNK) + list.cb, (BYTE *)pAviSplit->oldindex);
1135                 if (hr == S_OK)
1136                 {
1137                     hr = AVISplitter_ProcessOldIndex(pAviSplit);
1138                 }
1139                 else
1140                 {
1141                     CoTaskMemFree(pAviSplit->oldindex);
1142                     pAviSplit->oldindex = NULL;
1143                     hr = S_OK;
1144                 }
1145             }
1146         }
1147     }
1148
1149     indexes = 0;
1150     for (x = 0; x < pAviSplit->Parser.cStreams; ++x)
1151         if (pAviSplit->streams[x].entries)
1152             ++indexes;
1153
1154     if (indexes)
1155     {
1156         CoTaskMemFree(pAviSplit->oldindex);
1157         pAviSplit->oldindex = NULL;
1158         if (indexes < pAviSplit->Parser.cStreams)
1159         {
1160             /* This error could possible be survived by switching to old type index,
1161              * but I would rather find out why it doesn't find everything here
1162              */
1163             ERR("%d indexes expected, but only have %d\n", indexes, pAviSplit->Parser.cStreams);
1164             indexes = 0;
1165         }
1166     }
1167     else if (!indexes && pAviSplit->oldindex)
1168         indexes = pAviSplit->Parser.cStreams;
1169
1170     if (!indexes && pAviSplit->AviHeader.dwFlags & AVIF_MUSTUSEINDEX)
1171     {
1172         FIXME("No usable index was found!\n");
1173         hr = E_FAIL;
1174     }
1175
1176     /* Now, set up the streams */
1177     if (hr == S_OK)
1178         hr = AVISplitter_InitializeStreams(pAviSplit);
1179
1180     if (hr != S_OK)
1181     {
1182         AVISplitter_Disconnect(pAviSplit);
1183         return E_FAIL;
1184     }
1185
1186     TRACE("AVI File ok\n");
1187
1188     return hr;
1189 }
1190
1191 static HRESULT AVISplitter_Flush(LPVOID iface)
1192 {
1193     AVISplitterImpl *This = (AVISplitterImpl*)iface;
1194     DWORD x;
1195
1196     ERR("(%p)->()\n", This);
1197
1198     for (x = 0; x < This->Parser.cStreams; ++x)
1199     {
1200         StreamData *stream = This->streams + x;
1201
1202         if (stream->sample)
1203             assert(IMediaSample_Release(stream->sample) == 0);
1204         stream->sample = NULL;
1205
1206         ResetEvent(stream->packet_queued);
1207         assert(!stream->thread);
1208     }
1209
1210     return S_OK;
1211 }
1212
1213 static HRESULT AVISplitter_Disconnect(LPVOID iface)
1214 {
1215     AVISplitterImpl *This = iface;
1216     int x;
1217
1218     /* TODO: Remove other memory that's allocated during connect */
1219     CoTaskMemFree(This->oldindex);
1220     This->oldindex = NULL;
1221
1222     for (x = 0; x < This->Parser.cStreams; ++x)
1223     {
1224         int i;
1225
1226         StreamData *stream = &This->streams[x];
1227
1228         for (i = 0; i < stream->entries; ++i)
1229             CoTaskMemFree(stream->stdindex[i]);
1230
1231         CoTaskMemFree(stream->stdindex);
1232         CloseHandle(stream->packet_queued);
1233     }
1234     CoTaskMemFree(This->streams);
1235     This->streams = NULL;
1236     return S_OK;
1237 }
1238
1239 static ULONG WINAPI AVISplitter_Release(IBaseFilter *iface)
1240 {
1241     AVISplitterImpl *This = (AVISplitterImpl *)iface;
1242     ULONG ref;
1243
1244     ref = InterlockedDecrement(&This->Parser.refCount);
1245
1246     TRACE("(%p)->() Release from %d\n", This, ref + 1);
1247
1248     if (!ref)
1249     {
1250         AVISplitter_Flush(This);
1251         Parser_Destroy(&This->Parser);
1252     }
1253
1254     return ref;
1255 }
1256
1257 static HRESULT AVISplitter_seek(IBaseFilter *iface)
1258 {
1259     AVISplitterImpl *This = (AVISplitterImpl *)iface;
1260     PullPin *pPin = This->Parser.pInputPin;
1261     LONGLONG newpos, endpos;
1262     DWORD x;
1263
1264     newpos = This->Parser.mediaSeeking.llCurrent;
1265     endpos = This->Parser.mediaSeeking.llDuration;
1266
1267     if (newpos > endpos)
1268     {
1269         WARN("Requesting position %x%08x beyond end of stream %x%08x\n", (DWORD)(newpos>>32), (DWORD)newpos, (DWORD)(endpos>>32), (DWORD)endpos);
1270         return E_INVALIDARG;
1271     }
1272
1273     FIXME("Moving position to %u.%03u s!\n", (DWORD)(newpos / 10000000), (DWORD)((newpos / 10000)%1000));
1274
1275     EnterCriticalSection(&pPin->thread_lock);
1276     /* Send a flush to all output pins */
1277     IPin_BeginFlush((IPin *)pPin);
1278
1279     /* Make sure this is done while stopped, BeginFlush takes care of this */
1280     EnterCriticalSection(&This->Parser.csFilter);
1281     for (x = 0; x < This->Parser.cStreams; ++x)
1282     {
1283         Parser_OutputPin *pin = (Parser_OutputPin *)This->Parser.ppPins[1+x];
1284         StreamData *stream = This->streams + x;
1285         IPin *victim = NULL;
1286         LONGLONG wanted_frames;
1287         DWORD last_keyframe = 0, last_keyframeidx = 0, preroll = 0;
1288
1289         wanted_frames = newpos;
1290         wanted_frames *= stream->streamheader.dwRate;
1291         wanted_frames /= 10000000;
1292         wanted_frames /= stream->streamheader.dwScale;
1293
1294         IPin_ConnectedTo((IPin *)pin, &victim);
1295         if (victim)
1296         {
1297             IPin_NewSegment(victim, newpos, endpos, pPin->dRate);
1298             IPin_Release(victim);
1299         }
1300
1301         pin->dwSamplesProcessed = 0;
1302         stream->index = 0;
1303         stream->pos = 0;
1304         stream->seek = 1;
1305         if (stream->stdindex)
1306         {
1307             DWORD y, z = 0;
1308
1309             for (y = 0; y < stream->entries; ++y)
1310             {
1311                 for (z = 0; z < stream->stdindex[y]->nEntriesInUse; ++z)
1312                 {
1313                     if (stream->streamheader.dwSampleSize)
1314                     {
1315                         ULONG len = stream->stdindex[y]->aIndex[z].dwSize & ~(1 << 31);
1316                         ULONG size = stream->streamheader.dwSampleSize;
1317
1318                         pin->dwSamplesProcessed += len / size;
1319                         if (len % size)
1320                             ++pin->dwSamplesProcessed;
1321                     }
1322                     else ++pin->dwSamplesProcessed;
1323
1324                     if (!(stream->stdindex[y]->aIndex[z].dwSize >> 31))
1325                     {
1326                         last_keyframe = z;
1327                         last_keyframeidx = y;
1328                         preroll = 0;
1329                     }
1330                     else
1331                         ++preroll;
1332
1333                     if (pin->dwSamplesProcessed >= wanted_frames)
1334                         break;
1335                 }
1336                 if (pin->dwSamplesProcessed >= wanted_frames)
1337                     break;
1338             }
1339             stream->index = last_keyframeidx;
1340             stream->pos = last_keyframe;
1341         }
1342         else
1343         {
1344             DWORD nMax, n;
1345             nMax = This->oldindex->cb / sizeof(This->oldindex->aIndex[0]);
1346
1347             for (n = 0; n < nMax; ++n)
1348             {
1349                 DWORD streamId = StreamFromFOURCC(This->oldindex->aIndex[n].dwChunkId);
1350                 if (streamId != x)
1351                     continue;
1352
1353                 if (stream->streamheader.dwSampleSize)
1354                 {
1355                     ULONG len = This->oldindex->aIndex[n].dwSize;
1356                     ULONG size = stream->streamheader.dwSampleSize;
1357
1358                     pin->dwSamplesProcessed += len / size;
1359                     if (len % size)
1360                         ++pin->dwSamplesProcessed;
1361                 }
1362                 else ++pin->dwSamplesProcessed;
1363
1364                 if (This->oldindex->aIndex[n].dwFlags & AVIIF_KEYFRAME)
1365                 {
1366                     last_keyframe = n;
1367                     preroll = 0;
1368                 }
1369                 else
1370                     ++preroll;
1371
1372                 if (pin->dwSamplesProcessed >= wanted_frames)
1373                     break;
1374             }
1375             assert(n < nMax);
1376             stream->pos = last_keyframe;
1377             stream->index = 0;
1378         }
1379         stream->preroll = preroll;
1380         stream->seek = 1;
1381     }
1382     LeaveCriticalSection(&This->Parser.csFilter);
1383
1384     TRACE("Done flushing\n");
1385     IPin_EndFlush((IPin *)pPin);
1386     LeaveCriticalSection(&pPin->thread_lock);
1387
1388     return S_OK;
1389 }
1390
1391 static const IBaseFilterVtbl AVISplitterImpl_Vtbl =
1392 {
1393     Parser_QueryInterface,
1394     Parser_AddRef,
1395     AVISplitter_Release,
1396     Parser_GetClassID,
1397     Parser_Stop,
1398     Parser_Pause,
1399     Parser_Run,
1400     Parser_GetState,
1401     Parser_SetSyncSource,
1402     Parser_GetSyncSource,
1403     Parser_EnumPins,
1404     Parser_FindPin,
1405     Parser_QueryFilterInfo,
1406     Parser_JoinFilterGraph,
1407     Parser_QueryVendorInfo
1408 };
1409
1410 HRESULT AVISplitter_create(IUnknown * pUnkOuter, LPVOID * ppv)
1411 {
1412     HRESULT hr;
1413     AVISplitterImpl * This;
1414
1415     TRACE("(%p, %p)\n", pUnkOuter, ppv);
1416
1417     *ppv = NULL;
1418
1419     if (pUnkOuter)
1420         return CLASS_E_NOAGGREGATION;
1421
1422     /* Note: This memory is managed by the transform filter once created */
1423     This = CoTaskMemAlloc(sizeof(AVISplitterImpl));
1424
1425     This->streams = NULL;
1426     This->oldindex = NULL;
1427
1428     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);
1429
1430     if (FAILED(hr))
1431         return hr;
1432
1433     *ppv = (LPVOID)This;
1434
1435     return hr;
1436 }