quartz: Parse audio packets in mpeg splitter to obtain the duration.
[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  *
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
23 #include <assert.h>
24 #include <math.h>
25
26 #include "quartz_private.h"
27 #include "control_private.h"
28 #include "pin.h"
29
30 #include "uuids.h"
31 #include "mmreg.h"
32 #include "mmsystem.h"
33
34 #include "winternl.h"
35
36 #include "wine/unicode.h"
37 #include "wine/debug.h"
38
39 #include "parser.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
42
43 #define SEQUENCE_HEADER_CODE     0xB3
44 #define PACK_START_CODE          0xBA
45
46 #define SYSTEM_START_CODE        0xBB
47 #define AUDIO_ELEMENTARY_STREAM  0xC0
48 #define VIDEO_ELEMENTARY_STREAM  0xE0
49
50 #define MPEG_SYSTEM_HEADER 3
51 #define MPEG_VIDEO_HEADER 2
52 #define MPEG_AUDIO_HEADER 1
53 #define MPEG_NO_HEADER 0
54
55 typedef struct MPEGSplitterImpl
56 {
57     ParserImpl Parser;
58     IMediaSample *pCurrentSample;
59     LONGLONG EndOfFile;
60     LONGLONG duration;
61     LONGLONG position;
62     DWORD skipbytes;
63     DWORD remaining_bytes;
64 } MPEGSplitterImpl;
65
66 static int MPEGSplitter_head_check(const BYTE *header)
67 {
68     /* If this is a possible start code, check for a system or video header */
69     if (header[0] == 0 && header[1] == 0 && header[2] == 1)
70     {
71         /* Check if we got a system or elementary stream start code */
72         if (header[3] == PACK_START_CODE ||
73             header[3] == VIDEO_ELEMENTARY_STREAM ||
74             header[3] == AUDIO_ELEMENTARY_STREAM)
75             return MPEG_SYSTEM_HEADER;
76
77         /* Check for a MPEG video sequence start code */
78         if (header[3] == SEQUENCE_HEADER_CODE)
79             return MPEG_VIDEO_HEADER;
80     }
81
82     /* This should give a good guess if we have an MPEG audio header */
83     if(header[0] == 0xff && ((header[1]>>5)&0x7) == 0x7 &&
84        ((header[1]>>1)&0x3) != 0 && ((header[2]>>4)&0xf) != 0xf &&
85        ((header[2]>>2)&0x3) != 0x3)
86         return MPEG_AUDIO_HEADER;
87
88     /* Nothing yet.. */
89     return MPEG_NO_HEADER;
90 }
91
92 static const WCHAR wszAudioStream[] = {'A','u','d','i','o',0};
93 static const WCHAR wszVideoStream[] = {'V','i','d','e','o',0};
94
95 static const DWORD freqs[10] = { 44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000,  8000, 0 };
96
97 static const DWORD tabsel_123[2][3][16] = {
98     { {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,},
99       {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,},
100       {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,} },
101
102     { {0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,},
103       {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,},
104       {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,} }
105 };
106
107
108 static HRESULT parse_header(BYTE *header, LONGLONG *plen, LONGLONG *pduration)
109 {
110     LONGLONG duration = *pduration;
111
112     int bitrate_index, freq_index, mode_ext, emphasis, lsf = 1, mpeg1, layer, mode, padding, bitrate, length;
113
114     if (!(header[0] == 0xff && ((header[1]>>5)&0x7) == 0x7 &&
115        ((header[1]>>1)&0x3) != 0 && ((header[2]>>4)&0xf) != 0xf &&
116        ((header[2]>>2)&0x3) != 0x3))
117     {
118         WARN("Not a valid header: %02x:%02x\n", header[0], header[1]);
119         return E_INVALIDARG;
120     }
121
122     mpeg1 = (header[1]>>4)&0x1;
123     if (mpeg1)
124         lsf = ((header[1]>>3)&0x1)^1;
125
126     layer = 4-((header[1]>>1)&0x3);
127     bitrate_index = ((header[2]>>4)&0xf);
128     freq_index = ((header[2]>>2)&0x3) + (mpeg1?(lsf*3):6);
129     padding = ((header[2]>>1)&0x1);
130     mode = ((header[3]>>6)&0x3);
131     mode_ext = ((header[3]>>4)&0x3);
132     emphasis = ((header[3]>>0)&0x3);
133
134     bitrate = tabsel_123[lsf][layer-1][bitrate_index] * 1000;
135     if (layer == 3 || layer == 2)
136         length = 144 * bitrate / freqs[freq_index] + padding;
137     else
138         length = 4 * (12 * bitrate / freqs[freq_index] + padding);
139
140     duration = (ULONGLONG)10000000 * (ULONGLONG)(length) / (ULONGLONG)(bitrate/8);
141     *plen = length;
142     *pduration += duration;
143     return S_OK;
144 }
145
146
147 static void skip_data(BYTE** from, DWORD *flen, DWORD amount)
148 {
149     *flen -= amount;
150     if (!*flen)
151         *from = NULL;
152     else
153         *from += amount;
154 }
155
156 static HRESULT copy_data(IMediaSample *to, BYTE** from, DWORD *flen, DWORD amount)
157 {
158     HRESULT hr = S_OK;
159     BYTE *ptr = NULL;
160     DWORD oldlength = IMediaSample_GetActualDataLength(to);
161
162     hr = IMediaSample_SetActualDataLength(to, oldlength + amount);
163     if (FAILED(hr))
164     {
165         if (!oldlength || oldlength <= 4)
166             WARN("Could not set require length\n");
167         return hr;
168     }
169
170     IMediaSample_GetPointer(to, &ptr);
171     memcpy(ptr + oldlength, *from, amount);
172     skip_data(from, flen, amount);
173     return hr;
174 }
175
176 static HRESULT FillBuffer(MPEGSplitterImpl *This, BYTE** fbuf, DWORD *flen)
177 {
178     Parser_OutputPin * pOutputPin = (Parser_OutputPin*)This->Parser.ppPins[1];
179     LONGLONG length = 0;
180     HRESULT hr = S_OK;
181     DWORD dlen;
182     LONGLONG time = This->position, sampleduration = 0;
183
184     TRACE("Source length: %u, skip length: %u, remaining: %u\n", *flen, This->skipbytes, This->remaining_bytes);
185
186     /* Case where bytes are skipped */
187     if (This->skipbytes)
188     {
189         DWORD skip = min(This->skipbytes, *flen);
190         skip_data(fbuf, flen, skip);
191         This->skipbytes -= skip;
192         return S_OK;
193     }
194
195     /* Case where there is already an output sample being held */
196     if (This->remaining_bytes)
197     {
198         DWORD towrite = min(This->remaining_bytes, *flen);
199
200         hr = copy_data(This->pCurrentSample, fbuf, flen, towrite);
201         if (FAILED(hr))
202         {
203             WARN("Could not resize sample: %08x\n", hr);
204             goto release;
205         }
206
207         This->remaining_bytes -= towrite;
208         if (This->remaining_bytes)
209             return hr;
210
211         /* Optimize: Try appending more samples to the stream */
212         goto out_append;
213     }
214
215     /* Special case, last source sample might (or might not have) had a header, and now we want to retrieve it */
216     dlen = IMediaSample_GetActualDataLength(This->pCurrentSample);
217     if (dlen > 0 && dlen < 4)
218     {
219         BYTE *header = NULL;
220         DWORD attempts = 0;
221
222         /* Shoot anyone with a small sample! */
223         assert(*flen >= 6);
224
225         hr = IMediaSample_GetPointer(This->pCurrentSample, &header);
226
227         if (SUCCEEDED(hr))
228             hr = IMediaSample_SetActualDataLength(This->pCurrentSample, 7);
229
230         if (FAILED(hr))
231         {
232             WARN("Could not resize sample: %08x\n", hr);
233             goto release;
234         }
235
236         memcpy(header + dlen, *fbuf, 6 - dlen);
237
238         while (FAILED(parse_header(header+attempts, &length, &This->position)) && attempts < dlen)
239         {
240             attempts++;
241         }
242
243         /* No header found */
244         if (attempts == dlen)
245         {
246             hr = IMediaSample_SetActualDataLength(This->pCurrentSample, 0);
247             return hr;
248         }
249
250         IMediaSample_SetActualDataLength(This->pCurrentSample, 4);
251         IMediaSample_SetTime(This->pCurrentSample, &time, &This->position);
252
253         /* Move header back to beginning */
254         if (attempts)
255             memmove(header, header+attempts, 4);
256
257         This->remaining_bytes = length - 4;
258         *flen -= (4 - dlen + attempts);
259         *fbuf += (4 - dlen + attempts);
260         return hr;
261     }
262
263     /* Destination sample should contain no data! But the source sample should */
264     assert(!dlen);
265     assert(*flen);
266
267     /* Find the next valid header.. it <SHOULD> be right here */
268     while (*flen > 3 && FAILED(parse_header(*fbuf, &length, &This->position)))
269     {
270         skip_data(fbuf, flen, 1);
271     }
272
273     /* Uh oh, no header found! */
274     if (*flen < 4)
275     {
276         assert(!length);
277         hr = copy_data(This->pCurrentSample, fbuf, flen, *flen);
278         return hr;
279     }
280
281     IMediaSample_SetTime(This->pCurrentSample, &time, &This->position);
282
283     if (*flen < length)
284     {
285         /* Partial copy: Copy 4 bytes, the rest will be copied by the logic for This->remaining_bytes */
286         This->remaining_bytes = length - 4;
287         copy_data(This->pCurrentSample, fbuf, flen, 4);
288         return hr;
289     }
290
291     hr = copy_data(This->pCurrentSample, fbuf, flen, length);
292     if (FAILED(hr))
293     {
294         WARN("Couldn't set data size to %lld\n", length);
295         This->skipbytes = length;
296         return hr;
297     }
298
299 out_append:
300     /* Optimize: Send multiple samples! */
301     while (*flen >= 4)
302     {
303         if (FAILED(parse_header(*fbuf, &length, &sampleduration)))
304             break;
305
306         if (length > *flen)
307             break;
308
309         if (FAILED(copy_data(This->pCurrentSample, fbuf, flen, length)))
310             break;
311
312         This->position += sampleduration;
313         sampleduration = 0;
314         IMediaSample_SetTime(This->pCurrentSample, &time, &This->position);
315     }
316     TRACE("Media time: %lld.%03lld\n", (This->position/10000000), (This->position/10000)%1000);
317
318     hr = OutputPin_SendSample(&pOutputPin->pin, This->pCurrentSample);
319     if (FAILED(hr))
320         WARN("Error sending sample (%x)\n", hr);
321 release:
322     IMediaSample_Release(This->pCurrentSample);
323     This->pCurrentSample = NULL;
324     return hr;
325 }
326
327
328 static HRESULT MPEGSplitter_process_sample(LPVOID iface, IMediaSample * pSample)
329 {
330     MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
331     BYTE *pbSrcStream;
332     DWORD cbSrcStream = 0;
333     REFERENCE_TIME tStart, tStop;
334     Parser_OutputPin * pOutputPin;
335     HRESULT hr;
336
337     pOutputPin = (Parser_OutputPin*)This->Parser.ppPins[1];
338
339     hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
340     if (SUCCEEDED(hr))
341     {
342         cbSrcStream = IMediaSample_GetActualDataLength(pSample);
343         hr = IMediaSample_GetPointer(pSample, &pbSrcStream);
344     }
345
346     /* trace removed for performance reasons */
347     /* TRACE("(%p), %llu -> %llu\n", pSample, tStart, tStop); */
348
349     /* Now, try to find a new header */
350     while (cbSrcStream > 0)
351     {
352         if (!This->pCurrentSample)
353         {
354             if (FAILED(hr = OutputPin_GetDeliveryBuffer(&pOutputPin->pin, &This->pCurrentSample, NULL, NULL, 0)))
355             {
356                 FIXME("Failed with hres: %08x!\n", hr);
357                 break;
358             }
359
360             IMediaSample_SetTime(This->pCurrentSample, NULL, NULL);
361             if (FAILED(hr = IMediaSample_SetActualDataLength(This->pCurrentSample, 0)))
362                 goto fail;
363             IMediaSample_SetSyncPoint(This->pCurrentSample, TRUE);
364         }
365         hr = FillBuffer(This, &pbSrcStream, &cbSrcStream);
366         if (SUCCEEDED(hr))
367             continue;
368
369 fail:
370         FIXME("Failed with hres: %08x!\n", hr);
371         This->skipbytes += This->remaining_bytes;
372         This->remaining_bytes = 0;
373         IMediaSample_Release(This->pCurrentSample);
374         This->pCurrentSample = NULL;
375     }
376
377     if (BYTES_FROM_MEDIATIME(tStop) >= This->EndOfFile)
378     {
379         int i;
380
381         TRACE("End of file reached\n");
382
383         if (This->pCurrentSample)
384         {
385             /* Drop last data, it's likely to be garbage anyway */
386             IMediaSample_SetActualDataLength(This->pCurrentSample, 0);
387             IMediaSample_Release(This->pCurrentSample);
388             This->pCurrentSample = NULL;
389         }
390
391         for (i = 0; i < This->Parser.cStreams; i++)
392         {
393             IPin* ppin;
394             HRESULT hr;
395
396             TRACE("Send End Of Stream to output pin %d\n", i);
397
398             hr = IPin_ConnectedTo(This->Parser.ppPins[i+1], &ppin);
399             if (SUCCEEDED(hr))
400             {
401                 hr = IPin_EndOfStream(ppin);
402                 IPin_Release(ppin);
403             }
404             if (FAILED(hr))
405                 WARN("Error sending EndOfStream to pin %d (%x)\n", i, hr);
406         }
407
408         /* Force the pullpin thread to stop */
409         hr = S_FALSE;
410     }
411
412     return hr;
413 }
414
415
416 static HRESULT MPEGSplitter_query_accept(LPVOID iface, const AM_MEDIA_TYPE *pmt)
417 {
418     if (!IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream))
419         return S_FALSE;
420
421     if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1Audio))
422         return S_OK;
423
424     if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1Video))
425         FIXME("MPEG-1 video streams not yet supported.\n");
426     else if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1System))
427         FIXME("MPEG-1 system streams not yet supported.\n");
428     else if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1VideoCD))
429         FIXME("MPEG-1 VideoCD streams not yet supported.\n");
430
431     return S_FALSE;
432 }
433
434
435 static HRESULT MPEGSplitter_init_audio(MPEGSplitterImpl *This, const BYTE *header, PIN_INFO *ppiOutput, AM_MEDIA_TYPE *pamt)
436 {
437     WAVEFORMATEX *format;
438     int bitrate_index;
439     int freq_index;
440     int mode_ext;
441     int emphasis;
442     int lsf = 1;
443     int mpeg1;
444     int layer;
445     int mode;
446
447     ZeroMemory(pamt, sizeof(*pamt));
448     ppiOutput->dir = PINDIR_OUTPUT;
449     ppiOutput->pFilter = (IBaseFilter*)This;
450     wsprintfW(ppiOutput->achName, wszAudioStream);
451
452     pamt->formattype = FORMAT_WaveFormatEx;
453     pamt->majortype = MEDIATYPE_Audio;
454     pamt->subtype = MEDIASUBTYPE_MPEG1AudioPayload;
455
456     pamt->lSampleSize = 0;
457     pamt->bFixedSizeSamples = FALSE;
458     pamt->bTemporalCompression = 0;
459
460     mpeg1 = (header[1]>>4)&0x1;
461     if (mpeg1)
462         lsf = ((header[1]>>3)&0x1)^1;
463
464     layer         = 4-((header[1]>>1)&0x3);
465     bitrate_index =   ((header[2]>>4)&0xf);
466     freq_index    =   ((header[2]>>2)&0x3) + (mpeg1?(lsf*3):6);
467     mode          =   ((header[3]>>6)&0x3);
468     mode_ext      =   ((header[3]>>4)&0x3);
469     emphasis      =   ((header[3]>>0)&0x3);
470
471     if (!bitrate_index)
472     {
473         /* Set to highest bitrate so samples will fit in for sure */
474         FIXME("Variable-bitrate audio not fully supported.\n");
475         bitrate_index = 15;
476     }
477
478     pamt->cbFormat = ((layer==3)? sizeof(MPEGLAYER3WAVEFORMAT) :
479                                   sizeof(MPEG1WAVEFORMAT));
480     pamt->pbFormat = CoTaskMemAlloc(pamt->cbFormat);
481     if (!pamt->pbFormat)
482         return E_OUTOFMEMORY;
483     ZeroMemory(pamt->pbFormat, pamt->cbFormat);
484     format = (WAVEFORMATEX*)pamt->pbFormat;
485
486     format->wFormatTag      = ((layer == 3) ? WAVE_FORMAT_MPEGLAYER3 :
487                                               WAVE_FORMAT_MPEG);
488     format->nChannels       = ((mode == 3) ? 1 : 2);
489     format->nSamplesPerSec  = freqs[freq_index];
490     format->nAvgBytesPerSec = tabsel_123[lsf][layer-1][bitrate_index] * 1000 / 8;
491
492     if (layer == 3)
493         format->nBlockAlign = format->nAvgBytesPerSec * 8 * 144 /
494                               (format->nSamplesPerSec<<lsf) + 1;
495     else if (layer == 2)
496         format->nBlockAlign = format->nAvgBytesPerSec * 8 * 144 /
497                               format->nSamplesPerSec + 1;
498     else
499         format->nBlockAlign = 4 * (format->nAvgBytesPerSec * 8 * 12 / format->nSamplesPerSec + 1);
500
501     format->wBitsPerSample = 0;
502
503     if (layer == 3)
504     {
505         MPEGLAYER3WAVEFORMAT *mp3format = (MPEGLAYER3WAVEFORMAT*)format;
506
507         format->cbSize = MPEGLAYER3_WFX_EXTRA_BYTES;
508
509         mp3format->wID = MPEGLAYER3_ID_MPEG;
510         mp3format->fdwFlags = MPEGLAYER3_FLAG_PADDING_ON;
511         mp3format->nBlockSize = format->nBlockAlign;
512         mp3format->nFramesPerBlock = 1;
513
514         /* Beware the evil magic numbers. This struct is apparently horribly
515          * under-documented, and the only references I could find had it being
516          * set to this with no real explanation. It works fine though, so I'm
517          * not complaining (yet).
518          */
519         mp3format->nCodecDelay = 1393;
520     }
521     else
522     {
523         MPEG1WAVEFORMAT *mpgformat = (MPEG1WAVEFORMAT*)format;
524
525         format->cbSize = 22;
526
527         mpgformat->fwHeadLayer   = ((layer == 1) ? ACM_MPEG_LAYER1 :
528                                     ((layer == 2) ? ACM_MPEG_LAYER2 :
529                                      ACM_MPEG_LAYER3));
530         mpgformat->dwHeadBitrate = format->nAvgBytesPerSec * 8;
531         mpgformat->fwHeadMode    = ((mode == 3) ? ACM_MPEG_SINGLECHANNEL :
532                                     ((mode == 2) ? ACM_MPEG_DUALCHANNEL :
533                                      ((mode == 1) ? ACM_MPEG_JOINTSTEREO :
534                                       ACM_MPEG_STEREO)));
535         mpgformat->fwHeadModeExt = ((mode == 1) ? 0x0F : (1<<mode_ext));
536         mpgformat->wHeadEmphasis = emphasis + 1;
537         mpgformat->fwHeadFlags   = ACM_MPEG_ID_MPEG1;
538     }
539     pamt->subtype.Data1 = format->wFormatTag;
540
541     TRACE("MPEG audio stream detected:\n"
542           "\tLayer %d (%#x)\n"
543           "\tFrequency: %d\n"
544           "\tChannels: %d (%d)\n"
545           "\tBytesPerSec: %d\n",
546           layer, format->wFormatTag, format->nSamplesPerSec,
547           format->nChannels, mode, format->nAvgBytesPerSec);
548
549     dump_AM_MEDIA_TYPE(pamt);
550
551     return S_OK;
552 }
553
554
555 static HRESULT MPEGSplitter_pre_connect(IPin *iface, IPin *pConnectPin)
556 {
557     PullPin *pPin = (PullPin *)iface;
558     MPEGSplitterImpl *This = (MPEGSplitterImpl*)pPin->pin.pinInfo.pFilter;
559     ALLOCATOR_PROPERTIES props;
560     HRESULT hr;
561     LONGLONG pos = 0; /* in bytes */
562     BYTE header[10];
563     int streamtype = 0;
564     LONGLONG total, avail;
565     AM_MEDIA_TYPE amt;
566     PIN_INFO piOutput;
567
568     IAsyncReader_Length(pPin->pReader, &total, &avail);
569     This->EndOfFile = total;
570
571     hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
572     if (SUCCEEDED(hr))
573         pos += 4;
574
575     /* Skip ID3 v2 tag, if any */
576     if (SUCCEEDED(hr) && !strncmp("ID3", (char*)header, 3))
577     do {
578         UINT length;
579         hr = IAsyncReader_SyncRead(pPin->pReader, pos, 6, header + 4);
580         if (FAILED(hr))
581             break;
582         pos += 6;
583         TRACE("Found ID3 v2.%d.%d\n", header[3], header[4]);
584         length  = (header[6] & 0x7F) << 21;
585         length += (header[7] & 0x7F) << 14;
586         length += (header[8] & 0x7F) << 7;
587         length += (header[9] & 0x7F);
588         TRACE("Length: %u\n", length);
589         pos += length;
590
591         /* Read the real header for the mpeg splitter */
592         hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
593         if (SUCCEEDED(hr))
594             pos += 4;
595         TRACE("%x:%x:%x:%x\n", header[0], header[1], header[2], header[3]);
596     } while (0);
597
598     while(SUCCEEDED(hr) && !(streamtype=MPEGSplitter_head_check(header)))
599     {
600         TRACE("%x:%x:%x:%x\n", header[0], header[1], header[2], header[3]);
601         /* No valid header yet; shift by a byte and check again */
602         memmove(header, header+1, 3);
603         hr = IAsyncReader_SyncRead(pPin->pReader, pos++, 1, header + 3);
604     }
605     if (FAILED(hr))
606         return hr;
607     pos -= 4;
608     This->skipbytes = pos;
609
610     switch(streamtype)
611     {
612         case MPEG_AUDIO_HEADER:
613         {
614             LONGLONG duration = 0;
615             DWORD ticks = GetTickCount();
616
617             hr = MPEGSplitter_init_audio(This, header, &piOutput, &amt);
618             if (SUCCEEDED(hr))
619             {
620                 WAVEFORMATEX *format = (WAVEFORMATEX*)amt.pbFormat;
621
622                 props.cbAlign = 1;
623                 props.cbPrefix = 0;
624                 /* Make the output buffer a multiple of the frame size */
625                 props.cbBuffer = 0x4000 / format->nBlockAlign *
626                                  format->nBlockAlign;
627                 props.cBuffers = 1;
628                 hr = Parser_AddPin(&(This->Parser), &piOutput, &props, &amt);
629             }
630
631             if (FAILED(hr))
632             {
633                 if (amt.pbFormat)
634                     CoTaskMemFree(amt.pbFormat);
635                 ERR("Could not create pin for MPEG audio stream (%x)\n", hr);
636                 break;
637             }
638
639             /* Check for idv1 tag, and remove it from stream if found */
640             hr = IAsyncReader_SyncRead(pPin->pReader, This->EndOfFile-128, 3, header+4);
641             if (FAILED(hr))
642                 break;
643             if (!strncmp((char*)header+4, "TAG", 3))
644                 This->EndOfFile -= 128;
645
646             /* http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm has a whole readup on audio headers */
647             while (pos < This->EndOfFile && SUCCEEDED(hr))
648             {
649                 LONGLONG length = 0;
650                 while (parse_header(header, &length, &duration))
651                 {
652                     /* No valid header yet; shift by a byte and check again */
653                     memmove(header, header+1, 3);
654                     hr = IAsyncReader_SyncRead(pPin->pReader, pos++, 1, header + 3);
655                     if (FAILED(hr))
656                        break;
657                 }
658                 if (SUCCEEDED(hr))
659                 {
660                     pos += length;
661                     hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
662                 }
663             }
664             hr = S_OK;
665             TRACE("Duration: %lld seconds\n", duration / 10000000);
666             TRACE("Parsing took %u ms\n", GetTickCount() - ticks);
667             break;
668         }
669         case MPEG_VIDEO_HEADER:
670             FIXME("MPEG video processing not yet supported!\n");
671             hr = E_FAIL;
672             break;
673         case MPEG_SYSTEM_HEADER:
674             FIXME("MPEG system streams not yet supported!\n");
675             hr = E_FAIL;
676             break;
677
678         default:
679             break;
680     }
681     This->remaining_bytes = 0;
682     This->position = 0;
683
684     return hr;
685 }
686
687 static HRESULT MPEGSplitter_cleanup(LPVOID iface)
688 {
689     MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
690
691     TRACE("(%p)->()\n", This);
692
693     if (This->pCurrentSample)
694         IMediaSample_Release(This->pCurrentSample);
695     This->pCurrentSample = NULL;
696
697     return S_OK;
698 }
699
700 HRESULT MPEGSplitter_create(IUnknown * pUnkOuter, LPVOID * ppv)
701 {
702     MPEGSplitterImpl *This;
703     HRESULT hr = E_FAIL;
704
705     TRACE("(%p, %p)\n", pUnkOuter, ppv);
706
707     *ppv = NULL;
708
709     if (pUnkOuter)
710         return CLASS_E_NOAGGREGATION;
711
712     This = CoTaskMemAlloc(sizeof(MPEGSplitterImpl));
713     if (!This)
714         return E_OUTOFMEMORY;
715
716     ZeroMemory(This, sizeof(MPEGSplitterImpl));
717     hr = Parser_Create(&(This->Parser), &CLSID_MPEG1Splitter, MPEGSplitter_process_sample, MPEGSplitter_query_accept, MPEGSplitter_pre_connect, MPEGSplitter_cleanup);
718     if (FAILED(hr))
719     {
720         CoTaskMemFree(This);
721         return hr;
722     }
723
724     /* Note: This memory is managed by the parser filter once created */
725     *ppv = (LPVOID)This;
726
727     return hr;
728 }