quartz: NotifyAllocator does not like a null argument.
[wine] / dlls / quartz / mpegsplit.c
1 /*
2  * MPEG Splitter Filter
3  *
4  * Copyright 2003 Robert Shearman
5  * Copyright 2004-2005 Christian Costa
6  * Copyright 2007 Chris Robinson
7  * Copyright 2008 Maarten Lankhorst
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include <assert.h>
25 #include <math.h>
26
27 #include "quartz_private.h"
28 #include "control_private.h"
29 #include "pin.h"
30
31 #include "uuids.h"
32 #include "mmreg.h"
33 #include "mmsystem.h"
34
35 #include "winternl.h"
36
37 #include "wine/unicode.h"
38 #include "wine/debug.h"
39
40 #include "parser.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
43
44 #define SEQUENCE_HEADER_CODE     0xB3
45 #define PACK_START_CODE          0xBA
46
47 #define SYSTEM_START_CODE        0xBB
48 #define AUDIO_ELEMENTARY_STREAM  0xC0
49 #define VIDEO_ELEMENTARY_STREAM  0xE0
50
51 #define MPEG_SYSTEM_HEADER 3
52 #define MPEG_VIDEO_HEADER 2
53 #define MPEG_AUDIO_HEADER 1
54 #define MPEG_NO_HEADER 0
55
56 #define SEEK_INTERVAL (ULONGLONG)(10 * 10000000) /* Add an entry every 10 seconds */
57
58 struct seek_entry {
59     ULONGLONG bytepos;
60     ULONGLONG timepos;
61 };
62
63 typedef struct MPEGSplitterImpl
64 {
65     ParserImpl Parser;
66     IMediaSample *pCurrentSample;
67     LONGLONG EndOfFile;
68     LONGLONG duration;
69     LONGLONG position;
70     DWORD begin_offset;
71     BYTE header[4];
72
73     /* Whether we just seeked (or started playing) */
74     BOOL seek;
75
76     /* Seeking cache */
77     ULONG seek_entries;
78     struct seek_entry *seektable;
79 } MPEGSplitterImpl;
80
81 static int MPEGSplitter_head_check(const BYTE *header)
82 {
83     /* If this is a possible start code, check for a system or video header */
84     if (header[0] == 0 && header[1] == 0 && header[2] == 1)
85     {
86         /* Check if we got a system or elementary stream start code */
87         if (header[3] == PACK_START_CODE ||
88             header[3] == VIDEO_ELEMENTARY_STREAM ||
89             header[3] == AUDIO_ELEMENTARY_STREAM)
90             return MPEG_SYSTEM_HEADER;
91
92         /* Check for a MPEG video sequence start code */
93         if (header[3] == SEQUENCE_HEADER_CODE)
94             return MPEG_VIDEO_HEADER;
95     }
96
97     /* This should give a good guess if we have an MPEG audio header */
98     if(header[0] == 0xff && ((header[1]>>5)&0x7) == 0x7 &&
99        ((header[1]>>1)&0x3) != 0 && ((header[2]>>4)&0xf) != 0xf &&
100        ((header[2]>>2)&0x3) != 0x3)
101         return MPEG_AUDIO_HEADER;
102
103     /* Nothing yet.. */
104     return MPEG_NO_HEADER;
105 }
106
107 static const WCHAR wszAudioStream[] = {'A','u','d','i','o',0};
108 static const WCHAR wszVideoStream[] = {'V','i','d','e','o',0};
109
110 static const DWORD freqs[10] = { 44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000,  8000, 0 };
111
112 static const DWORD tabsel_123[2][3][16] = {
113     { {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,},
114       {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,},
115       {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,} },
116
117     { {0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,},
118       {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,},
119       {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,} }
120 };
121
122 static HRESULT parse_header(BYTE *header, LONGLONG *plen, LONGLONG *pduration)
123 {
124     LONGLONG duration;
125
126     int bitrate_index, freq_index, lsf = 1, mpeg1, layer, padding, bitrate, length;
127
128     if (!(header[0] == 0xff && ((header[1]>>5)&0x7) == 0x7 &&
129        ((header[1]>>1)&0x3) != 0 && ((header[2]>>4)&0xf) != 0xf &&
130        ((header[2]>>2)&0x3) != 0x3))
131     {
132         FIXME("Not a valid header: %02x:%02x\n", header[0], header[1]);
133         return E_INVALIDARG;
134     }
135
136     mpeg1 = (header[1]>>4)&0x1;
137     if (mpeg1)
138         lsf = ((header[1]>>3)&0x1)^1;
139
140     layer = 4-((header[1]>>1)&0x3);
141     bitrate_index = ((header[2]>>4)&0xf);
142     freq_index = ((header[2]>>2)&0x3) + (mpeg1?(lsf*3):6);
143     padding = ((header[2]>>1)&0x1);
144
145     bitrate = tabsel_123[lsf][layer-1][bitrate_index] * 1000;
146     if (!bitrate || layer != 3)
147     {
148         FIXME("Not a valid header: %02x:%02x:%02x:%02x\n", header[0], header[1], header[2], header[3]);
149         return E_INVALIDARG;
150     }
151
152
153     if (layer == 3 || layer == 2)
154         length = 144 * bitrate / freqs[freq_index] + padding;
155     else
156         length = 4 * (12 * bitrate / freqs[freq_index] + padding);
157
158     duration = (ULONGLONG)10000000 * (ULONGLONG)(length) / (ULONGLONG)(bitrate/8);
159     *plen = length;
160     if (pduration)
161         *pduration += duration;
162     return S_OK;
163 }
164
165 static HRESULT FillBuffer(MPEGSplitterImpl *This, IMediaSample *pCurrentSample)
166 {
167     Parser_OutputPin * pOutputPin = (Parser_OutputPin*)This->Parser.ppPins[1];
168     LONGLONG length = 0;
169     LONGLONG pos = BYTES_FROM_MEDIATIME(This->Parser.pInputPin->rtNext);
170     LONGLONG time = This->position;
171     HRESULT hr;
172     BYTE *fbuf = NULL;
173     DWORD len = IMediaSample_GetActualDataLength(pCurrentSample);
174
175     TRACE("Source length: %u\n", len);
176     IMediaSample_GetPointer(pCurrentSample, &fbuf);
177
178     /* Find the next valid header.. it <SHOULD> be right here */
179     assert(parse_header(fbuf, &length, &This->position) == S_OK);
180     assert(length == len || length + 4 == len);
181     IMediaSample_SetActualDataLength(pCurrentSample, length);
182
183     if (length + 4 == len)
184     {
185         PullPin *pin = This->Parser.pInputPin;
186         LONGLONG stop = BYTES_FROM_MEDIATIME(pin->rtStop);
187
188         hr = S_OK;
189         memcpy(This->header, fbuf + length, 4);
190         while (FAILED(hr = parse_header(This->header, &length, NULL)))
191         {
192             memmove(This->header, This->header+1, 3);
193             if (pos + 4 >= stop)
194                 break;
195             IAsyncReader_SyncRead(pin->pReader, ++pos, 1, This->header + 3);
196         }
197         pin->rtNext = MEDIATIME_FROM_BYTES(pos);
198
199         if (SUCCEEDED(hr))
200         {
201             /* Remove 4 for the last header, which should hopefully work */
202             IMediaSample *sample = NULL;
203             LONGLONG rtSampleStart = pin->rtNext - MEDIATIME_FROM_BYTES(4);
204             LONGLONG rtSampleStop = rtSampleStart + MEDIATIME_FROM_BYTES(length + 4);
205
206             hr = IMemAllocator_GetBuffer(pin->pAlloc, &sample, NULL, NULL, 0);
207
208             if (rtSampleStop > pin->rtStop)
209                 rtSampleStop = MEDIATIME_FROM_BYTES(ALIGNUP(BYTES_FROM_MEDIATIME(pin->rtStop), pin->cbAlign));
210
211             IMediaSample_SetTime(sample, &rtSampleStart, &rtSampleStop);
212             IMediaSample_SetPreroll(sample, 0);
213             IMediaSample_SetDiscontinuity(sample, 0);
214             IMediaSample_SetSyncPoint(sample, 1);
215             pin->rtCurrent = rtSampleStart;
216             pin->rtNext = rtSampleStop;
217
218             if (SUCCEEDED(hr))
219                 hr = IAsyncReader_Request(pin->pReader, sample, 0);
220             if (FAILED(hr))
221                 FIXME("o_Ox%08x\n", hr);
222         }
223     }
224     /* If not, we're presumably at the end of file */
225
226     TRACE("Media time : %u.%03u\n", (DWORD)(This->position/10000000), (DWORD)((This->position/10000)%1000));
227
228     IMediaSample_SetTime(pCurrentSample, &time, &This->position);
229
230     hr = OutputPin_SendSample(&pOutputPin->pin, pCurrentSample);
231
232     if (hr != S_OK)
233     {
234         if (hr != S_FALSE)
235             TRACE("Error sending sample (%x)\n", hr);
236         else
237             TRACE("S_FALSE (%d), holding\n", IMediaSample_GetActualDataLength(pCurrentSample));
238     }
239
240     return hr;
241 }
242
243
244 static HRESULT MPEGSplitter_process_sample(LPVOID iface, IMediaSample * pSample, DWORD_PTR cookie)
245 {
246     MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
247     BYTE *pbSrcStream;
248     DWORD cbSrcStream = 0;
249     REFERENCE_TIME tStart, tStop;
250     Parser_OutputPin * pOutputPin;
251     HRESULT hr;
252
253     pOutputPin = (Parser_OutputPin*)This->Parser.ppPins[1];
254
255     hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
256     if (SUCCEEDED(hr))
257     {
258         cbSrcStream = IMediaSample_GetActualDataLength(pSample);
259         hr = IMediaSample_GetPointer(pSample, &pbSrcStream);
260     }
261
262     /* Flush occuring */
263     if (cbSrcStream == 0)
264     {
265         FIXME(".. Why do I need you?\n");
266         return S_OK;
267     }
268
269     /* trace removed for performance reasons */
270     /* TRACE("(%p), %llu -> %llu\n", pSample, tStart, tStop); */
271
272     /* Try to get rid of current sample, if any */
273     if (This->pCurrentSample)
274     {
275         Parser_OutputPin * pOutputPin = (Parser_OutputPin*)This->Parser.ppPins[1];
276         IMediaSample *pCurrentSample = This->pCurrentSample;
277
278         /* Requeue buffer */
279         hr = OutputPin_SendSample(&pOutputPin->pin, pCurrentSample);
280
281         if (hr != S_OK)
282         {
283             Sleep(10);
284             TRACE("Yuck!\n");
285             IMediaSample_AddRef(pSample);
286             IAsyncReader_Request(This->Parser.pInputPin->pReader, pSample, 0);
287             return hr;
288         }
289
290         IMediaSample_Release(This->pCurrentSample);
291         This->pCurrentSample = NULL;
292     }
293
294     /* Now, try to find a new header */
295     hr = FillBuffer(This, pSample);
296     if (hr != S_OK)
297     {
298         /* We still have our sample! Do damage control and send it next round */
299
300         WARN("Failed with hres: %08x!\n", hr);
301
302         /* If set to S_FALSE we keep the sample, to transmit it next time */
303         if (hr == S_FALSE)
304         {
305             This->pCurrentSample = pSample;
306             IMediaSample_AddRef(This->pCurrentSample);
307         }
308
309         /* Sample was rejected because of whatever reason (paused/flushing/etc), no need to terminate the processing */
310         if (hr == S_FALSE)
311             hr = S_OK;
312     }
313
314     if (BYTES_FROM_MEDIATIME(tStop) >= This->EndOfFile || This->position >= This->Parser.mediaSeeking.llStop)
315     {
316         int i;
317
318         TRACE("End of file reached\n");
319
320         for (i = 0; i < This->Parser.cStreams; i++)
321         {
322             IPin* ppin;
323
324             hr = IPin_ConnectedTo(This->Parser.ppPins[i+1], &ppin);
325             if (SUCCEEDED(hr))
326             {
327                 hr = IPin_EndOfStream(ppin);
328                 IPin_Release(ppin);
329             }
330             if (FAILED(hr))
331                 WARN("Error sending EndOfStream to pin %d (%x)\n", i, hr);
332         }
333
334         /* Force the pullpin thread to stop */
335         hr = S_FALSE;
336     }
337
338     return hr;
339 }
340
341
342 static HRESULT MPEGSplitter_query_accept(LPVOID iface, const AM_MEDIA_TYPE *pmt)
343 {
344     if (!IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream))
345         return S_FALSE;
346
347     if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1Audio))
348         return S_OK;
349
350     if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1Video))
351         FIXME("MPEG-1 video streams not yet supported.\n");
352     else if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1System))
353         FIXME("MPEG-1 system streams not yet supported.\n");
354     else if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1VideoCD))
355         FIXME("MPEG-1 VideoCD streams not yet supported.\n");
356
357     return S_FALSE;
358 }
359
360
361 static HRESULT MPEGSplitter_init_audio(MPEGSplitterImpl *This, const BYTE *header, PIN_INFO *ppiOutput, AM_MEDIA_TYPE *pamt)
362 {
363     WAVEFORMATEX *format;
364     int bitrate_index;
365     int freq_index;
366     int mode_ext;
367     int emphasis;
368     int lsf = 1;
369     int mpeg1;
370     int layer;
371     int mode;
372
373     ZeroMemory(pamt, sizeof(*pamt));
374     ppiOutput->dir = PINDIR_OUTPUT;
375     ppiOutput->pFilter = (IBaseFilter*)This;
376     wsprintfW(ppiOutput->achName, wszAudioStream);
377
378     pamt->formattype = FORMAT_WaveFormatEx;
379     pamt->majortype = MEDIATYPE_Audio;
380     pamt->subtype = MEDIASUBTYPE_MPEG1AudioPayload;
381
382     pamt->lSampleSize = 0;
383     pamt->bFixedSizeSamples = FALSE;
384     pamt->bTemporalCompression = 0;
385
386     mpeg1 = (header[1]>>4)&0x1;
387     if (mpeg1)
388         lsf = ((header[1]>>3)&0x1)^1;
389
390     layer         = 4-((header[1]>>1)&0x3);
391     bitrate_index =   ((header[2]>>4)&0xf);
392     freq_index    =   ((header[2]>>2)&0x3) + (mpeg1?(lsf*3):6);
393     mode          =   ((header[3]>>6)&0x3);
394     mode_ext      =   ((header[3]>>4)&0x3);
395     emphasis      =   ((header[3]>>0)&0x3);
396
397     if (!bitrate_index)
398     {
399         /* Set to highest bitrate so samples will fit in for sure */
400         FIXME("Variable-bitrate audio not fully supported.\n");
401         bitrate_index = 15;
402     }
403
404     pamt->cbFormat = ((layer==3)? sizeof(MPEGLAYER3WAVEFORMAT) :
405                                   sizeof(MPEG1WAVEFORMAT));
406     pamt->pbFormat = CoTaskMemAlloc(pamt->cbFormat);
407     if (!pamt->pbFormat)
408         return E_OUTOFMEMORY;
409     ZeroMemory(pamt->pbFormat, pamt->cbFormat);
410     format = (WAVEFORMATEX*)pamt->pbFormat;
411
412     format->wFormatTag      = ((layer == 3) ? WAVE_FORMAT_MPEGLAYER3 :
413                                               WAVE_FORMAT_MPEG);
414     format->nChannels       = ((mode == 3) ? 1 : 2);
415     format->nSamplesPerSec  = freqs[freq_index];
416     format->nAvgBytesPerSec = tabsel_123[lsf][layer-1][bitrate_index] * 1000 / 8;
417
418     if (layer == 3)
419         format->nBlockAlign = format->nAvgBytesPerSec * 8 * 144 /
420                               (format->nSamplesPerSec<<lsf) + 1;
421     else if (layer == 2)
422         format->nBlockAlign = format->nAvgBytesPerSec * 8 * 144 /
423                               format->nSamplesPerSec + 1;
424     else
425         format->nBlockAlign = 4 * (format->nAvgBytesPerSec * 8 * 12 / format->nSamplesPerSec + 1);
426
427     format->wBitsPerSample = 0;
428
429     if (layer == 3)
430     {
431         MPEGLAYER3WAVEFORMAT *mp3format = (MPEGLAYER3WAVEFORMAT*)format;
432
433         format->cbSize = MPEGLAYER3_WFX_EXTRA_BYTES;
434
435         mp3format->wID = MPEGLAYER3_ID_MPEG;
436         mp3format->fdwFlags = MPEGLAYER3_FLAG_PADDING_ON;
437         mp3format->nBlockSize = format->nBlockAlign;
438         mp3format->nFramesPerBlock = 1;
439
440         /* Beware the evil magic numbers. This struct is apparently horribly
441          * under-documented, and the only references I could find had it being
442          * set to this with no real explanation. It works fine though, so I'm
443          * not complaining (yet).
444          */
445         mp3format->nCodecDelay = 1393;
446     }
447     else
448     {
449         MPEG1WAVEFORMAT *mpgformat = (MPEG1WAVEFORMAT*)format;
450
451         format->cbSize = 22;
452
453         mpgformat->fwHeadLayer   = ((layer == 1) ? ACM_MPEG_LAYER1 :
454                                     ((layer == 2) ? ACM_MPEG_LAYER2 :
455                                      ACM_MPEG_LAYER3));
456         mpgformat->dwHeadBitrate = format->nAvgBytesPerSec * 8;
457         mpgformat->fwHeadMode    = ((mode == 3) ? ACM_MPEG_SINGLECHANNEL :
458                                     ((mode == 2) ? ACM_MPEG_DUALCHANNEL :
459                                      ((mode == 1) ? ACM_MPEG_JOINTSTEREO :
460                                       ACM_MPEG_STEREO)));
461         mpgformat->fwHeadModeExt = ((mode == 1) ? 0x0F : (1<<mode_ext));
462         mpgformat->wHeadEmphasis = emphasis + 1;
463         mpgformat->fwHeadFlags   = ACM_MPEG_ID_MPEG1;
464     }
465     pamt->subtype.Data1 = format->wFormatTag;
466
467     TRACE("MPEG audio stream detected:\n"
468           "\tLayer %d (%#x)\n"
469           "\tFrequency: %d\n"
470           "\tChannels: %d (%d)\n"
471           "\tBytesPerSec: %d\n",
472           layer, format->wFormatTag, format->nSamplesPerSec,
473           format->nChannels, mode, format->nAvgBytesPerSec);
474
475     dump_AM_MEDIA_TYPE(pamt);
476
477     return S_OK;
478 }
479
480
481 static HRESULT MPEGSplitter_pre_connect(IPin *iface, IPin *pConnectPin, ALLOCATOR_PROPERTIES *props)
482 {
483     PullPin *pPin = (PullPin *)iface;
484     MPEGSplitterImpl *This = (MPEGSplitterImpl*)pPin->pin.pinInfo.pFilter;
485     HRESULT hr;
486     LONGLONG pos = 0; /* in bytes */
487     BYTE header[10];
488     int streamtype = 0;
489     LONGLONG total, avail;
490     AM_MEDIA_TYPE amt;
491     PIN_INFO piOutput;
492
493     IAsyncReader_Length(pPin->pReader, &total, &avail);
494     This->EndOfFile = total;
495
496     hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
497     if (SUCCEEDED(hr))
498         pos += 4;
499
500     /* Skip ID3 v2 tag, if any */
501     if (SUCCEEDED(hr) && !strncmp("ID3", (char*)header, 3))
502     do {
503         UINT length;
504         hr = IAsyncReader_SyncRead(pPin->pReader, pos, 6, header + 4);
505         if (FAILED(hr))
506             break;
507         pos += 6;
508         TRACE("Found ID3 v2.%d.%d\n", header[3], header[4]);
509         length  = (header[6] & 0x7F) << 21;
510         length += (header[7] & 0x7F) << 14;
511         length += (header[8] & 0x7F) << 7;
512         length += (header[9] & 0x7F);
513         TRACE("Length: %u\n", length);
514         pos += length;
515
516         /* Read the real header for the mpeg splitter */
517         hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
518         if (SUCCEEDED(hr))
519             pos += 4;
520         TRACE("%x:%x:%x:%x\n", header[0], header[1], header[2], header[3]);
521     } while (0);
522
523     while(SUCCEEDED(hr) && !(streamtype=MPEGSplitter_head_check(header)))
524     {
525         TRACE("%x:%x:%x:%x\n", header[0], header[1], header[2], header[3]);
526         /* No valid header yet; shift by a byte and check again */
527         memmove(header, header+1, 3);
528         hr = IAsyncReader_SyncRead(pPin->pReader, pos++, 1, header + 3);
529     }
530     if (FAILED(hr))
531         return hr;
532     pos -= 4;
533     This->begin_offset = pos;
534     memcpy(This->header, header, 4);
535
536     This->seektable[0].bytepos = pos;
537     This->seektable[0].timepos = 0;
538
539     switch(streamtype)
540     {
541         case MPEG_AUDIO_HEADER:
542         {
543             LONGLONG duration = 0;
544             DWORD last_entry = 0;
545
546             DWORD ticks = GetTickCount();
547
548             hr = MPEGSplitter_init_audio(This, header, &piOutput, &amt);
549             if (SUCCEEDED(hr))
550             {
551                 WAVEFORMATEX *format = (WAVEFORMATEX*)amt.pbFormat;
552
553                 props->cbAlign = 1;
554                 props->cbPrefix = 0;
555                 /* Make the output buffer a multiple of the frame size */
556                 props->cbBuffer = 0x4000 / format->nBlockAlign *
557                                  format->nBlockAlign;
558                 props->cBuffers = 2;
559                 hr = Parser_AddPin(&(This->Parser), &piOutput, props, &amt);
560             }
561
562             if (FAILED(hr))
563             {
564                 if (amt.pbFormat)
565                     CoTaskMemFree(amt.pbFormat);
566                 ERR("Could not create pin for MPEG audio stream (%x)\n", hr);
567                 break;
568             }
569
570             /* Check for idv1 tag, and remove it from stream if found */
571             hr = IAsyncReader_SyncRead(pPin->pReader, This->EndOfFile-128, 3, header+4);
572             if (FAILED(hr))
573                 break;
574             if (!strncmp((char*)header+4, "TAG", 3))
575                 This->EndOfFile -= 128;
576             This->Parser.pInputPin->rtStop = MEDIATIME_FROM_BYTES(This->EndOfFile);
577             This->Parser.pInputPin->rtStart = This->Parser.pInputPin->rtCurrent = MEDIATIME_FROM_BYTES(This->begin_offset);
578
579             /* http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm has a whole read up on audio headers */
580             while (pos + 3 < This->EndOfFile)
581             {
582                 LONGLONG length = 0;
583                 hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
584                 if (hr != S_OK)
585                     break;
586                 while (parse_header(header, &length, &duration))
587                 {
588                     /* No valid header yet; shift by a byte and check again */
589                     memmove(header, header+1, 3);
590                     hr = IAsyncReader_SyncRead(pPin->pReader, pos++, 1, header + 3);
591                     if (hr != S_OK || This->EndOfFile - pos < 4)
592                        break;
593                 }
594                 pos += length;
595
596                 if (This->seektable && (duration / SEEK_INTERVAL) > last_entry)
597                 {
598                     if (last_entry + 1 > duration / SEEK_INTERVAL)
599                     {
600                         ERR("Somehow skipped %d interval lengths instead of 1\n", (DWORD)(duration/SEEK_INTERVAL) - (last_entry + 1));
601                     }
602                     ++last_entry;
603
604                     TRACE("Entry: %u\n", last_entry);
605                     if (last_entry >= This->seek_entries)
606                     {
607                         This->seek_entries += 64;
608                         This->seektable = CoTaskMemRealloc(This->seektable, (This->seek_entries)*sizeof(struct seek_entry));
609                     }
610                     This->seektable[last_entry].bytepos = pos;
611                     This->seektable[last_entry].timepos = duration;
612                 }
613
614                 TRACE("Pos: %x%08x/%x%08x\n", (DWORD)(pos >> 32), (DWORD)pos, (DWORD)(This->EndOfFile>>32), (DWORD)This->EndOfFile);
615             }
616             hr = S_OK;
617             TRACE("Duration: %d seconds\n", (DWORD)(duration / 10000000));
618             TRACE("Parsing took %u ms\n", GetTickCount() - ticks);
619             This->duration = duration;
620
621             This->Parser.mediaSeeking.llCurrent = 0;
622             This->Parser.mediaSeeking.llDuration = duration;
623             This->Parser.mediaSeeking.llStop = duration;
624             break;
625         }
626         case MPEG_VIDEO_HEADER:
627             FIXME("MPEG video processing not yet supported!\n");
628             hr = E_FAIL;
629             break;
630         case MPEG_SYSTEM_HEADER:
631             FIXME("MPEG system streams not yet supported!\n");
632             hr = E_FAIL;
633             break;
634
635         default:
636             break;
637     }
638     This->position = 0;
639
640     return hr;
641 }
642
643 static HRESULT MPEGSplitter_cleanup(LPVOID iface)
644 {
645     MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
646
647     TRACE("(%p) Deleting sample\n", This);
648
649     if (This->pCurrentSample)
650         IMediaSample_Release(This->pCurrentSample);
651     This->pCurrentSample = NULL;
652
653     return S_OK;
654 }
655
656 static HRESULT MPEGSplitter_seek(IBaseFilter *iface)
657 {
658     MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
659     PullPin *pPin = This->Parser.pInputPin;
660     LONGLONG newpos, timepos, bytepos;
661     HRESULT hr = S_OK;
662     BYTE header[4];
663
664     newpos = This->Parser.mediaSeeking.llCurrent;
665
666     if (newpos > This->duration)
667     {
668         WARN("Requesting position %x%08x beyond end of stream %x%08x\n", (DWORD)(newpos>>32), (DWORD)newpos, (DWORD)(This->duration>>32), (DWORD)This->duration);
669         return E_INVALIDARG;
670     }
671
672     if (This->position/1000000 == newpos/1000000)
673     {
674         TRACE("Requesting position %x%08x same as current position %x%08x\n", (DWORD)(newpos>>32), (DWORD)newpos, (DWORD)(This->position>>32), (DWORD)This->position);
675         return S_OK;
676     }
677
678     /* Position, cached */
679     bytepos = This->seektable[newpos / SEEK_INTERVAL].bytepos;
680     timepos = This->seektable[newpos / SEEK_INTERVAL].timepos;
681
682     hr = IAsyncReader_SyncRead(pPin->pReader, bytepos, 4, header);
683     while (bytepos + 3 < This->EndOfFile)
684     {
685         LONGLONG length = 0;
686         hr = IAsyncReader_SyncRead(pPin->pReader, bytepos, 4, header);
687         if (hr != S_OK || timepos >= newpos)
688             break;
689
690         while (parse_header(header, &length, &timepos) && bytepos + 3 < This->EndOfFile)
691         {
692             /* No valid header yet; shift by a byte and check again */
693             memmove(header, header+1, 3);
694             hr = IAsyncReader_SyncRead(pPin->pReader, ++bytepos, 1, header + 3);
695             if (hr != S_OK)
696                 break;
697          }
698          bytepos += length;
699          TRACE("Pos: %x%08x/%x%08x\n", (DWORD)(bytepos >> 32), (DWORD)bytepos, (DWORD)(This->EndOfFile>>32), (DWORD)This->EndOfFile);
700     }
701
702     if (SUCCEEDED(hr))
703     {
704         PullPin *pin = This->Parser.pInputPin;
705         IPin *victim = NULL;
706
707         TRACE("Moving sound to %08u bytes!\n", (DWORD)bytepos);
708
709         EnterCriticalSection(&pin->thread_lock);
710         IPin_BeginFlush((IPin *)pin);
711
712         /* Make sure this is done while stopped, BeginFlush takes care of this */
713         EnterCriticalSection(&This->Parser.csFilter);
714         memcpy(This->header, header, 4);
715         IPin_ConnectedTo(This->Parser.ppPins[1], &victim);
716         if (victim)
717         {
718             IPin_NewSegment(victim, newpos, This->duration, pin->dRate);
719             IPin_Release(victim);
720         }
721
722         pin->rtStart = pin->rtCurrent = MEDIATIME_FROM_BYTES(bytepos);
723         pin->rtStop = MEDIATIME_FROM_BYTES((REFERENCE_TIME)This->EndOfFile);
724         This->seek = TRUE;
725         This->position = newpos;
726         LeaveCriticalSection(&This->Parser.csFilter);
727
728         TRACE("Done flushing\n");
729         IPin_EndFlush((IPin *)pin);
730         LeaveCriticalSection(&pin->thread_lock);
731     }
732     return hr;
733 }
734
735 static HRESULT MPEGSplitter_disconnect(LPVOID iface)
736 {
737     /* TODO: Find memory leaks etc */
738     return S_OK;
739 }
740
741 static HRESULT MPEGSplitter_first_request(LPVOID iface)
742 {
743     MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
744     PullPin *pin = This->Parser.pInputPin;
745     HRESULT hr;
746     LONGLONG length;
747     IMediaSample *sample;
748
749     TRACE("Seeking? %d\n", This->seek);
750     assert(parse_header(This->header, &length, NULL) == S_OK);
751
752     if (pin->rtCurrent >= pin->rtStop)
753     {
754         /* Last sample has already been queued, request nothing more */
755         FIXME("Done!\n");
756         return S_OK;
757     }
758
759     hr = IMemAllocator_GetBuffer(pin->pAlloc, &sample, NULL, NULL, 0);
760
761     pin->rtNext = pin->rtCurrent;
762     if (SUCCEEDED(hr))
763     {
764         LONGLONG rtSampleStart = pin->rtNext;
765         /* Add 4 for the next header, which should hopefully work */
766         LONGLONG rtSampleStop = rtSampleStart + MEDIATIME_FROM_BYTES(length + 4);
767
768         if (rtSampleStop > pin->rtStop)
769             rtSampleStop = MEDIATIME_FROM_BYTES(ALIGNUP(BYTES_FROM_MEDIATIME(pin->rtStop), pin->cbAlign));
770
771         hr = IMediaSample_SetTime(sample, &rtSampleStart, &rtSampleStop);
772
773         pin->rtCurrent = pin->rtNext;
774         pin->rtNext = rtSampleStop;
775
776         IMediaSample_SetPreroll(sample, FALSE);
777         IMediaSample_SetDiscontinuity(sample, This->seek);
778         IMediaSample_SetSyncPoint(sample, 1);
779         This->seek = 0;
780
781         hr = IAsyncReader_Request(pin->pReader, sample, 0);
782     }
783     if (FAILED(hr))
784         ERR("Horsemen of the apocalypse came to bring error 0x%08x\n", hr);
785
786     return hr;
787 }
788
789 static const IBaseFilterVtbl MPEGSplitter_Vtbl =
790 {
791     Parser_QueryInterface,
792     Parser_AddRef,
793     Parser_Release,
794     Parser_GetClassID,
795     Parser_Stop,
796     Parser_Pause,
797     Parser_Run,
798     Parser_GetState,
799     Parser_SetSyncSource,
800     Parser_GetSyncSource,
801     Parser_EnumPins,
802     Parser_FindPin,
803     Parser_QueryFilterInfo,
804     Parser_JoinFilterGraph,
805     Parser_QueryVendorInfo
806 };
807
808 HRESULT MPEGSplitter_create(IUnknown * pUnkOuter, LPVOID * ppv)
809 {
810     MPEGSplitterImpl *This;
811     HRESULT hr = E_FAIL;
812
813     TRACE("(%p, %p)\n", pUnkOuter, ppv);
814
815     *ppv = NULL;
816
817     if (pUnkOuter)
818         return CLASS_E_NOAGGREGATION;
819
820     This = CoTaskMemAlloc(sizeof(MPEGSplitterImpl));
821     if (!This)
822         return E_OUTOFMEMORY;
823
824     ZeroMemory(This, sizeof(MPEGSplitterImpl));
825     This->seektable = CoTaskMemAlloc(sizeof(struct seek_entry) * 64);
826     if (!This->seektable)
827     {
828         CoTaskMemFree(This);
829         return E_OUTOFMEMORY;
830     }
831     This->seek_entries = 64;
832
833     hr = Parser_Create(&(This->Parser), &MPEGSplitter_Vtbl, &CLSID_MPEG1Splitter, MPEGSplitter_process_sample, MPEGSplitter_query_accept, MPEGSplitter_pre_connect, MPEGSplitter_cleanup, MPEGSplitter_disconnect, MPEGSplitter_first_request, NULL, MPEGSplitter_seek, NULL);
834     if (FAILED(hr))
835     {
836         CoTaskMemFree(This);
837         return hr;
838     }
839     This->seek = 1;
840
841     /* Note: This memory is managed by the parser filter once created */
842     *ppv = (LPVOID)This;
843
844     return hr;
845 }