push a68a33e62d41ba03b0e27371e671eaa1e09ebd44
[wine/hacks.git] / dlls / quartz / avisplit.c
blobe712eb9b17701f5284508669c260d95db3542af8
1 /*
2 * AVI Splitter Filter
4 * Copyright 2003 Robert Shearman
5 * Copyright 2004-2005 Christian Costa
6 * Copyright 2008 Maarten Lankhorst
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.
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.
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
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.
32 #include "quartz_private.h"
33 #include "control_private.h"
34 #include "pin.h"
36 #include "uuids.h"
37 #include "vfw.h"
38 #include "aviriff.h"
39 #include "vfwmsgs.h"
40 #include "amvideo.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
45 #include <math.h>
46 #include <assert.h>
48 #include "parser.h"
50 #define TWOCCFromFOURCC(fcc) HIWORD(fcc)
52 /* four character codes used in AVI files */
53 #define ckidINFO mmioFOURCC('I','N','F','O')
54 #define ckidREC mmioFOURCC('R','E','C',' ')
56 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
58 typedef struct StreamData
60 DWORD dwSampleSize;
61 FLOAT fSamplesPerSec;
62 DWORD dwLength;
64 AVISTREAMHEADER streamheader;
65 DWORD entries;
66 AVISTDINDEX **stdindex;
67 DWORD frames;
68 DWORD seek;
70 /* Position, in index units */
71 DWORD pos, pos_next, index, index_next;
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.
77 HANDLE thread, packet_queued;
78 IMediaSample *sample;
80 /* Amount of preroll samples for this stream */
81 DWORD preroll;
82 } StreamData;
84 typedef struct AVISplitterImpl
86 ParserImpl Parser;
87 RIFFCHUNK CurrentChunk;
88 LONGLONG CurrentChunkOffset; /* in media time */
89 LONGLONG EndOfFile;
90 AVIMAINHEADER AviHeader;
91 AVIEXTHEADER ExtHeader;
93 AVIOLDINDEX *oldindex;
94 DWORD offset;
96 StreamData *streams;
97 } AVISplitterImpl;
99 struct thread_args {
100 AVISplitterImpl *This;
101 DWORD stream;
104 /* The threading stuff cries for an explanation
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.
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.
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
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.
124 static HRESULT AVISplitter_SendEndOfFile(AVISplitterImpl *This, DWORD streamnumber)
126 IPin* ppin = NULL;
127 HRESULT hr;
129 TRACE("End of file reached\n");
131 hr = IPin_ConnectedTo(This->Parser.ppPins[streamnumber+1], &ppin);
132 if (SUCCEEDED(hr))
134 hr = IPin_EndOfStream(ppin);
135 IPin_Release(ppin);
137 TRACE("--> %x\n", hr);
139 /* Force the pullpin thread to stop */
140 return S_FALSE;
143 /* Thread worker horse */
144 static HRESULT AVISplitter_next_request(AVISplitterImpl *This, DWORD streamnumber)
146 StreamData *stream = This->streams + streamnumber;
147 PullPin *pin = This->Parser.pInputPin;
148 IMediaSample *sample = NULL;
149 HRESULT hr;
151 TRACE("(%p, %u)->()\n", This, streamnumber);
153 hr = IMemAllocator_GetBuffer(pin->pAlloc, &sample, NULL, NULL, 0);
154 if (hr != S_OK)
155 ERR("... %08x?\n", hr);
157 if (SUCCEEDED(hr))
159 LONGLONG rtSampleStart;
160 /* Add 4 for the next header, which should hopefully work */
161 LONGLONG rtSampleStop;
163 stream->pos = stream->pos_next;
164 stream->index = stream->index_next;
166 IMediaSample_SetDiscontinuity(sample, stream->seek);
167 stream->seek = FALSE;
168 if (stream->preroll)
170 --stream->preroll;
171 IMediaSample_SetPreroll(sample, TRUE);
173 else
174 IMediaSample_SetPreroll(sample, FALSE);
175 IMediaSample_SetSyncPoint(sample, TRUE);
177 if (stream->stdindex)
179 AVISTDINDEX *index = stream->stdindex[stream->index];
180 AVISTDINDEX_ENTRY *entry = &index->aIndex[stream->pos];
181 BOOL keyframe;
183 /* End of file */
184 if (stream->index >= stream->entries)
186 ERR("END OF STREAM ON %u\n", streamnumber);
187 IMediaSample_Release(sample);
188 return S_FALSE;
191 rtSampleStart = index->qwBaseOffset;
192 keyframe = !(entry->dwSize >> 31);
193 rtSampleStart += entry->dwOffset;
194 rtSampleStart = MEDIATIME_FROM_BYTES(rtSampleStart);
196 ++stream->pos_next;
197 if (index->nEntriesInUse == stream->pos_next)
199 stream->pos_next = 0;
200 ++stream->index_next;
203 rtSampleStop = rtSampleStart + MEDIATIME_FROM_BYTES(entry->dwSize & ~(1 << 31));
205 TRACE("offset(%u) size(%u)\n", (DWORD)BYTES_FROM_MEDIATIME(rtSampleStart), (DWORD)BYTES_FROM_MEDIATIME(rtSampleStop - rtSampleStart));
207 else if (This->oldindex)
209 DWORD flags = This->oldindex->aIndex[stream->pos].dwFlags;
210 DWORD size = This->oldindex->aIndex[stream->pos].dwSize;
211 BOOL keyframe;
213 /* End of file */
214 if (stream->index)
216 IMediaSample_Release(sample);
217 ERR("END OF STREAM ON %u\n", streamnumber);
218 return S_FALSE;
221 keyframe = !!(flags & AVIIF_KEYFRAME);
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)
228 FIXME("Only stand alone frames are currently handled correctly!\n");
230 if (flags & AVIIF_LIST)
232 FIXME("Not sure if this is handled correctly\n");
233 rtSampleStart += MEDIATIME_FROM_BYTES(sizeof(RIFFLIST));
234 rtSampleStop += MEDIATIME_FROM_BYTES(sizeof(RIFFLIST));
236 else
238 rtSampleStart += MEDIATIME_FROM_BYTES(sizeof(RIFFCHUNK));
239 rtSampleStop += MEDIATIME_FROM_BYTES(sizeof(RIFFCHUNK));
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);
248 /* End of file soon */
249 if (stream->pos_next * sizeof(This->oldindex->aIndex[0]) >= This->oldindex->cb)
251 stream->pos_next = 0;
252 ++stream->index_next;
255 else /* TODO: Generate an index automagically */
257 ERR("CAN'T PLAY WITHOUT AN INDEX! SOS! SOS! SOS!\n");
258 assert(0);
261 if (rtSampleStart != rtSampleStop)
263 hr = IMediaSample_SetTime(sample, &rtSampleStart, &rtSampleStop);
265 hr = IAsyncReader_Request(pin->pReader, sample, streamnumber);
267 if (FAILED(hr))
268 assert(IMediaSample_Release(sample) == 0);
270 else
272 stream->sample = sample;
273 IMediaSample_SetActualDataLength(sample, 0);
274 SetEvent(stream->packet_queued);
277 else
279 if (sample)
281 ERR("There should be no sample!\n");
282 assert(IMediaSample_Release(sample) == 0);
285 TRACE("--> %08x\n", hr);
287 return hr;
290 static HRESULT AVISplitter_Receive(AVISplitterImpl *This, IMediaSample *sample, DWORD streamnumber)
292 Parser_OutputPin *pin = (Parser_OutputPin *)This->Parser.ppPins[1+streamnumber];
293 HRESULT hr;
294 LONGLONG start, stop;
295 StreamData *stream = &This->streams[streamnumber];
297 start = pin->dwSamplesProcessed;
298 start *= stream->streamheader.dwScale;
299 start *= 10000000;
300 start /= stream->streamheader.dwRate;
302 if (stream->streamheader.dwSampleSize)
304 ULONG len = IMediaSample_GetActualDataLength(sample);
305 ULONG size = stream->streamheader.dwSampleSize;
307 pin->dwSamplesProcessed += len / size;
309 else
310 ++pin->dwSamplesProcessed;
312 stop = pin->dwSamplesProcessed;
313 stop *= stream->streamheader.dwScale;
314 stop *= 10000000;
315 stop /= stream->streamheader.dwRate;
317 IMediaSample_SetTime(sample, &start, &stop);
319 hr = OutputPin_SendSample(&pin->pin, sample);
321 /* Uncomment this if you want to debug the time differences between the
322 * different streams, it is useful for that
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));
328 return hr;
331 static DWORD WINAPI AVISplitter_thread_reader(LPVOID data)
333 struct thread_args *args = data;
334 AVISplitterImpl *This = args->This;
335 DWORD streamnumber = args->stream;
336 HRESULT hr = S_OK;
340 HRESULT nexthr = S_FALSE;
341 IMediaSample *sample;
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;
349 nexthr = AVISplitter_next_request(This, streamnumber);
351 hr = AVISplitter_Receive(This, sample, streamnumber);
352 if (hr != S_OK)
353 FIXME("Receiving error: %08x\n", hr);
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);
362 FIXME("Thread %u terminated with hr %08x!\n", streamnumber, hr);
364 return hr;
367 static HRESULT AVISplitter_Sample(LPVOID iface, IMediaSample * pSample, DWORD_PTR cookie)
369 AVISplitterImpl *This = iface;
370 StreamData *stream = This->streams + cookie;
371 HRESULT hr = S_OK;
373 if (!IMediaSample_GetActualDataLength(pSample))
375 ERR("Received empty sample\n");
376 return S_OK;
379 /* Send the sample to whatever thread is appropiate
380 * That thread should also not have a sample queued at the moment
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);
388 IMediaSample_AddRef(pSample);
390 stream->sample = pSample;
391 SetEvent(stream->packet_queued);
393 return hr;
396 static HRESULT AVISplitter_done_process(LPVOID iface);
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
402 static HRESULT AVISplitter_first_request(LPVOID iface)
404 AVISplitterImpl *This = (AVISplitterImpl *)iface;
405 HRESULT hr = S_OK;
406 int x;
407 IMediaSample *sample = NULL;
408 BOOL have_sample = FALSE;
410 TRACE("(%p)->()\n", This);
412 for (x = 0; x < This->Parser.cStreams; ++x)
414 StreamData *stream = This->streams + x;
416 /* Nothing should be running at this point */
417 assert(!stream->thread);
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);
424 stream->pos_next = stream->pos;
425 stream->index_next = stream->index;
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
434 if (have_sample)
436 DWORD_PTR dwUser = ~0;
437 hr = IAsyncReader_WaitForNext(This->Parser.pInputPin->pReader, 10000, &sample, &dwUser);
438 assert(hr == S_OK);
439 assert(sample);
441 AVISplitter_Sample(iface, sample, dwUser);
442 IMediaSample_Release(sample);
445 hr = AVISplitter_next_request(This, x);
446 TRACE("-->%08x\n", hr);
448 /* Could be an EOF instead */
449 have_sample = (hr == S_OK);
450 if (FAILED(hr))
451 break;
454 /* FIXME: Don't do this for each pin that sent an EOF */
455 for (x = 0; x < This->Parser.cStreams && SUCCEEDED(hr); ++x)
457 struct thread_args *args;
458 DWORD tid;
460 if ((This->streams[x].stdindex && This->streams[x].index_next >= This->streams[x].entries) ||
461 (!This->streams[x].stdindex && This->streams[x].index_next))
463 This->streams[x].thread = NULL;
464 continue;
467 args = CoTaskMemAlloc(sizeof(*args));
468 args->This = This;
469 args->stream = x;
470 This->streams[x].thread = CreateThread(NULL, 0, AVISplitter_thread_reader, args, 0, &tid);
471 FIXME("Created stream %u thread 0x%08x\n", x, tid);
474 if (FAILED(hr))
475 ERR("Horsemen of the apocalypse came to bring error 0x%08x\n", hr);
477 return hr;
480 static HRESULT AVISplitter_done_process(LPVOID iface)
482 AVISplitterImpl *This = iface;
484 DWORD x;
486 for (x = 0; x < This->Parser.cStreams; ++x)
488 StreamData *stream = This->streams + x;
490 FIXME("Waiting for %u to terminate\n", x);
491 /* Make the thread return first */
492 SetEvent(stream->packet_queued);
493 assert(WaitForSingleObject(stream->thread, 100000) != WAIT_TIMEOUT);
494 CloseHandle(stream->thread);
495 stream->thread = NULL;
497 if (stream->sample)
498 assert(IMediaSample_Release(stream->sample) == 0);
499 stream->sample = NULL;
501 ResetEvent(stream->packet_queued);
504 return S_OK;
507 static HRESULT AVISplitter_QueryAccept(LPVOID iface, const AM_MEDIA_TYPE * pmt)
509 if (IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream) && IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_Avi))
510 return S_OK;
511 return S_FALSE;
514 static HRESULT AVISplitter_ProcessIndex(AVISplitterImpl *This, AVISTDINDEX **index, LONGLONG qwOffset, DWORD cb)
516 AVISTDINDEX *pIndex;
517 int x;
518 long rest;
520 *index = NULL;
521 if (cb < sizeof(AVISTDINDEX))
523 FIXME("size %u too small\n", cb);
524 return E_INVALIDARG;
527 pIndex = CoTaskMemAlloc(cb);
528 if (!pIndex)
529 return E_OUTOFMEMORY;
531 IAsyncReader_SyncRead(((PullPin *)This->Parser.ppPins[0])->pReader, qwOffset, cb, (BYTE *)pIndex);
532 pIndex = CoTaskMemRealloc(pIndex, pIndex->cb);
533 if (!pIndex)
534 return E_OUTOFMEMORY;
536 IAsyncReader_SyncRead(((PullPin *)This->Parser.ppPins[0])->pReader, qwOffset, pIndex->cb, (BYTE *)pIndex);
537 rest = pIndex->cb - sizeof(AVISUPERINDEX) + sizeof(RIFFCHUNK) + sizeof(pIndex->aIndex[0]) * ANYSIZE_ARRAY;
539 TRACE("FOURCC: %s\n", debugstr_an((char *)&pIndex->fcc, 4));
540 TRACE("wLongsPerEntry: %hd\n", pIndex->wLongsPerEntry);
541 TRACE("bIndexSubType: %hd\n", pIndex->bIndexSubType);
542 TRACE("bIndexType: %hd\n", pIndex->bIndexType);
543 TRACE("nEntriesInUse: %u\n", pIndex->nEntriesInUse);
544 TRACE("dwChunkId: %.4s\n", (char *)&pIndex->dwChunkId);
545 TRACE("qwBaseOffset: %x%08x\n", (DWORD)(pIndex->qwBaseOffset >> 32), (DWORD)pIndex->qwBaseOffset);
546 TRACE("dwReserved_3: %u\n", pIndex->dwReserved_3);
548 if (pIndex->bIndexType != AVI_INDEX_OF_CHUNKS
549 || pIndex->wLongsPerEntry != 2
550 || rest < (pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry)
551 || (pIndex->bIndexSubType != AVI_INDEX_SUB_DEFAULT))
553 FIXME("Invalid index chunk encountered\n");
554 return E_INVALIDARG;
557 for (x = 0; x < pIndex->nEntriesInUse; ++x)
559 BOOL keyframe = !(pIndex->aIndex[x].dwSize >> 31);
560 DWORDLONG offset = pIndex->qwBaseOffset + pIndex->aIndex[x].dwOffset;
561 TRACE("dwOffset: %x%08x\n", (DWORD)(offset >> 32), (DWORD)offset);
562 TRACE("dwSize: %u\n", (pIndex->aIndex[x].dwSize & ~(1<<31)));
563 TRACE("Frame is a keyframe: %s\n", keyframe ? "yes" : "no");
566 *index = pIndex;
567 return S_OK;
570 static HRESULT AVISplitter_ProcessOldIndex(AVISplitterImpl *This)
572 ULONGLONG mov_pos = BYTES_FROM_MEDIATIME(This->CurrentChunkOffset) - sizeof(DWORD);
573 AVIOLDINDEX *pAviOldIndex = This->oldindex;
574 int relative = -1;
575 int x;
577 for (x = 0; x < pAviOldIndex->cb / sizeof(pAviOldIndex->aIndex[0]); ++x)
579 DWORD temp, temp2 = 0, offset, chunkid;
580 PullPin *pin = This->Parser.pInputPin;
582 offset = pAviOldIndex->aIndex[x].dwOffset;
583 chunkid = pAviOldIndex->aIndex[x].dwChunkId;
585 TRACE("dwChunkId: %.4s\n", (char *)&chunkid);
586 TRACE("dwFlags: %08x\n", pAviOldIndex->aIndex[x].dwFlags);
587 TRACE("dwOffset (%s): %08x\n", relative ? "relative" : "absolute", offset);
588 TRACE("dwSize: %08x\n", pAviOldIndex->aIndex[x].dwSize);
590 /* Only scan once, or else this will take too long */
591 if (relative == -1)
593 IAsyncReader_SyncRead(pin->pReader, offset, sizeof(DWORD), (BYTE *)&temp);
594 relative = (chunkid != temp);
596 if (chunkid == mmioFOURCC('7','F','x','x')
597 && ((char *)&temp)[0] == 'i' && ((char *)&temp)[1] == 'x')
598 relative = FALSE;
600 if (relative)
602 if (offset + mov_pos < BYTES_FROM_MEDIATIME(This->EndOfFile))
603 IAsyncReader_SyncRead(pin->pReader, offset + mov_pos, sizeof(DWORD), (BYTE *)&temp2);
605 if (chunkid == mmioFOURCC('7','F','x','x')
606 && ((char *)&temp2)[0] == 'i' && ((char *)&temp2)[1] == 'x')
608 /* Do nothing, all is great */
610 else if (temp2 != chunkid)
612 ERR("Faulty index or bug in handling: Wanted FCC: %s, Abs FCC: %s (@ %x), Rel FCC: %s (@ %.0x%08x)\n",
613 debugstr_an((char *)&chunkid, 4), debugstr_an((char *)&temp, 4), offset,
614 debugstr_an((char *)&temp2, 4), (DWORD)((mov_pos + offset) >> 32), (DWORD)(mov_pos + offset));
615 relative = -1;
617 else
618 TRACE("Scanned dwChunkId: %s\n", debugstr_an((char *)&temp2, 4));
620 else if (!relative)
621 TRACE("Scanned dwChunkId: %s\n", debugstr_an((char *)&temp, 4));
623 /* Only dump one packet */
624 else break;
627 if (relative == -1)
629 FIXME("Dropping index: no idea whether it is relative or absolute\n");
630 CoTaskMemFree(This->oldindex);
631 This->oldindex = NULL;
633 else if (!relative)
634 This->offset = 0;
635 else
636 This->offset = (DWORD)mov_pos;
638 return S_OK;
641 static HRESULT AVISplitter_ProcessStreamList(AVISplitterImpl * This, const BYTE * pData, DWORD cb, ALLOCATOR_PROPERTIES *props)
643 PIN_INFO piOutput;
644 const RIFFCHUNK * pChunk;
645 HRESULT hr;
646 AM_MEDIA_TYPE amt;
647 float fSamplesPerSec = 0.0f;
648 DWORD dwSampleSize = 0;
649 DWORD dwLength = 0;
650 DWORD nstdindex = 0;
651 static const WCHAR wszStreamTemplate[] = {'S','t','r','e','a','m',' ','%','0','2','d',0};
652 StreamData *stream;
654 ZeroMemory(&amt, sizeof(amt));
655 piOutput.dir = PINDIR_OUTPUT;
656 piOutput.pFilter = (IBaseFilter *)This;
657 wsprintfW(piOutput.achName, wszStreamTemplate, This->Parser.cStreams);
658 This->streams = CoTaskMemRealloc(This->streams, sizeof(StreamData) * (This->Parser.cStreams+1));
659 stream = This->streams + This->Parser.cStreams;
660 ZeroMemory(stream, sizeof(*stream));
662 for (pChunk = (const RIFFCHUNK *)pData;
663 ((const BYTE *)pChunk >= pData) && ((const BYTE *)pChunk + sizeof(RIFFCHUNK) < pData + cb) && (pChunk->cb > 0);
664 pChunk = (const RIFFCHUNK *)((const BYTE*)pChunk + sizeof(RIFFCHUNK) + pChunk->cb)
667 switch (pChunk->fcc)
669 case ckidSTREAMHEADER:
671 const AVISTREAMHEADER * pStrHdr = (const AVISTREAMHEADER *)pChunk;
672 TRACE("processing stream header\n");
673 stream->streamheader = *pStrHdr;
675 fSamplesPerSec = (float)pStrHdr->dwRate / (float)pStrHdr->dwScale;
676 CoTaskMemFree(amt.pbFormat);
677 amt.pbFormat = NULL;
678 amt.cbFormat = 0;
680 switch (pStrHdr->fccType)
682 case streamtypeVIDEO:
683 amt.formattype = FORMAT_VideoInfo;
684 break;
685 case streamtypeAUDIO:
686 amt.formattype = FORMAT_WaveFormatEx;
687 break;
688 default:
689 FIXME("fccType %.4s not handled yet\n", (char *)&pStrHdr->fccType);
690 amt.formattype = FORMAT_None;
692 amt.majortype = MEDIATYPE_Video;
693 amt.majortype.Data1 = pStrHdr->fccType;
694 amt.subtype = MEDIATYPE_Video;
695 amt.subtype.Data1 = pStrHdr->fccHandler;
696 TRACE("Subtype FCC: %.04s\n", (LPCSTR)&pStrHdr->fccHandler);
697 amt.lSampleSize = pStrHdr->dwSampleSize;
698 amt.bFixedSizeSamples = (amt.lSampleSize != 0);
700 /* FIXME: Is this right? */
701 if (!amt.lSampleSize)
703 amt.lSampleSize = 1;
704 dwSampleSize = 1;
707 amt.bTemporalCompression = IsEqualGUID(&amt.majortype, &MEDIATYPE_Video); /* FIXME? */
708 dwSampleSize = pStrHdr->dwSampleSize;
709 dwLength = pStrHdr->dwLength;
710 if (!dwLength)
711 dwLength = This->AviHeader.dwTotalFrames;
713 if (pStrHdr->dwSuggestedBufferSize && pStrHdr->dwSuggestedBufferSize > props->cbBuffer)
714 props->cbBuffer = pStrHdr->dwSuggestedBufferSize;
716 break;
718 case ckidSTREAMFORMAT:
719 TRACE("processing stream format data\n");
720 if (IsEqualIID(&amt.formattype, &FORMAT_VideoInfo))
722 VIDEOINFOHEADER * pvi;
723 /* biCompression member appears to override the value in the stream header.
724 * i.e. the stream header can say something completely contradictory to what
725 * is in the BITMAPINFOHEADER! */
726 if (pChunk->cb < sizeof(BITMAPINFOHEADER))
728 ERR("Not enough bytes for BITMAPINFOHEADER\n");
729 return E_FAIL;
731 amt.cbFormat = sizeof(VIDEOINFOHEADER) - sizeof(BITMAPINFOHEADER) + pChunk->cb;
732 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
733 ZeroMemory(amt.pbFormat, amt.cbFormat);
734 pvi = (VIDEOINFOHEADER *)amt.pbFormat;
735 pvi->AvgTimePerFrame = (LONGLONG)(10000000.0 / fSamplesPerSec);
737 CopyMemory(&pvi->bmiHeader, (const BYTE *)(pChunk + 1), pChunk->cb);
738 if (pvi->bmiHeader.biCompression)
739 amt.subtype.Data1 = pvi->bmiHeader.biCompression;
741 else if (IsEqualIID(&amt.formattype, &FORMAT_WaveFormatEx))
743 amt.cbFormat = pChunk->cb;
744 if (amt.cbFormat < sizeof(WAVEFORMATEX))
745 amt.cbFormat = sizeof(WAVEFORMATEX);
746 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
747 ZeroMemory(amt.pbFormat, amt.cbFormat);
748 CopyMemory(amt.pbFormat, (const BYTE *)(pChunk + 1), pChunk->cb);
750 else
752 amt.cbFormat = pChunk->cb;
753 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
754 CopyMemory(amt.pbFormat, (const BYTE *)(pChunk + 1), amt.cbFormat);
756 break;
757 case ckidSTREAMNAME:
758 TRACE("processing stream name\n");
759 /* FIXME: this doesn't exactly match native version (we omit the "##)" prefix), but hey... */
760 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)(pChunk + 1), pChunk->cb, piOutput.achName, sizeof(piOutput.achName) / sizeof(piOutput.achName[0]));
761 break;
762 case ckidSTREAMHANDLERDATA:
763 FIXME("process stream handler data\n");
764 break;
765 case ckidAVIPADDING:
766 TRACE("JUNK chunk ignored\n");
767 break;
768 case ckidAVISUPERINDEX:
770 const AVISUPERINDEX *pIndex = (const AVISUPERINDEX *)pChunk;
771 int x;
772 long rest = pIndex->cb - sizeof(AVISUPERINDEX) + sizeof(RIFFCHUNK) + sizeof(pIndex->aIndex[0]) * ANYSIZE_ARRAY;
774 if (pIndex->cb < sizeof(AVISUPERINDEX) - sizeof(RIFFCHUNK))
776 FIXME("size %u\n", pIndex->cb);
777 break;
780 if (nstdindex++ > 0)
782 ERR("Stream %d got more than 1 superindex?\n", This->Parser.cStreams);
783 break;
786 TRACE("wLongsPerEntry: %hd\n", pIndex->wLongsPerEntry);
787 TRACE("bIndexSubType: %hd\n", pIndex->bIndexSubType);
788 TRACE("bIndexType: %hd\n", pIndex->bIndexType);
789 TRACE("nEntriesInUse: %u\n", pIndex->nEntriesInUse);
790 TRACE("dwChunkId: %.4s\n", (char *)&pIndex->dwChunkId);
791 if (pIndex->dwReserved[0])
792 TRACE("dwReserved[0]: %u\n", pIndex->dwReserved[0]);
793 if (pIndex->dwReserved[2])
794 TRACE("dwReserved[1]: %u\n", pIndex->dwReserved[1]);
795 if (pIndex->dwReserved[2])
796 TRACE("dwReserved[2]: %u\n", pIndex->dwReserved[2]);
798 if (pIndex->bIndexType != AVI_INDEX_OF_INDEXES
799 || pIndex->wLongsPerEntry != 4
800 || rest < (pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry)
801 || (pIndex->bIndexSubType != AVI_INDEX_SUB_2FIELD && pIndex->bIndexSubType != AVI_INDEX_SUB_DEFAULT))
803 FIXME("Invalid index chunk encountered\n");
804 break;
807 stream->entries = pIndex->nEntriesInUse;
808 stream->stdindex = CoTaskMemRealloc(stream->stdindex, sizeof(*stream->stdindex) * stream->entries);
809 for (x = 0; x < pIndex->nEntriesInUse; ++x)
811 TRACE("qwOffset: %x%08x\n", (DWORD)(pIndex->aIndex[x].qwOffset >> 32), (DWORD)pIndex->aIndex[x].qwOffset);
812 TRACE("dwSize: %u\n", pIndex->aIndex[x].dwSize);
813 TRACE("dwDuration: %u (unreliable)\n", pIndex->aIndex[x].dwDuration);
815 AVISplitter_ProcessIndex(This, &stream->stdindex[nstdindex-1], pIndex->aIndex[x].qwOffset, pIndex->aIndex[x].dwSize);
817 break;
819 default:
820 FIXME("unknown chunk type \"%.04s\" ignored\n", (LPCSTR)&pChunk->fcc);
824 if (IsEqualGUID(&amt.formattype, &FORMAT_WaveFormatEx))
826 amt.subtype = MEDIATYPE_Video;
827 amt.subtype.Data1 = ((WAVEFORMATEX *)amt.pbFormat)->wFormatTag;
830 dump_AM_MEDIA_TYPE(&amt);
831 TRACE("fSamplesPerSec = %f\n", (double)fSamplesPerSec);
832 TRACE("dwSampleSize = %x\n", dwSampleSize);
833 TRACE("dwLength = %x\n", dwLength);
835 stream->fSamplesPerSec = fSamplesPerSec;
836 stream->dwSampleSize = dwSampleSize;
837 stream->dwLength = dwLength; /* TODO: Use this for mediaseeking */
838 stream->packet_queued = CreateEventW(NULL, 0, 0, NULL);
840 hr = Parser_AddPin(&(This->Parser), &piOutput, props, &amt);
841 CoTaskMemFree(amt.pbFormat);
844 return hr;
847 static HRESULT AVISplitter_ProcessODML(AVISplitterImpl * This, const BYTE * pData, DWORD cb)
849 const RIFFCHUNK * pChunk;
851 for (pChunk = (const RIFFCHUNK *)pData;
852 ((const BYTE *)pChunk >= pData) && ((const BYTE *)pChunk + sizeof(RIFFCHUNK) < pData + cb) && (pChunk->cb > 0);
853 pChunk = (const RIFFCHUNK *)((const BYTE*)pChunk + sizeof(RIFFCHUNK) + pChunk->cb)
856 switch (pChunk->fcc)
858 case ckidAVIEXTHEADER:
860 int x;
861 const AVIEXTHEADER * pExtHdr = (const AVIEXTHEADER *)pChunk;
863 TRACE("processing extension header\n");
864 if (pExtHdr->cb != sizeof(AVIEXTHEADER) - sizeof(RIFFCHUNK))
866 FIXME("Size: %u\n", pExtHdr->cb);
867 break;
869 TRACE("dwGrandFrames: %u\n", pExtHdr->dwGrandFrames);
870 for (x = 0; x < 61; ++x)
871 if (pExtHdr->dwFuture[x])
872 FIXME("dwFuture[%i] = %u (0x%08x)\n", x, pExtHdr->dwFuture[x], pExtHdr->dwFuture[x]);
873 This->ExtHeader = *pExtHdr;
874 break;
876 default:
877 FIXME("unknown chunk type \"%.04s\" ignored\n", (LPCSTR)&pChunk->fcc);
881 return S_OK;
884 static HRESULT AVISplitter_InitializeStreams(AVISplitterImpl *This)
886 int x;
888 if (This->oldindex)
890 DWORD nMax, n;
892 for (x = 0; x < This->Parser.cStreams; ++x)
894 This->streams[x].frames = 0;
895 This->streams[x].pos = ~0;
896 This->streams[x].index = 0;
899 nMax = This->oldindex->cb / sizeof(This->oldindex->aIndex[0]);
901 /* Ok, maybe this is more of an excercise to see if I interpret everything correctly or not, but that is useful for now. */
902 for (n = 0; n < nMax; ++n)
904 DWORD streamId = StreamFromFOURCC(This->oldindex->aIndex[n].dwChunkId);
905 if (streamId >= This->Parser.cStreams)
907 FIXME("Stream id %s ignored\n", debugstr_an((char*)&This->oldindex->aIndex[n].dwChunkId, 4));
908 continue;
910 if (This->streams[streamId].pos == ~0)
911 This->streams[streamId].pos = n;
913 if (This->streams[streamId].streamheader.dwSampleSize)
914 This->streams[streamId].frames += This->oldindex->aIndex[n].dwSize / This->streams[streamId].streamheader.dwSampleSize;
915 else
916 ++This->streams[streamId].frames;
919 for (x = 0; x < This->Parser.cStreams; ++x)
921 if ((DWORD)This->streams[x].frames != This->streams[x].streamheader.dwLength)
923 FIXME("stream %u: frames found: %u, frames meant to be found: %u\n", x, (DWORD)This->streams[x].frames, This->streams[x].streamheader.dwLength);
928 else if (!This->streams[0].entries)
930 for (x = 0; x < This->Parser.cStreams; ++x)
932 This->streams[x].frames = This->streams[x].streamheader.dwLength;
934 /* MS Avi splitter does seek through the whole file, we should! */
935 ERR("We should be manually seeking through the entire file to build an index, because the index is missing!!!\n");
936 return E_NOTIMPL;
939 /* Not much here yet */
940 for (x = 0; x < This->Parser.cStreams; ++x)
942 StreamData *stream = This->streams + x;
943 int y;
944 DWORD64 frames = 0;
946 stream->seek = 1;
948 if (stream->stdindex)
950 stream->index = 0;
951 stream->pos = 0;
952 for (y = 0; y < stream->entries; ++y)
954 if (stream->streamheader.dwSampleSize)
956 int z;
958 for (z = 0; z < stream->stdindex[y]->nEntriesInUse; ++z)
960 UINT len = stream->stdindex[y]->aIndex[z].dwSize & ~(1 << 31);
961 frames += len / stream->streamheader.dwSampleSize + !!(len % stream->streamheader.dwSampleSize);
964 else
965 frames += stream->stdindex[y]->nEntriesInUse;
968 else frames = stream->frames;
970 frames *= stream->streamheader.dwScale;
971 /* Keep accuracy as high as possible for duration */
972 This->Parser.mediaSeeking.llDuration = frames * 10000000;
973 This->Parser.mediaSeeking.llDuration /= stream->streamheader.dwRate;
974 This->Parser.mediaSeeking.llStop = This->Parser.mediaSeeking.llDuration;
975 This->Parser.mediaSeeking.llCurrent = 0;
977 frames /= stream->streamheader.dwRate;
979 TRACE("Duration: %d days, %d hours, %d minutes and %d seconds\n", (DWORD)(frames / 86400),
980 (DWORD)((frames % 86400) / 3600), (DWORD)((frames % 3600) / 60), (DWORD)(frames % 60));
983 return S_OK;
986 static HRESULT AVISplitter_Disconnect(LPVOID iface);
988 /* FIXME: fix leaks on failure here */
989 static HRESULT AVISplitter_InputPin_PreConnect(IPin * iface, IPin * pConnectPin, ALLOCATOR_PROPERTIES *props)
991 PullPin *This = (PullPin *)iface;
992 HRESULT hr;
993 RIFFLIST list;
994 LONGLONG pos = 0; /* in bytes */
995 BYTE * pBuffer;
996 RIFFCHUNK * pCurrentChunk;
997 LONGLONG total, avail;
998 int x;
999 DWORD indexes;
1001 AVISplitterImpl * pAviSplit = (AVISplitterImpl *)This->pin.pinInfo.pFilter;
1003 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1004 pos += sizeof(list);
1006 if (list.fcc != FOURCC_RIFF)
1008 ERR("Input stream not a RIFF file\n");
1009 return E_FAIL;
1011 if (list.fccListType != formtypeAVI)
1013 ERR("Input stream not an AVI RIFF file\n");
1014 return E_FAIL;
1017 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1018 if (list.fcc != FOURCC_LIST)
1020 ERR("Expected LIST chunk, but got %.04s\n", (LPSTR)&list.fcc);
1021 return E_FAIL;
1023 if (list.fccListType != listtypeAVIHEADER)
1025 ERR("Header list expected. Got: %.04s\n", (LPSTR)&list.fccListType);
1026 return E_FAIL;
1029 pBuffer = HeapAlloc(GetProcessHeap(), 0, list.cb - sizeof(RIFFLIST) + sizeof(RIFFCHUNK));
1030 hr = IAsyncReader_SyncRead(This->pReader, pos + sizeof(list), list.cb - sizeof(RIFFLIST) + sizeof(RIFFCHUNK), pBuffer);
1032 pAviSplit->AviHeader.cb = 0;
1034 /* Stream list will set the buffer size here, so set a default and allow an override */
1035 props->cbBuffer = 0x20000;
1037 for (pCurrentChunk = (RIFFCHUNK *)pBuffer; (BYTE *)pCurrentChunk + sizeof(*pCurrentChunk) < pBuffer + list.cb; pCurrentChunk = (RIFFCHUNK *)(((BYTE *)pCurrentChunk) + sizeof(*pCurrentChunk) + pCurrentChunk->cb))
1039 RIFFLIST * pList;
1041 switch (pCurrentChunk->fcc)
1043 case ckidMAINAVIHEADER:
1044 /* AVIMAINHEADER includes the structure that is pCurrentChunk at the moment */
1045 memcpy(&pAviSplit->AviHeader, pCurrentChunk, sizeof(pAviSplit->AviHeader));
1046 break;
1047 case FOURCC_LIST:
1048 pList = (RIFFLIST *)pCurrentChunk;
1049 switch (pList->fccListType)
1051 case ckidSTREAMLIST:
1052 hr = AVISplitter_ProcessStreamList(pAviSplit, (BYTE *)pCurrentChunk + sizeof(RIFFLIST), pCurrentChunk->cb + sizeof(RIFFCHUNK) - sizeof(RIFFLIST), props);
1053 break;
1054 case ckidODML:
1055 hr = AVISplitter_ProcessODML(pAviSplit, (BYTE *)pCurrentChunk + sizeof(RIFFLIST), pCurrentChunk->cb + sizeof(RIFFCHUNK) - sizeof(RIFFLIST));
1056 break;
1058 break;
1059 case ckidAVIPADDING:
1060 /* ignore */
1061 break;
1062 default:
1063 FIXME("unrecognised header list type: %.04s\n", (LPSTR)&pCurrentChunk->fcc);
1066 HeapFree(GetProcessHeap(), 0, pBuffer);
1068 if (pAviSplit->AviHeader.cb != sizeof(pAviSplit->AviHeader) - sizeof(RIFFCHUNK))
1070 ERR("Avi Header wrong size!\n");
1071 return E_FAIL;
1074 pos += sizeof(RIFFCHUNK) + list.cb;
1075 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1077 while (list.fcc == ckidAVIPADDING || (list.fcc == FOURCC_LIST && list.fccListType == ckidINFO))
1079 pos += sizeof(RIFFCHUNK) + list.cb;
1081 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1084 if (list.fcc != FOURCC_LIST)
1086 ERR("Expected LIST, but got %.04s\n", (LPSTR)&list.fcc);
1087 return E_FAIL;
1089 if (list.fccListType != listtypeAVIMOVIE)
1091 ERR("Expected AVI movie list, but got %.04s\n", (LPSTR)&list.fccListType);
1092 return E_FAIL;
1095 IAsyncReader_Length(This->pReader, &total, &avail);
1097 /* FIXME: AVIX files are extended beyond the FOURCC chunk "AVI ", and thus won't be played here,
1098 * once I get one of the files I'll try to fix it */
1099 if (hr == S_OK)
1101 This->rtStart = pAviSplit->CurrentChunkOffset = MEDIATIME_FROM_BYTES(pos + sizeof(RIFFLIST));
1102 pos += list.cb + sizeof(RIFFCHUNK);
1104 pAviSplit->EndOfFile = This->rtStop = MEDIATIME_FROM_BYTES(pos);
1105 if (pos > total)
1107 ERR("File smaller (%x%08x) then EndOfFile (%x%08x)\n", (DWORD)(total >> 32), (DWORD)total, (DWORD)(pAviSplit->EndOfFile >> 32), (DWORD)pAviSplit->EndOfFile);
1108 return E_FAIL;
1111 hr = IAsyncReader_SyncRead(This->pReader, BYTES_FROM_MEDIATIME(pAviSplit->CurrentChunkOffset), sizeof(pAviSplit->CurrentChunk), (BYTE *)&pAviSplit->CurrentChunk);
1114 props->cbAlign = 1;
1115 props->cbPrefix = 0;
1116 /* Comrades, prevent shortage of buffers, or you will feel the consequences! DA! */
1117 props->cBuffers = 2 * pAviSplit->Parser.cStreams;
1119 /* Now peek into the idx1 index, if available */
1120 if (hr == S_OK && (total - pos) > sizeof(RIFFCHUNK))
1122 memset(&list, 0, sizeof(list));
1124 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1125 if (list.fcc == ckidAVIOLDINDEX)
1127 pAviSplit->oldindex = CoTaskMemRealloc(pAviSplit->oldindex, list.cb + sizeof(RIFFCHUNK));
1128 if (pAviSplit->oldindex)
1130 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(RIFFCHUNK) + list.cb, (BYTE *)pAviSplit->oldindex);
1131 if (hr == S_OK)
1133 hr = AVISplitter_ProcessOldIndex(pAviSplit);
1135 else
1137 CoTaskMemFree(pAviSplit->oldindex);
1138 pAviSplit->oldindex = NULL;
1139 hr = S_OK;
1145 indexes = 0;
1146 for (x = 0; x < pAviSplit->Parser.cStreams; ++x)
1147 if (pAviSplit->streams[x].entries)
1148 ++indexes;
1150 if (indexes)
1152 CoTaskMemFree(pAviSplit->oldindex);
1153 pAviSplit->oldindex = NULL;
1154 if (indexes < pAviSplit->Parser.cStreams)
1156 /* This error could possible be survived by switching to old type index,
1157 * but I would rather find out why it doesn't find everything here
1159 ERR("%d indexes expected, but only have %d\n", indexes, pAviSplit->Parser.cStreams);
1160 indexes = 0;
1163 else if (!indexes && pAviSplit->oldindex)
1164 indexes = pAviSplit->Parser.cStreams;
1166 if (!indexes && pAviSplit->AviHeader.dwFlags & AVIF_MUSTUSEINDEX)
1168 FIXME("No usable index was found!\n");
1169 hr = E_FAIL;
1172 /* Now, set up the streams */
1173 if (hr == S_OK)
1174 hr = AVISplitter_InitializeStreams(pAviSplit);
1176 if (hr != S_OK)
1178 AVISplitter_Disconnect(pAviSplit);
1179 return E_FAIL;
1182 TRACE("AVI File ok\n");
1184 return hr;
1187 static HRESULT AVISplitter_Flush(LPVOID iface)
1189 AVISplitterImpl *This = (AVISplitterImpl*)iface;
1190 DWORD x;
1192 ERR("(%p)->()\n", This);
1194 for (x = 0; x < This->Parser.cStreams; ++x)
1196 StreamData *stream = This->streams + x;
1198 if (stream->sample)
1199 assert(IMediaSample_Release(stream->sample) == 0);
1200 stream->sample = NULL;
1202 ResetEvent(stream->packet_queued);
1203 assert(!stream->thread);
1206 return S_OK;
1209 static HRESULT AVISplitter_Disconnect(LPVOID iface)
1211 AVISplitterImpl *This = iface;
1212 int x;
1214 /* TODO: Remove other memory that's allocated during connect */
1215 CoTaskMemFree(This->oldindex);
1216 This->oldindex = NULL;
1218 for (x = 0; x < This->Parser.cStreams; ++x)
1220 int i;
1222 StreamData *stream = &This->streams[x];
1224 for (i = 0; i < stream->entries; ++i)
1225 CoTaskMemFree(stream->stdindex[i]);
1227 CoTaskMemFree(stream->stdindex);
1228 CloseHandle(stream->packet_queued);
1230 CoTaskMemFree(This->streams);
1231 This->streams = NULL;
1232 return S_OK;
1235 static ULONG WINAPI AVISplitter_Release(IBaseFilter *iface)
1237 AVISplitterImpl *This = (AVISplitterImpl *)iface;
1238 ULONG ref;
1240 ref = InterlockedDecrement(&This->Parser.refCount);
1242 TRACE("(%p)->() Release from %d\n", This, ref + 1);
1244 if (!ref)
1246 AVISplitter_Flush(This);
1247 Parser_Destroy(&This->Parser);
1250 return ref;
1253 static HRESULT AVISplitter_seek(IBaseFilter *iface)
1255 AVISplitterImpl *This = (AVISplitterImpl *)iface;
1256 PullPin *pPin = This->Parser.pInputPin;
1257 LONGLONG newpos, endpos;
1258 DWORD x;
1260 newpos = This->Parser.mediaSeeking.llCurrent;
1261 endpos = This->Parser.mediaSeeking.llDuration;
1263 if (newpos > endpos)
1265 WARN("Requesting position %x%08x beyond end of stream %x%08x\n", (DWORD)(newpos>>32), (DWORD)newpos, (DWORD)(endpos>>32), (DWORD)endpos);
1266 return E_INVALIDARG;
1269 FIXME("Moving position to %u.%03u s!\n", (DWORD)(newpos / 10000000), (DWORD)((newpos / 10000)%1000));
1271 EnterCriticalSection(&pPin->thread_lock);
1272 /* Send a flush to all output pins */
1273 IPin_BeginFlush((IPin *)pPin);
1275 /* Make sure this is done while stopped, BeginFlush takes care of this */
1276 EnterCriticalSection(&This->Parser.csFilter);
1277 for (x = 0; x < This->Parser.cStreams; ++x)
1279 Parser_OutputPin *pin = (Parser_OutputPin *)This->Parser.ppPins[1+x];
1280 StreamData *stream = This->streams + x;
1281 IPin *victim = NULL;
1282 LONGLONG wanted_frames;
1283 DWORD last_keyframe = 0, last_keyframeidx = 0, preroll = 0;
1285 wanted_frames = newpos;
1286 wanted_frames *= stream->streamheader.dwRate;
1287 wanted_frames /= 10000000;
1288 wanted_frames /= stream->streamheader.dwScale;
1290 IPin_ConnectedTo((IPin *)pin, &victim);
1291 if (victim)
1293 IPin_NewSegment(victim, newpos, endpos, pPin->dRate);
1294 IPin_Release(victim);
1297 pin->dwSamplesProcessed = 0;
1298 stream->index = 0;
1299 stream->pos = 0;
1300 stream->seek = 1;
1301 if (stream->stdindex)
1303 DWORD y, z = 0;
1305 for (y = 0; y < stream->entries; ++y)
1307 for (z = 0; z < stream->stdindex[y]->nEntriesInUse; ++z)
1309 if (stream->streamheader.dwSampleSize)
1311 ULONG len = stream->stdindex[y]->aIndex[z].dwSize & ~(1 << 31);
1312 ULONG size = stream->streamheader.dwSampleSize;
1314 pin->dwSamplesProcessed += len / size;
1315 if (len % size)
1316 ++pin->dwSamplesProcessed;
1318 else ++pin->dwSamplesProcessed;
1320 if (!(stream->stdindex[y]->aIndex[z].dwSize >> 31))
1322 last_keyframe = z;
1323 last_keyframeidx = y;
1324 preroll = 0;
1326 else
1327 ++preroll;
1329 if (pin->dwSamplesProcessed >= wanted_frames)
1330 break;
1332 if (pin->dwSamplesProcessed >= wanted_frames)
1333 break;
1335 stream->index = last_keyframeidx;
1336 stream->pos = last_keyframe;
1338 else
1340 DWORD nMax, n;
1341 nMax = This->oldindex->cb / sizeof(This->oldindex->aIndex[0]);
1343 for (n = 0; n < nMax; ++n)
1345 DWORD streamId = StreamFromFOURCC(This->oldindex->aIndex[n].dwChunkId);
1346 if (streamId != x)
1347 continue;
1349 if (stream->streamheader.dwSampleSize)
1351 ULONG len = This->oldindex->aIndex[n].dwSize;
1352 ULONG size = stream->streamheader.dwSampleSize;
1354 pin->dwSamplesProcessed += len / size;
1355 if (len % size)
1356 ++pin->dwSamplesProcessed;
1358 else ++pin->dwSamplesProcessed;
1360 if (This->oldindex->aIndex[n].dwFlags & AVIIF_KEYFRAME)
1362 last_keyframe = n;
1363 preroll = 0;
1365 else
1366 ++preroll;
1368 if (pin->dwSamplesProcessed >= wanted_frames)
1369 break;
1371 assert(n < nMax);
1372 stream->pos = last_keyframe;
1373 stream->index = 0;
1375 stream->preroll = preroll;
1376 stream->seek = 1;
1378 LeaveCriticalSection(&This->Parser.csFilter);
1380 TRACE("Done flushing\n");
1381 IPin_EndFlush((IPin *)pPin);
1382 LeaveCriticalSection(&pPin->thread_lock);
1384 return S_OK;
1387 static const IBaseFilterVtbl AVISplitterImpl_Vtbl =
1389 Parser_QueryInterface,
1390 Parser_AddRef,
1391 AVISplitter_Release,
1392 Parser_GetClassID,
1393 Parser_Stop,
1394 Parser_Pause,
1395 Parser_Run,
1396 Parser_GetState,
1397 Parser_SetSyncSource,
1398 Parser_GetSyncSource,
1399 Parser_EnumPins,
1400 Parser_FindPin,
1401 Parser_QueryFilterInfo,
1402 Parser_JoinFilterGraph,
1403 Parser_QueryVendorInfo
1406 HRESULT AVISplitter_create(IUnknown * pUnkOuter, LPVOID * ppv)
1408 HRESULT hr;
1409 AVISplitterImpl * This;
1411 TRACE("(%p, %p)\n", pUnkOuter, ppv);
1413 *ppv = NULL;
1415 if (pUnkOuter)
1416 return CLASS_E_NOAGGREGATION;
1418 /* Note: This memory is managed by the transform filter once created */
1419 This = CoTaskMemAlloc(sizeof(AVISplitterImpl));
1421 This->streams = NULL;
1422 This->oldindex = NULL;
1424 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);
1426 if (FAILED(hr))
1427 return hr;
1429 *ppv = (LPVOID)This;
1431 return hr;