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