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