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