msxml3: Block ::add() if collection is read-only.
[wine/multimedia.git] / dlls / quartz / avisplit.c
blobe539d6443b6e04ddd1901b734217c48964327a01
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 static inline AVISplitterImpl *impl_from_IMediaSeeking( IMediaSeeking *iface )
106 return (AVISplitterImpl *)((char*)iface - FIELD_OFFSET(AVISplitterImpl, Parser.sourceSeeking.lpVtbl));
109 /* The threading stuff cries for an explanation
111 * PullPin starts processing and calls AVISplitter_first_request
112 * AVISplitter_first_request creates a thread for each stream
113 * A stream can be audio, video, subtitles or something undefined.
115 * AVISplitter_first_request loads a single packet to each but one stream,
116 * and queues it for that last stream. This is to prevent WaitForNext to time
117 * out badly.
119 * The processing loop is entered. It calls IAsyncReader_WaitForNext in the
120 * PullPin. Every time it receives a packet, it will call AVISplitter_Sample
121 * AVISplitter_Sample will signal the relevant thread that a new sample is
122 * arrived, when that thread is ready it will read the packet and transmits
123 * it downstream with AVISplitter_Receive
125 * Threads terminate upon receiving NULL as packet or when ANY error code
126 * != S_OK occurs. This means that any error is fatal to processing.
129 static HRESULT AVISplitter_SendEndOfFile(AVISplitterImpl *This, DWORD streamnumber)
131 IPin* ppin = NULL;
132 HRESULT hr;
134 TRACE("End of file reached\n");
136 hr = IPin_ConnectedTo(This->Parser.ppPins[streamnumber+1], &ppin);
137 if (SUCCEEDED(hr))
139 hr = IPin_EndOfStream(ppin);
140 IPin_Release(ppin);
142 TRACE("--> %x\n", hr);
144 /* Force the pullpin thread to stop */
145 return S_FALSE;
148 /* Thread worker horse */
149 static HRESULT AVISplitter_next_request(AVISplitterImpl *This, DWORD streamnumber)
151 StreamData *stream = This->streams + streamnumber;
152 PullPin *pin = This->Parser.pInputPin;
153 IMediaSample *sample = NULL;
154 HRESULT hr;
156 TRACE("(%p, %u)->()\n", This, streamnumber);
158 hr = IMemAllocator_GetBuffer(pin->pAlloc, &sample, NULL, NULL, 0);
159 if (hr != S_OK)
160 ERR("... %08x?\n", hr);
162 if (SUCCEEDED(hr))
164 LONGLONG rtSampleStart;
165 /* Add 4 for the next header, which should hopefully work */
166 LONGLONG rtSampleStop;
168 stream->pos = stream->pos_next;
169 stream->index = stream->index_next;
171 IMediaSample_SetDiscontinuity(sample, stream->seek);
172 stream->seek = FALSE;
173 if (stream->preroll)
175 --stream->preroll;
176 IMediaSample_SetPreroll(sample, TRUE);
178 else
179 IMediaSample_SetPreroll(sample, FALSE);
180 IMediaSample_SetSyncPoint(sample, TRUE);
182 if (stream->stdindex)
184 AVISTDINDEX *index = stream->stdindex[stream->index];
185 AVISTDINDEX_ENTRY *entry = &index->aIndex[stream->pos];
187 /* End of file */
188 if (stream->index >= stream->entries)
190 TRACE("END OF STREAM ON %u\n", streamnumber);
191 IMediaSample_Release(sample);
192 return S_FALSE;
195 rtSampleStart = index->qwBaseOffset;
196 rtSampleStart += entry->dwOffset;
197 rtSampleStart = MEDIATIME_FROM_BYTES(rtSampleStart);
199 ++stream->pos_next;
200 if (index->nEntriesInUse == stream->pos_next)
202 stream->pos_next = 0;
203 ++stream->index_next;
206 rtSampleStop = rtSampleStart + MEDIATIME_FROM_BYTES(entry->dwSize & ~(1 << 31));
208 TRACE("offset(%u) size(%u)\n", (DWORD)BYTES_FROM_MEDIATIME(rtSampleStart), (DWORD)BYTES_FROM_MEDIATIME(rtSampleStop - rtSampleStart));
210 else if (This->oldindex)
212 DWORD flags = This->oldindex->aIndex[stream->pos].dwFlags;
213 DWORD size = This->oldindex->aIndex[stream->pos].dwSize;
215 /* End of file */
216 if (stream->index)
218 TRACE("END OF STREAM ON %u\n", streamnumber);
219 IMediaSample_Release(sample);
220 return S_FALSE;
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, rtstart, rtstop;
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 if (IMediaSample_IsDiscontinuity(sample) == S_OK) {
318 IPin *victim;
319 EnterCriticalSection(&This->Parser.filter.csFilter);
320 pin->pin.pin.tStart = start;
321 pin->pin.pin.dRate = This->Parser.sourceSeeking.dRate;
322 hr = IPin_ConnectedTo((IPin *)pin, &victim);
323 if (hr == S_OK)
325 hr = IPin_NewSegment(victim, start, This->Parser.sourceSeeking.llStop,
326 This->Parser.sourceSeeking.dRate);
327 if (hr != S_OK)
328 FIXME("NewSegment returns %08x\n", hr);
329 IPin_Release(victim);
331 LeaveCriticalSection(&This->Parser.filter.csFilter);
332 if (hr != S_OK)
333 return hr;
335 rtstart = (double)(start - pin->pin.pin.tStart) / pin->pin.pin.dRate;
336 rtstop = (double)(stop - pin->pin.pin.tStart) / pin->pin.pin.dRate;
337 hr = IMediaSample_SetMediaTime(sample, &start, &stop);
338 IMediaSample_SetTime(sample, &rtstart, &rtstop);
339 IMediaSample_SetMediaTime(sample, &start, &stop);
341 hr = BaseOutputPinImpl_Deliver((BaseOutputPin*)&pin->pin, sample);
343 /* Uncomment this if you want to debug the time differences between the
344 * different streams, it is useful for that
346 FIXME("stream %u, hr: %08x, Start: %u.%03u, Stop: %u.%03u\n", streamnumber, hr,
347 (DWORD)(start / 10000000), (DWORD)((start / 10000)%1000),
348 (DWORD)(stop / 10000000), (DWORD)((stop / 10000)%1000));
350 return hr;
353 static DWORD WINAPI AVISplitter_thread_reader(LPVOID data)
355 struct thread_args *args = data;
356 AVISplitterImpl *This = args->This;
357 DWORD streamnumber = args->stream;
358 HRESULT hr = S_OK;
362 HRESULT nexthr = S_FALSE;
363 IMediaSample *sample;
365 WaitForSingleObject(This->streams[streamnumber].packet_queued, INFINITE);
366 sample = This->streams[streamnumber].sample;
367 This->streams[streamnumber].sample = NULL;
368 if (!sample)
369 break;
371 nexthr = AVISplitter_next_request(This, streamnumber);
373 hr = AVISplitter_Receive(This, sample, streamnumber);
374 if (hr != S_OK)
375 FIXME("Receiving error: %08x\n", hr);
377 IMediaSample_Release(sample);
378 if (hr == S_OK)
379 hr = nexthr;
380 if (nexthr == S_FALSE)
381 AVISplitter_SendEndOfFile(This, streamnumber);
382 } while (hr == S_OK);
384 if (hr != S_FALSE)
385 FIXME("Thread %u terminated with hr %08x!\n", streamnumber, hr);
386 else
387 TRACE("Thread %u terminated properly\n", streamnumber);
388 return hr;
391 static HRESULT AVISplitter_Sample(LPVOID iface, IMediaSample * pSample, DWORD_PTR cookie)
393 AVISplitterImpl *This = iface;
394 StreamData *stream = This->streams + cookie;
395 HRESULT hr = S_OK;
397 if (!IMediaSample_GetActualDataLength(pSample))
399 ERR("Received empty sample\n");
400 return S_OK;
403 /* Send the sample to whatever thread is appropiate
404 * That thread should also not have a sample queued at the moment
406 /* Debugging */
407 TRACE("(%p)->(%p size: %u, %lu)\n", This, pSample, IMediaSample_GetActualDataLength(pSample), cookie);
408 assert(cookie < This->Parser.cStreams);
409 assert(!stream->sample);
410 assert(WaitForSingleObject(stream->packet_queued, 0) == WAIT_TIMEOUT);
412 IMediaSample_AddRef(pSample);
414 stream->sample = pSample;
415 SetEvent(stream->packet_queued);
417 return hr;
420 static HRESULT AVISplitter_done_process(LPVOID iface);
422 /* On the first request we have to be sure that (cStreams-1) samples have
423 * already been processed, because otherwise some pins might not ever finish
424 * a Pause state change
426 static HRESULT AVISplitter_first_request(LPVOID iface)
428 AVISplitterImpl *This = iface;
429 HRESULT hr = S_OK;
430 DWORD x;
431 IMediaSample *sample = NULL;
432 BOOL have_sample = FALSE;
434 TRACE("(%p)->()\n", This);
436 for (x = 0; x < This->Parser.cStreams; ++x)
438 StreamData *stream = This->streams + x;
440 /* Nothing should be running at this point */
441 assert(!stream->thread);
443 assert(!sample);
444 /* It could be we asked the thread to terminate, and the thread
445 * already terminated before receiving the deathwish */
446 ResetEvent(stream->packet_queued);
448 stream->pos_next = stream->pos;
449 stream->index_next = stream->index;
451 /* This was sent after stopped->paused or stopped->playing, so set seek */
452 stream->seek = 1;
454 /* There should be a packet queued from AVISplitter_next_request last time
455 * It needs to be done now because this is the only way to ensure that every
456 * stream will have at least 1 packet processed
457 * If this is done after the threads start it could go all awkward and we
458 * would have no guarantees that it's successful at all
461 if (have_sample)
463 DWORD_PTR dwUser = ~0;
464 hr = IAsyncReader_WaitForNext(This->Parser.pInputPin->pReader, 10000, &sample, &dwUser);
465 assert(hr == S_OK);
466 assert(sample);
468 AVISplitter_Sample(iface, sample, dwUser);
469 IMediaSample_Release(sample);
472 hr = AVISplitter_next_request(This, x);
473 TRACE("-->%08x\n", hr);
475 /* Could be an EOF instead */
476 have_sample = (hr == S_OK);
477 if (hr == S_FALSE)
478 AVISplitter_SendEndOfFile(This, x);
480 if (FAILED(hr) && hr != VFW_E_NOT_CONNECTED)
481 break;
482 hr = S_OK;
485 /* FIXME: Don't do this for each pin that sent an EOF */
486 for (x = 0; x < This->Parser.cStreams && SUCCEEDED(hr); ++x)
488 struct thread_args *args;
489 DWORD tid;
491 if ((This->streams[x].stdindex && This->streams[x].index_next >= This->streams[x].entries) ||
492 (!This->streams[x].stdindex && This->streams[x].index_next))
494 This->streams[x].thread = NULL;
495 continue;
498 args = CoTaskMemAlloc(sizeof(*args));
499 args->This = This;
500 args->stream = x;
501 This->streams[x].thread = CreateThread(NULL, 0, AVISplitter_thread_reader, args, 0, &tid);
502 TRACE("Created stream %u thread 0x%08x\n", x, tid);
505 if (FAILED(hr))
506 ERR("Horsemen of the apocalypse came to bring error 0x%08x\n", hr);
508 return hr;
511 static HRESULT AVISplitter_done_process(LPVOID iface)
513 AVISplitterImpl *This = iface;
515 DWORD x;
517 for (x = 0; x < This->Parser.cStreams; ++x)
519 StreamData *stream = This->streams + x;
521 TRACE("Waiting for %u to terminate\n", x);
522 /* Make the thread return first */
523 SetEvent(stream->packet_queued);
524 assert(WaitForSingleObject(stream->thread, 100000) != WAIT_TIMEOUT);
525 CloseHandle(stream->thread);
526 stream->thread = NULL;
528 if (stream->sample)
529 assert(IMediaSample_Release(stream->sample) == 0);
530 stream->sample = NULL;
532 ResetEvent(stream->packet_queued);
534 TRACE("All threads are now terminated\n");
536 return S_OK;
539 static HRESULT AVISplitter_QueryAccept(LPVOID iface, const AM_MEDIA_TYPE * pmt)
541 if (IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream) && IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_Avi))
542 return S_OK;
543 return S_FALSE;
546 static HRESULT AVISplitter_ProcessIndex(AVISplitterImpl *This, AVISTDINDEX **index, LONGLONG qwOffset, DWORD cb)
548 AVISTDINDEX *pIndex;
549 DWORD x;
550 int rest;
552 *index = NULL;
553 if (cb < sizeof(AVISTDINDEX))
555 FIXME("size %u too small\n", cb);
556 return E_INVALIDARG;
559 pIndex = CoTaskMemAlloc(cb);
560 if (!pIndex)
561 return E_OUTOFMEMORY;
563 IAsyncReader_SyncRead(((PullPin *)This->Parser.ppPins[0])->pReader, qwOffset, cb, (BYTE *)pIndex);
564 rest = cb - sizeof(AVISUPERINDEX) + sizeof(RIFFCHUNK) + sizeof(pIndex->aIndex);
566 TRACE("FOURCC: %s\n", debugstr_an((char *)&pIndex->fcc, 4));
567 TRACE("wLongsPerEntry: %hd\n", pIndex->wLongsPerEntry);
568 TRACE("bIndexSubType: %u\n", pIndex->bIndexSubType);
569 TRACE("bIndexType: %u\n", pIndex->bIndexType);
570 TRACE("nEntriesInUse: %u\n", pIndex->nEntriesInUse);
571 TRACE("dwChunkId: %.4s\n", (char *)&pIndex->dwChunkId);
572 TRACE("qwBaseOffset: %x%08x\n", (DWORD)(pIndex->qwBaseOffset >> 32), (DWORD)pIndex->qwBaseOffset);
573 TRACE("dwReserved_3: %u\n", pIndex->dwReserved_3);
575 if (pIndex->bIndexType != AVI_INDEX_OF_CHUNKS
576 || pIndex->wLongsPerEntry != 2
577 || rest < (pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry)
578 || (pIndex->bIndexSubType != AVI_INDEX_SUB_DEFAULT))
580 FIXME("Invalid index chunk encountered: %u/%u, %u/%u, %u/%u, %u/%u\n",
581 pIndex->bIndexType, AVI_INDEX_OF_CHUNKS, pIndex->wLongsPerEntry, 2,
582 rest, (DWORD)(pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry),
583 pIndex->bIndexSubType, AVI_INDEX_SUB_DEFAULT);
584 *index = NULL;
585 return E_INVALIDARG;
588 for (x = 0; x < pIndex->nEntriesInUse; ++x)
590 BOOL keyframe = !(pIndex->aIndex[x].dwSize >> 31);
591 DWORDLONG offset = pIndex->qwBaseOffset + pIndex->aIndex[x].dwOffset;
592 TRACE("dwOffset: %x%08x\n", (DWORD)(offset >> 32), (DWORD)offset);
593 TRACE("dwSize: %u\n", (pIndex->aIndex[x].dwSize & ~(1<<31)));
594 TRACE("Frame is a keyframe: %s\n", keyframe ? "yes" : "no");
597 *index = pIndex;
598 return S_OK;
601 static HRESULT AVISplitter_ProcessOldIndex(AVISplitterImpl *This)
603 ULONGLONG mov_pos = BYTES_FROM_MEDIATIME(This->CurrentChunkOffset) - sizeof(DWORD);
604 AVIOLDINDEX *pAviOldIndex = This->oldindex;
605 int relative = -1;
606 DWORD x;
608 for (x = 0; x < pAviOldIndex->cb / sizeof(pAviOldIndex->aIndex[0]); ++x)
610 DWORD temp, temp2 = 0, offset, chunkid;
611 PullPin *pin = This->Parser.pInputPin;
613 offset = pAviOldIndex->aIndex[x].dwOffset;
614 chunkid = pAviOldIndex->aIndex[x].dwChunkId;
616 TRACE("dwChunkId: %.4s\n", (char *)&chunkid);
617 TRACE("dwFlags: %08x\n", pAviOldIndex->aIndex[x].dwFlags);
618 TRACE("dwOffset (%s): %08x\n", relative ? "relative" : "absolute", offset);
619 TRACE("dwSize: %08x\n", pAviOldIndex->aIndex[x].dwSize);
621 /* Only scan once, or else this will take too long */
622 if (relative == -1)
624 IAsyncReader_SyncRead(pin->pReader, offset, sizeof(DWORD), (BYTE *)&temp);
625 relative = (chunkid != temp);
627 if (chunkid == mmioFOURCC('7','F','x','x')
628 && ((char *)&temp)[0] == 'i' && ((char *)&temp)[1] == 'x')
629 relative = FALSE;
631 if (relative)
633 if (offset + mov_pos < BYTES_FROM_MEDIATIME(This->EndOfFile))
634 IAsyncReader_SyncRead(pin->pReader, offset + mov_pos, sizeof(DWORD), (BYTE *)&temp2);
636 if (chunkid == mmioFOURCC('7','F','x','x')
637 && ((char *)&temp2)[0] == 'i' && ((char *)&temp2)[1] == 'x')
639 /* Do nothing, all is great */
641 else if (temp2 != chunkid)
643 ERR("Faulty index or bug in handling: Wanted FCC: %s, Abs FCC: %s (@ %x), Rel FCC: %s (@ %.0x%08x)\n",
644 debugstr_an((char *)&chunkid, 4), debugstr_an((char *)&temp, 4), offset,
645 debugstr_an((char *)&temp2, 4), (DWORD)((mov_pos + offset) >> 32), (DWORD)(mov_pos + offset));
646 relative = -1;
648 else
649 TRACE("Scanned dwChunkId: %s\n", debugstr_an((char *)&temp2, 4));
651 else if (!relative)
652 TRACE("Scanned dwChunkId: %s\n", debugstr_an((char *)&temp, 4));
654 /* Only dump one packet */
655 else break;
658 if (relative == -1)
660 FIXME("Dropping index: no idea whether it is relative or absolute\n");
661 CoTaskMemFree(This->oldindex);
662 This->oldindex = NULL;
664 else if (!relative)
665 This->offset = 0;
666 else
667 This->offset = (DWORD)mov_pos;
669 return S_OK;
672 static HRESULT AVISplitter_ProcessStreamList(AVISplitterImpl * This, const BYTE * pData, DWORD cb, ALLOCATOR_PROPERTIES *props)
674 PIN_INFO piOutput;
675 const RIFFCHUNK * pChunk;
676 HRESULT hr;
677 AM_MEDIA_TYPE amt;
678 float fSamplesPerSec = 0.0f;
679 DWORD dwSampleSize = 0;
680 DWORD dwLength = 0;
681 DWORD nstdindex = 0;
682 static const WCHAR wszStreamTemplate[] = {'S','t','r','e','a','m',' ','%','0','2','d',0};
683 StreamData *stream;
685 ZeroMemory(&amt, sizeof(amt));
686 piOutput.dir = PINDIR_OUTPUT;
687 piOutput.pFilter = (IBaseFilter *)This;
688 wsprintfW(piOutput.achName, wszStreamTemplate, This->Parser.cStreams);
689 This->streams = CoTaskMemRealloc(This->streams, sizeof(StreamData) * (This->Parser.cStreams+1));
690 stream = This->streams + This->Parser.cStreams;
691 ZeroMemory(stream, sizeof(*stream));
693 for (pChunk = (const RIFFCHUNK *)pData;
694 ((const BYTE *)pChunk >= pData) && ((const BYTE *)pChunk + sizeof(RIFFCHUNK) < pData + cb) && (pChunk->cb > 0);
695 pChunk = (const RIFFCHUNK *)((const BYTE*)pChunk + sizeof(RIFFCHUNK) + pChunk->cb)
698 switch (pChunk->fcc)
700 case ckidSTREAMHEADER:
702 const AVISTREAMHEADER * pStrHdr = (const AVISTREAMHEADER *)pChunk;
703 TRACE("processing stream header\n");
704 stream->streamheader = *pStrHdr;
706 fSamplesPerSec = (float)pStrHdr->dwRate / (float)pStrHdr->dwScale;
707 CoTaskMemFree(amt.pbFormat);
708 amt.pbFormat = NULL;
709 amt.cbFormat = 0;
711 switch (pStrHdr->fccType)
713 case streamtypeVIDEO:
714 amt.formattype = FORMAT_VideoInfo;
715 break;
716 case streamtypeAUDIO:
717 amt.formattype = FORMAT_WaveFormatEx;
718 break;
719 default:
720 FIXME("fccType %.4s not handled yet\n", (const char *)&pStrHdr->fccType);
721 amt.formattype = FORMAT_None;
723 amt.majortype = MEDIATYPE_Video;
724 amt.majortype.Data1 = pStrHdr->fccType;
725 amt.subtype = MEDIATYPE_Video;
726 amt.subtype.Data1 = pStrHdr->fccHandler;
727 TRACE("Subtype FCC: %.04s\n", (LPCSTR)&pStrHdr->fccHandler);
728 amt.lSampleSize = pStrHdr->dwSampleSize;
729 amt.bFixedSizeSamples = (amt.lSampleSize != 0);
731 /* FIXME: Is this right? */
732 if (!amt.lSampleSize)
734 amt.lSampleSize = 1;
735 dwSampleSize = 1;
738 amt.bTemporalCompression = IsEqualGUID(&amt.majortype, &MEDIATYPE_Video); /* FIXME? */
739 dwSampleSize = pStrHdr->dwSampleSize;
740 dwLength = pStrHdr->dwLength;
741 if (!dwLength)
742 dwLength = This->AviHeader.dwTotalFrames;
744 if (pStrHdr->dwSuggestedBufferSize && pStrHdr->dwSuggestedBufferSize > props->cbBuffer)
745 props->cbBuffer = pStrHdr->dwSuggestedBufferSize;
747 break;
749 case ckidSTREAMFORMAT:
750 TRACE("processing stream format data\n");
751 if (IsEqualIID(&amt.formattype, &FORMAT_VideoInfo))
753 VIDEOINFOHEADER * pvi;
754 /* biCompression member appears to override the value in the stream header.
755 * i.e. the stream header can say something completely contradictory to what
756 * is in the BITMAPINFOHEADER! */
757 if (pChunk->cb < sizeof(BITMAPINFOHEADER))
759 ERR("Not enough bytes for BITMAPINFOHEADER\n");
760 return E_FAIL;
762 amt.cbFormat = sizeof(VIDEOINFOHEADER) - sizeof(BITMAPINFOHEADER) + pChunk->cb;
763 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
764 ZeroMemory(amt.pbFormat, amt.cbFormat);
765 pvi = (VIDEOINFOHEADER *)amt.pbFormat;
766 pvi->AvgTimePerFrame = (LONGLONG)(10000000.0 / fSamplesPerSec);
768 CopyMemory(&pvi->bmiHeader, pChunk + 1, pChunk->cb);
769 if (pvi->bmiHeader.biCompression)
770 amt.subtype.Data1 = pvi->bmiHeader.biCompression;
772 else if (IsEqualIID(&amt.formattype, &FORMAT_WaveFormatEx))
774 amt.cbFormat = pChunk->cb;
775 if (amt.cbFormat < sizeof(WAVEFORMATEX))
776 amt.cbFormat = sizeof(WAVEFORMATEX);
777 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
778 ZeroMemory(amt.pbFormat, amt.cbFormat);
779 CopyMemory(amt.pbFormat, pChunk + 1, pChunk->cb);
781 else
783 amt.cbFormat = pChunk->cb;
784 amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
785 CopyMemory(amt.pbFormat, pChunk + 1, amt.cbFormat);
787 break;
788 case ckidSTREAMNAME:
789 TRACE("processing stream name\n");
790 /* FIXME: this doesn't exactly match native version (we omit the "##)" prefix), but hey... */
791 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)(pChunk + 1), pChunk->cb, piOutput.achName, sizeof(piOutput.achName) / sizeof(piOutput.achName[0]));
792 break;
793 case ckidSTREAMHANDLERDATA:
794 FIXME("process stream handler data\n");
795 break;
796 case ckidAVIPADDING:
797 TRACE("JUNK chunk ignored\n");
798 break;
799 case ckidAVISUPERINDEX:
801 const AVISUPERINDEX *pIndex = (const AVISUPERINDEX *)pChunk;
802 DWORD x;
803 UINT rest = pIndex->cb - sizeof(AVISUPERINDEX) + sizeof(RIFFCHUNK) + sizeof(pIndex->aIndex[0]) * ANYSIZE_ARRAY;
805 if (pIndex->cb < sizeof(AVISUPERINDEX) - sizeof(RIFFCHUNK))
807 FIXME("size %u\n", pIndex->cb);
808 break;
811 if (nstdindex++ > 0)
813 ERR("Stream %d got more than 1 superindex?\n", This->Parser.cStreams);
814 break;
817 TRACE("wLongsPerEntry: %hd\n", pIndex->wLongsPerEntry);
818 TRACE("bIndexSubType: %u\n", pIndex->bIndexSubType);
819 TRACE("bIndexType: %u\n", pIndex->bIndexType);
820 TRACE("nEntriesInUse: %u\n", pIndex->nEntriesInUse);
821 TRACE("dwChunkId: %.4s\n", (const char *)&pIndex->dwChunkId);
822 if (pIndex->dwReserved[0])
823 TRACE("dwReserved[0]: %u\n", pIndex->dwReserved[0]);
824 if (pIndex->dwReserved[2])
825 TRACE("dwReserved[1]: %u\n", pIndex->dwReserved[1]);
826 if (pIndex->dwReserved[2])
827 TRACE("dwReserved[2]: %u\n", pIndex->dwReserved[2]);
829 if (pIndex->bIndexType != AVI_INDEX_OF_INDEXES
830 || pIndex->wLongsPerEntry != 4
831 || rest < (pIndex->nEntriesInUse * sizeof(DWORD) * pIndex->wLongsPerEntry)
832 || (pIndex->bIndexSubType != AVI_INDEX_SUB_2FIELD && pIndex->bIndexSubType != AVI_INDEX_SUB_DEFAULT))
834 FIXME("Invalid index chunk encountered\n");
835 break;
838 stream->entries = pIndex->nEntriesInUse;
839 stream->stdindex = CoTaskMemRealloc(stream->stdindex, sizeof(*stream->stdindex) * stream->entries);
840 for (x = 0; x < pIndex->nEntriesInUse; ++x)
842 TRACE("qwOffset: %x%08x\n", (DWORD)(pIndex->aIndex[x].qwOffset >> 32), (DWORD)pIndex->aIndex[x].qwOffset);
843 TRACE("dwSize: %u\n", pIndex->aIndex[x].dwSize);
844 TRACE("dwDuration: %u (unreliable)\n", pIndex->aIndex[x].dwDuration);
846 AVISplitter_ProcessIndex(This, &stream->stdindex[x], pIndex->aIndex[x].qwOffset, pIndex->aIndex[x].dwSize);
848 break;
850 default:
851 FIXME("unknown chunk type \"%.04s\" ignored\n", (LPCSTR)&pChunk->fcc);
855 if (IsEqualGUID(&amt.formattype, &FORMAT_WaveFormatEx))
857 amt.subtype = MEDIATYPE_Video;
858 amt.subtype.Data1 = ((WAVEFORMATEX *)amt.pbFormat)->wFormatTag;
861 dump_AM_MEDIA_TYPE(&amt);
862 TRACE("fSamplesPerSec = %f\n", (double)fSamplesPerSec);
863 TRACE("dwSampleSize = %x\n", dwSampleSize);
864 TRACE("dwLength = %x\n", dwLength);
866 stream->fSamplesPerSec = fSamplesPerSec;
867 stream->dwSampleSize = dwSampleSize;
868 stream->dwLength = dwLength; /* TODO: Use this for mediaseeking */
869 stream->packet_queued = CreateEventW(NULL, 0, 0, NULL);
871 hr = Parser_AddPin(&(This->Parser), &piOutput, props, &amt);
872 CoTaskMemFree(amt.pbFormat);
875 return hr;
878 static HRESULT AVISplitter_ProcessODML(AVISplitterImpl * This, const BYTE * pData, DWORD cb)
880 const RIFFCHUNK * pChunk;
882 for (pChunk = (const RIFFCHUNK *)pData;
883 ((const BYTE *)pChunk >= pData) && ((const BYTE *)pChunk + sizeof(RIFFCHUNK) < pData + cb) && (pChunk->cb > 0);
884 pChunk = (const RIFFCHUNK *)((const BYTE*)pChunk + sizeof(RIFFCHUNK) + pChunk->cb)
887 switch (pChunk->fcc)
889 case ckidAVIEXTHEADER:
891 int x;
892 const AVIEXTHEADER * pExtHdr = (const AVIEXTHEADER *)pChunk;
894 TRACE("processing extension header\n");
895 if (pExtHdr->cb != sizeof(AVIEXTHEADER) - sizeof(RIFFCHUNK))
897 FIXME("Size: %u\n", pExtHdr->cb);
898 break;
900 TRACE("dwGrandFrames: %u\n", pExtHdr->dwGrandFrames);
901 for (x = 0; x < 61; ++x)
902 if (pExtHdr->dwFuture[x])
903 FIXME("dwFuture[%i] = %u (0x%08x)\n", x, pExtHdr->dwFuture[x], pExtHdr->dwFuture[x]);
904 This->ExtHeader = *pExtHdr;
905 break;
907 default:
908 FIXME("unknown chunk type \"%.04s\" ignored\n", (LPCSTR)&pChunk->fcc);
912 return S_OK;
915 static HRESULT AVISplitter_InitializeStreams(AVISplitterImpl *This)
917 unsigned int x;
919 if (This->oldindex)
921 DWORD nMax, n;
923 for (x = 0; x < This->Parser.cStreams; ++x)
925 This->streams[x].frames = 0;
926 This->streams[x].pos = ~0;
927 This->streams[x].index = 0;
930 nMax = This->oldindex->cb / sizeof(This->oldindex->aIndex[0]);
932 /* Ok, maybe this is more of an exercise to see if I interpret everything correctly or not, but that is useful for now. */
933 for (n = 0; n < nMax; ++n)
935 DWORD streamId = StreamFromFOURCC(This->oldindex->aIndex[n].dwChunkId);
936 if (streamId >= This->Parser.cStreams)
938 FIXME("Stream id %s ignored\n", debugstr_an((char*)&This->oldindex->aIndex[n].dwChunkId, 4));
939 continue;
941 if (This->streams[streamId].pos == ~0U)
942 This->streams[streamId].pos = n;
944 if (This->streams[streamId].streamheader.dwSampleSize)
945 This->streams[streamId].frames += This->oldindex->aIndex[n].dwSize / This->streams[streamId].streamheader.dwSampleSize;
946 else
947 ++This->streams[streamId].frames;
950 for (x = 0; x < This->Parser.cStreams; ++x)
952 if ((DWORD)This->streams[x].frames != This->streams[x].streamheader.dwLength)
954 FIXME("stream %u: frames found: %u, frames meant to be found: %u\n", x, (DWORD)This->streams[x].frames, This->streams[x].streamheader.dwLength);
959 else if (!This->streams[0].entries)
961 for (x = 0; x < This->Parser.cStreams; ++x)
963 This->streams[x].frames = This->streams[x].streamheader.dwLength;
965 /* MS Avi splitter does seek through the whole file, we should! */
966 ERR("We should be manually seeking through the entire file to build an index, because the index is missing!!!\n");
967 return E_NOTIMPL;
970 /* Not much here yet */
971 for (x = 0; x < This->Parser.cStreams; ++x)
973 StreamData *stream = This->streams + x;
974 DWORD y;
975 DWORD64 frames = 0;
977 stream->seek = 1;
979 if (stream->stdindex)
981 stream->index = 0;
982 stream->pos = 0;
983 for (y = 0; y < stream->entries; ++y)
985 if (stream->streamheader.dwSampleSize)
987 DWORD z;
989 for (z = 0; z < stream->stdindex[y]->nEntriesInUse; ++z)
991 UINT len = stream->stdindex[y]->aIndex[z].dwSize & ~(1 << 31);
992 frames += len / stream->streamheader.dwSampleSize + !!(len % stream->streamheader.dwSampleSize);
995 else
996 frames += stream->stdindex[y]->nEntriesInUse;
999 else frames = stream->frames;
1001 frames *= stream->streamheader.dwScale;
1002 /* Keep accuracy as high as possible for duration */
1003 This->Parser.sourceSeeking.llDuration = frames * 10000000;
1004 This->Parser.sourceSeeking.llDuration /= stream->streamheader.dwRate;
1005 This->Parser.sourceSeeking.llStop = This->Parser.sourceSeeking.llDuration;
1006 This->Parser.sourceSeeking.llCurrent = 0;
1008 frames /= stream->streamheader.dwRate;
1010 TRACE("Duration: %d days, %d hours, %d minutes and %d.%03u seconds\n", (DWORD)(frames / 86400),
1011 (DWORD)((frames % 86400) / 3600), (DWORD)((frames % 3600) / 60), (DWORD)(frames % 60),
1012 (DWORD)(This->Parser.sourceSeeking.llDuration/10000) % 1000);
1015 return S_OK;
1018 static HRESULT AVISplitter_Disconnect(LPVOID iface);
1020 /* FIXME: fix leaks on failure here */
1021 static HRESULT AVISplitter_InputPin_PreConnect(IPin * iface, IPin * pConnectPin, ALLOCATOR_PROPERTIES *props)
1023 PullPin *This = (PullPin *)iface;
1024 HRESULT hr;
1025 RIFFLIST list;
1026 LONGLONG pos = 0; /* in bytes */
1027 BYTE * pBuffer;
1028 RIFFCHUNK * pCurrentChunk;
1029 LONGLONG total, avail;
1030 ULONG x;
1031 DWORD indexes;
1033 AVISplitterImpl * pAviSplit = (AVISplitterImpl *)This->pin.pinInfo.pFilter;
1035 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1036 pos += sizeof(list);
1038 if (list.fcc != FOURCC_RIFF)
1040 ERR("Input stream not a RIFF file\n");
1041 return E_FAIL;
1043 if (list.fccListType != formtypeAVI)
1045 ERR("Input stream not an AVI RIFF file\n");
1046 return E_FAIL;
1049 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1050 if (list.fcc != FOURCC_LIST)
1052 ERR("Expected LIST chunk, but got %.04s\n", (LPSTR)&list.fcc);
1053 return E_FAIL;
1055 if (list.fccListType != listtypeAVIHEADER)
1057 ERR("Header list expected. Got: %.04s\n", (LPSTR)&list.fccListType);
1058 return E_FAIL;
1061 pBuffer = HeapAlloc(GetProcessHeap(), 0, list.cb - sizeof(RIFFLIST) + sizeof(RIFFCHUNK));
1062 hr = IAsyncReader_SyncRead(This->pReader, pos + sizeof(list), list.cb - sizeof(RIFFLIST) + sizeof(RIFFCHUNK), pBuffer);
1064 pAviSplit->AviHeader.cb = 0;
1066 /* Stream list will set the buffer size here, so set a default and allow an override */
1067 props->cbBuffer = 0x20000;
1069 for (pCurrentChunk = (RIFFCHUNK *)pBuffer; (BYTE *)pCurrentChunk + sizeof(*pCurrentChunk) < pBuffer + list.cb; pCurrentChunk = (RIFFCHUNK *)(((BYTE *)pCurrentChunk) + sizeof(*pCurrentChunk) + pCurrentChunk->cb))
1071 RIFFLIST * pList;
1073 switch (pCurrentChunk->fcc)
1075 case ckidMAINAVIHEADER:
1076 /* AVIMAINHEADER includes the structure that is pCurrentChunk at the moment */
1077 memcpy(&pAviSplit->AviHeader, pCurrentChunk, sizeof(pAviSplit->AviHeader));
1078 break;
1079 case FOURCC_LIST:
1080 pList = (RIFFLIST *)pCurrentChunk;
1081 switch (pList->fccListType)
1083 case ckidSTREAMLIST:
1084 hr = AVISplitter_ProcessStreamList(pAviSplit, (BYTE *)pCurrentChunk + sizeof(RIFFLIST), pCurrentChunk->cb + sizeof(RIFFCHUNK) - sizeof(RIFFLIST), props);
1085 break;
1086 case ckidODML:
1087 hr = AVISplitter_ProcessODML(pAviSplit, (BYTE *)pCurrentChunk + sizeof(RIFFLIST), pCurrentChunk->cb + sizeof(RIFFCHUNK) - sizeof(RIFFLIST));
1088 break;
1090 break;
1091 case ckidAVIPADDING:
1092 /* ignore */
1093 break;
1094 default:
1095 FIXME("unrecognised header list type: %.04s\n", (LPSTR)&pCurrentChunk->fcc);
1098 HeapFree(GetProcessHeap(), 0, pBuffer);
1100 if (pAviSplit->AviHeader.cb != sizeof(pAviSplit->AviHeader) - sizeof(RIFFCHUNK))
1102 ERR("Avi Header wrong size!\n");
1103 return E_FAIL;
1106 pos += sizeof(RIFFCHUNK) + list.cb;
1107 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1109 while (list.fcc == ckidAVIPADDING || (list.fcc == FOURCC_LIST && list.fccListType != listtypeAVIMOVIE))
1111 pos += sizeof(RIFFCHUNK) + list.cb;
1113 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1116 if (list.fcc != FOURCC_LIST)
1118 ERR("Expected LIST, but got %.04s\n", (LPSTR)&list.fcc);
1119 return E_FAIL;
1121 if (list.fccListType != listtypeAVIMOVIE)
1123 ERR("Expected AVI movie list, but got %.04s\n", (LPSTR)&list.fccListType);
1124 return E_FAIL;
1127 IAsyncReader_Length(This->pReader, &total, &avail);
1129 /* FIXME: AVIX files are extended beyond the FOURCC chunk "AVI ", and thus won't be played here,
1130 * once I get one of the files I'll try to fix it */
1131 if (hr == S_OK)
1133 This->rtStart = pAviSplit->CurrentChunkOffset = MEDIATIME_FROM_BYTES(pos + sizeof(RIFFLIST));
1134 pos += list.cb + sizeof(RIFFCHUNK);
1136 pAviSplit->EndOfFile = This->rtStop = MEDIATIME_FROM_BYTES(pos);
1137 if (pos > total)
1139 ERR("File smaller (%x%08x) then EndOfFile (%x%08x)\n", (DWORD)(total >> 32), (DWORD)total, (DWORD)(pAviSplit->EndOfFile >> 32), (DWORD)pAviSplit->EndOfFile);
1140 return E_FAIL;
1143 hr = IAsyncReader_SyncRead(This->pReader, BYTES_FROM_MEDIATIME(pAviSplit->CurrentChunkOffset), sizeof(pAviSplit->CurrentChunk), (BYTE *)&pAviSplit->CurrentChunk);
1146 props->cbAlign = 1;
1147 props->cbPrefix = 0;
1148 /* Comrades, prevent shortage of buffers, or you will feel the consequences! DA! */
1149 props->cBuffers = 2 * pAviSplit->Parser.cStreams;
1151 /* Now peek into the idx1 index, if available */
1152 if (hr == S_OK && (total - pos) > sizeof(RIFFCHUNK))
1154 memset(&list, 0, sizeof(list));
1156 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
1157 if (list.fcc == ckidAVIOLDINDEX)
1159 pAviSplit->oldindex = CoTaskMemRealloc(pAviSplit->oldindex, list.cb + sizeof(RIFFCHUNK));
1160 if (pAviSplit->oldindex)
1162 hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(RIFFCHUNK) + list.cb, (BYTE *)pAviSplit->oldindex);
1163 if (hr == S_OK)
1165 hr = AVISplitter_ProcessOldIndex(pAviSplit);
1167 else
1169 CoTaskMemFree(pAviSplit->oldindex);
1170 pAviSplit->oldindex = NULL;
1171 hr = S_OK;
1177 indexes = 0;
1178 for (x = 0; x < pAviSplit->Parser.cStreams; ++x)
1179 if (pAviSplit->streams[x].entries)
1180 ++indexes;
1182 if (indexes)
1184 CoTaskMemFree(pAviSplit->oldindex);
1185 pAviSplit->oldindex = NULL;
1186 if (indexes < pAviSplit->Parser.cStreams)
1188 /* This error could possible be survived by switching to old type index,
1189 * but I would rather find out why it doesn't find everything here
1191 ERR("%d indexes expected, but only have %d\n", indexes, pAviSplit->Parser.cStreams);
1192 indexes = 0;
1195 else if (!indexes && pAviSplit->oldindex)
1196 indexes = pAviSplit->Parser.cStreams;
1198 if (!indexes && pAviSplit->AviHeader.dwFlags & AVIF_MUSTUSEINDEX)
1200 FIXME("No usable index was found!\n");
1201 hr = E_FAIL;
1204 /* Now, set up the streams */
1205 if (hr == S_OK)
1206 hr = AVISplitter_InitializeStreams(pAviSplit);
1208 if (hr != S_OK)
1210 AVISplitter_Disconnect(pAviSplit);
1211 return E_FAIL;
1214 TRACE("AVI File ok\n");
1216 return hr;
1219 static HRESULT AVISplitter_Flush(LPVOID iface)
1221 AVISplitterImpl *This = iface;
1222 DWORD x;
1224 TRACE("(%p)->()\n", This);
1226 for (x = 0; x < This->Parser.cStreams; ++x)
1228 StreamData *stream = This->streams + x;
1230 if (stream->sample)
1231 assert(IMediaSample_Release(stream->sample) == 0);
1232 stream->sample = NULL;
1234 ResetEvent(stream->packet_queued);
1235 assert(!stream->thread);
1238 return S_OK;
1241 static HRESULT AVISplitter_Disconnect(LPVOID iface)
1243 AVISplitterImpl *This = iface;
1244 ULONG x;
1246 /* TODO: Remove other memory that's allocated during connect */
1247 CoTaskMemFree(This->oldindex);
1248 This->oldindex = NULL;
1250 for (x = 0; x < This->Parser.cStreams; ++x)
1252 DWORD i;
1254 StreamData *stream = &This->streams[x];
1256 for (i = 0; i < stream->entries; ++i)
1257 CoTaskMemFree(stream->stdindex[i]);
1259 CoTaskMemFree(stream->stdindex);
1260 CloseHandle(stream->packet_queued);
1262 CoTaskMemFree(This->streams);
1263 This->streams = NULL;
1264 return S_OK;
1267 static ULONG WINAPI AVISplitter_Release(IBaseFilter *iface)
1269 AVISplitterImpl *This = (AVISplitterImpl *)iface;
1270 ULONG ref;
1272 ref = InterlockedDecrement(&This->Parser.filter.refCount);
1274 TRACE("(%p)->() Release from %d\n", This, ref + 1);
1276 if (!ref)
1278 AVISplitter_Flush(This);
1279 Parser_Destroy(&This->Parser);
1282 return ref;
1285 static HRESULT WINAPI AVISplitter_seek(IMediaSeeking *iface)
1287 AVISplitterImpl *This = impl_from_IMediaSeeking(iface);
1288 PullPin *pPin = This->Parser.pInputPin;
1289 LONGLONG newpos, endpos;
1290 DWORD x;
1292 newpos = This->Parser.sourceSeeking.llCurrent;
1293 endpos = This->Parser.sourceSeeking.llDuration;
1295 if (newpos > endpos)
1297 WARN("Requesting position %x%08x beyond end of stream %x%08x\n", (DWORD)(newpos>>32), (DWORD)newpos, (DWORD)(endpos>>32), (DWORD)endpos);
1298 return E_INVALIDARG;
1301 FIXME("Moving position to %u.%03u s!\n", (DWORD)(newpos / 10000000), (DWORD)((newpos / 10000)%1000));
1303 EnterCriticalSection(&pPin->thread_lock);
1304 /* Send a flush to all output pins */
1305 IPin_BeginFlush((IPin *)pPin);
1307 /* Make sure this is done while stopped, BeginFlush takes care of this */
1308 EnterCriticalSection(&This->Parser.filter.csFilter);
1309 for (x = 0; x < This->Parser.cStreams; ++x)
1311 Parser_OutputPin *pin = (Parser_OutputPin *)This->Parser.ppPins[1+x];
1312 StreamData *stream = This->streams + x;
1313 LONGLONG wanted_frames;
1314 DWORD last_keyframe = 0, last_keyframeidx = 0, preroll = 0;
1316 wanted_frames = newpos;
1317 wanted_frames *= stream->streamheader.dwRate;
1318 wanted_frames /= 10000000;
1319 wanted_frames /= stream->streamheader.dwScale;
1321 pin->dwSamplesProcessed = 0;
1322 stream->index = 0;
1323 stream->pos = 0;
1324 stream->seek = 1;
1325 if (stream->stdindex)
1327 DWORD y, z = 0;
1329 for (y = 0; y < stream->entries; ++y)
1331 for (z = 0; z < stream->stdindex[y]->nEntriesInUse; ++z)
1333 if (stream->streamheader.dwSampleSize)
1335 ULONG len = stream->stdindex[y]->aIndex[z].dwSize & ~(1 << 31);
1336 ULONG size = stream->streamheader.dwSampleSize;
1338 pin->dwSamplesProcessed += len / size;
1339 if (len % size)
1340 ++pin->dwSamplesProcessed;
1342 else ++pin->dwSamplesProcessed;
1344 if (!(stream->stdindex[y]->aIndex[z].dwSize >> 31))
1346 last_keyframe = z;
1347 last_keyframeidx = y;
1348 preroll = 0;
1350 else
1351 ++preroll;
1353 if (pin->dwSamplesProcessed >= wanted_frames)
1354 break;
1356 if (pin->dwSamplesProcessed >= wanted_frames)
1357 break;
1359 stream->index = last_keyframeidx;
1360 stream->pos = last_keyframe;
1362 else
1364 DWORD nMax, n;
1365 nMax = This->oldindex->cb / sizeof(This->oldindex->aIndex[0]);
1367 for (n = 0; n < nMax; ++n)
1369 DWORD streamId = StreamFromFOURCC(This->oldindex->aIndex[n].dwChunkId);
1370 if (streamId != x)
1371 continue;
1373 if (stream->streamheader.dwSampleSize)
1375 ULONG len = This->oldindex->aIndex[n].dwSize;
1376 ULONG size = stream->streamheader.dwSampleSize;
1378 pin->dwSamplesProcessed += len / size;
1379 if (len % size)
1380 ++pin->dwSamplesProcessed;
1382 else ++pin->dwSamplesProcessed;
1384 if (This->oldindex->aIndex[n].dwFlags & AVIIF_KEYFRAME)
1386 last_keyframe = n;
1387 preroll = 0;
1389 else
1390 ++preroll;
1392 if (pin->dwSamplesProcessed >= wanted_frames)
1393 break;
1395 assert(n < nMax);
1396 stream->pos = last_keyframe;
1397 stream->index = 0;
1399 stream->preroll = preroll;
1400 stream->seek = 1;
1402 LeaveCriticalSection(&This->Parser.filter.csFilter);
1404 TRACE("Done flushing\n");
1405 IPin_EndFlush((IPin *)pPin);
1406 LeaveCriticalSection(&pPin->thread_lock);
1408 return S_OK;
1411 static const IBaseFilterVtbl AVISplitterImpl_Vtbl =
1413 Parser_QueryInterface,
1414 Parser_AddRef,
1415 AVISplitter_Release,
1416 Parser_GetClassID,
1417 Parser_Stop,
1418 Parser_Pause,
1419 Parser_Run,
1420 Parser_GetState,
1421 Parser_SetSyncSource,
1422 Parser_GetSyncSource,
1423 Parser_EnumPins,
1424 Parser_FindPin,
1425 Parser_QueryFilterInfo,
1426 Parser_JoinFilterGraph,
1427 Parser_QueryVendorInfo
1430 HRESULT AVISplitter_create(IUnknown * pUnkOuter, LPVOID * ppv)
1432 HRESULT hr;
1433 AVISplitterImpl * This;
1435 TRACE("(%p, %p)\n", pUnkOuter, ppv);
1437 *ppv = NULL;
1439 if (pUnkOuter)
1440 return CLASS_E_NOAGGREGATION;
1442 /* Note: This memory is managed by the transform filter once created */
1443 This = CoTaskMemAlloc(sizeof(AVISplitterImpl));
1445 This->streams = NULL;
1446 This->oldindex = NULL;
1448 hr = Parser_Create(&(This->Parser), &AVISplitterImpl_Vtbl, &CLSID_AviSplitter, AVISplitter_Sample, AVISplitter_QueryAccept, AVISplitter_InputPin_PreConnect, AVISplitter_Flush, AVISplitter_Disconnect, AVISplitter_first_request, AVISplitter_done_process, NULL, AVISplitter_seek, NULL);
1450 if (FAILED(hr))
1451 return hr;
1453 *ppv = This;
1455 return hr;