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