4 * Copyright 2003 Robert Shearman
5 * Copyright 2004-2005 Christian Costa
6 * Copyright 2007 Chris Robinson
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.
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.
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
26 #include "quartz_private.h"
27 #include "control_private.h"
36 #include "wine/unicode.h"
37 #include "wine/debug.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
43 #define SEQUENCE_HEADER_CODE 0xB3
44 #define PACK_START_CODE 0xBA
46 #define SYSTEM_START_CODE 0xBB
47 #define AUDIO_ELEMENTARY_STREAM 0xC0
48 #define VIDEO_ELEMENTARY_STREAM 0xE0
50 #define MPEG_SYSTEM_HEADER 3
51 #define MPEG_VIDEO_HEADER 2
52 #define MPEG_AUDIO_HEADER 1
53 #define MPEG_NO_HEADER 0
55 typedef struct MPEGSplitterImpl
58 IMediaSample *pCurrentSample;
63 DWORD remaining_bytes;
66 static int MPEGSplitter_head_check(const BYTE *header)
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)
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;
77 /* Check for a MPEG video sequence start code */
78 if (header[3] == SEQUENCE_HEADER_CODE)
79 return MPEG_VIDEO_HEADER;
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;
89 return MPEG_NO_HEADER;
92 static const WCHAR wszAudioStream[] = {'A','u','d','i','o',0};
93 static const WCHAR wszVideoStream[] = {'V','i','d','e','o',0};
95 static const DWORD freqs[10] = { 44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000, 0 };
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,} },
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,} }
108 static HRESULT parse_header(BYTE *header, LONGLONG *plen, LONGLONG *pduration)
110 LONGLONG duration = *pduration;
112 int bitrate_index, freq_index, mode_ext, emphasis, lsf = 1, mpeg1, layer, mode, padding, bitrate, length;
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))
118 WARN("Not a valid header: %02x:%02x\n", header[0], header[1]);
122 mpeg1 = (header[1]>>4)&0x1;
124 lsf = ((header[1]>>3)&0x1)^1;
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);
134 bitrate = tabsel_123[lsf][layer-1][bitrate_index] * 1000;
135 if (layer == 3 || layer == 2)
136 length = 144 * bitrate / freqs[freq_index] + padding;
138 length = 4 * (12 * bitrate / freqs[freq_index] + padding);
140 duration = (ULONGLONG)10000000 * (ULONGLONG)(length) / (ULONGLONG)(bitrate/8);
142 *pduration += duration;
147 static void skip_data(BYTE** from, DWORD *flen, DWORD amount)
156 static HRESULT copy_data(IMediaSample *to, BYTE** from, DWORD *flen, DWORD amount)
160 DWORD oldlength = IMediaSample_GetActualDataLength(to);
162 hr = IMediaSample_SetActualDataLength(to, oldlength + amount);
165 if (!oldlength || oldlength <= 4)
166 WARN("Could not set require length\n");
170 IMediaSample_GetPointer(to, &ptr);
171 memcpy(ptr + oldlength, *from, amount);
172 skip_data(from, flen, amount);
176 static HRESULT FillBuffer(MPEGSplitterImpl *This, BYTE** fbuf, DWORD *flen)
178 Parser_OutputPin * pOutputPin = (Parser_OutputPin*)This->Parser.ppPins[1];
182 LONGLONG time = This->position, sampleduration = 0;
184 TRACE("Source length: %u, skip length: %u, remaining: %u\n", *flen, This->skipbytes, This->remaining_bytes);
186 /* Case where bytes are skipped */
189 DWORD skip = min(This->skipbytes, *flen);
190 skip_data(fbuf, flen, skip);
191 This->skipbytes -= skip;
195 /* Case where there is already an output sample being held */
196 if (This->remaining_bytes)
198 DWORD towrite = min(This->remaining_bytes, *flen);
200 hr = copy_data(This->pCurrentSample, fbuf, flen, towrite);
203 WARN("Could not resize sample: %08x\n", hr);
207 This->remaining_bytes -= towrite;
208 if (This->remaining_bytes)
211 /* Optimize: Try appending more samples to the stream */
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)
222 /* Shoot anyone with a small sample! */
225 hr = IMediaSample_GetPointer(This->pCurrentSample, &header);
228 hr = IMediaSample_SetActualDataLength(This->pCurrentSample, 7);
232 WARN("Could not resize sample: %08x\n", hr);
236 memcpy(header + dlen, *fbuf, 6 - dlen);
238 while (FAILED(parse_header(header+attempts, &length, &This->position)) && attempts < dlen)
243 /* No header found */
244 if (attempts == dlen)
246 hr = IMediaSample_SetActualDataLength(This->pCurrentSample, 0);
250 IMediaSample_SetActualDataLength(This->pCurrentSample, 4);
251 IMediaSample_SetTime(This->pCurrentSample, &time, &This->position);
253 /* Move header back to beginning */
255 memmove(header, header+attempts, 4);
257 This->remaining_bytes = length - 4;
258 *flen -= (4 - dlen + attempts);
259 *fbuf += (4 - dlen + attempts);
263 /* Destination sample should contain no data! But the source sample should */
267 /* Find the next valid header.. it <SHOULD> be right here */
268 while (*flen > 3 && FAILED(parse_header(*fbuf, &length, &This->position)))
270 skip_data(fbuf, flen, 1);
273 /* Uh oh, no header found! */
277 hr = copy_data(This->pCurrentSample, fbuf, flen, *flen);
281 IMediaSample_SetTime(This->pCurrentSample, &time, &This->position);
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);
291 hr = copy_data(This->pCurrentSample, fbuf, flen, length);
294 WARN("Couldn't set data size to %x%08x\n", (DWORD)(length >> 32), (DWORD)length);
295 This->skipbytes = length;
300 /* Optimize: Send multiple samples! */
303 if (FAILED(parse_header(*fbuf, &length, &sampleduration)))
309 if (FAILED(copy_data(This->pCurrentSample, fbuf, flen, length)))
312 This->position += sampleduration;
314 IMediaSample_SetTime(This->pCurrentSample, &time, &This->position);
316 TRACE("Media time: %u.%03u\n", (DWORD)(This->position/10000000), (DWORD)((This->position/10000)%1000));
318 hr = OutputPin_SendSample(&pOutputPin->pin, This->pCurrentSample);
320 WARN("Error sending sample (%x)\n", hr);
322 IMediaSample_Release(This->pCurrentSample);
323 This->pCurrentSample = NULL;
328 static HRESULT MPEGSplitter_process_sample(LPVOID iface, IMediaSample * pSample)
330 MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
332 DWORD cbSrcStream = 0;
333 REFERENCE_TIME tStart, tStop;
334 Parser_OutputPin * pOutputPin;
337 pOutputPin = (Parser_OutputPin*)This->Parser.ppPins[1];
339 hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
342 cbSrcStream = IMediaSample_GetActualDataLength(pSample);
343 hr = IMediaSample_GetPointer(pSample, &pbSrcStream);
346 /* trace removed for performance reasons */
347 /* TRACE("(%p), %llu -> %llu\n", pSample, tStart, tStop); */
349 /* Now, try to find a new header */
350 while (cbSrcStream > 0)
352 if (!This->pCurrentSample)
354 if (FAILED(hr = OutputPin_GetDeliveryBuffer(&pOutputPin->pin, &This->pCurrentSample, NULL, NULL, 0)))
356 FIXME("Failed with hres: %08x!\n", hr);
360 IMediaSample_SetTime(This->pCurrentSample, NULL, NULL);
361 if (FAILED(hr = IMediaSample_SetActualDataLength(This->pCurrentSample, 0)))
363 IMediaSample_SetSyncPoint(This->pCurrentSample, TRUE);
365 hr = FillBuffer(This, &pbSrcStream, &cbSrcStream);
373 FIXME("Failed with hres: %08x!\n", hr);
374 This->skipbytes += This->remaining_bytes;
375 This->remaining_bytes = 0;
376 if (This->pCurrentSample)
378 IMediaSample_SetActualDataLength(This->pCurrentSample, 0);
379 IMediaSample_Release(This->pCurrentSample);
380 This->pCurrentSample = NULL;
384 if (BYTES_FROM_MEDIATIME(tStop) >= This->EndOfFile)
388 TRACE("End of file reached\n");
390 if (This->pCurrentSample)
392 /* Drop last data, it's likely to be garbage anyway */
393 IMediaSample_SetActualDataLength(This->pCurrentSample, 0);
394 IMediaSample_Release(This->pCurrentSample);
395 This->pCurrentSample = NULL;
398 for (i = 0; i < This->Parser.cStreams; i++)
403 TRACE("Send End Of Stream to output pin %d\n", i);
405 hr = IPin_ConnectedTo(This->Parser.ppPins[i+1], &ppin);
408 hr = IPin_EndOfStream(ppin);
412 WARN("Error sending EndOfStream to pin %d (%x)\n", i, hr);
415 /* Force the pullpin thread to stop */
423 static HRESULT MPEGSplitter_query_accept(LPVOID iface, const AM_MEDIA_TYPE *pmt)
425 if (!IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream))
428 if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1Audio))
431 if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1Video))
432 FIXME("MPEG-1 video streams not yet supported.\n");
433 else if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1System))
434 FIXME("MPEG-1 system streams not yet supported.\n");
435 else if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1VideoCD))
436 FIXME("MPEG-1 VideoCD streams not yet supported.\n");
442 static HRESULT MPEGSplitter_init_audio(MPEGSplitterImpl *This, const BYTE *header, PIN_INFO *ppiOutput, AM_MEDIA_TYPE *pamt)
444 WAVEFORMATEX *format;
454 ZeroMemory(pamt, sizeof(*pamt));
455 ppiOutput->dir = PINDIR_OUTPUT;
456 ppiOutput->pFilter = (IBaseFilter*)This;
457 wsprintfW(ppiOutput->achName, wszAudioStream);
459 pamt->formattype = FORMAT_WaveFormatEx;
460 pamt->majortype = MEDIATYPE_Audio;
461 pamt->subtype = MEDIASUBTYPE_MPEG1AudioPayload;
463 pamt->lSampleSize = 0;
464 pamt->bFixedSizeSamples = FALSE;
465 pamt->bTemporalCompression = 0;
467 mpeg1 = (header[1]>>4)&0x1;
469 lsf = ((header[1]>>3)&0x1)^1;
471 layer = 4-((header[1]>>1)&0x3);
472 bitrate_index = ((header[2]>>4)&0xf);
473 freq_index = ((header[2]>>2)&0x3) + (mpeg1?(lsf*3):6);
474 mode = ((header[3]>>6)&0x3);
475 mode_ext = ((header[3]>>4)&0x3);
476 emphasis = ((header[3]>>0)&0x3);
480 /* Set to highest bitrate so samples will fit in for sure */
481 FIXME("Variable-bitrate audio not fully supported.\n");
485 pamt->cbFormat = ((layer==3)? sizeof(MPEGLAYER3WAVEFORMAT) :
486 sizeof(MPEG1WAVEFORMAT));
487 pamt->pbFormat = CoTaskMemAlloc(pamt->cbFormat);
489 return E_OUTOFMEMORY;
490 ZeroMemory(pamt->pbFormat, pamt->cbFormat);
491 format = (WAVEFORMATEX*)pamt->pbFormat;
493 format->wFormatTag = ((layer == 3) ? WAVE_FORMAT_MPEGLAYER3 :
495 format->nChannels = ((mode == 3) ? 1 : 2);
496 format->nSamplesPerSec = freqs[freq_index];
497 format->nAvgBytesPerSec = tabsel_123[lsf][layer-1][bitrate_index] * 1000 / 8;
500 format->nBlockAlign = format->nAvgBytesPerSec * 8 * 144 /
501 (format->nSamplesPerSec<<lsf) + 1;
503 format->nBlockAlign = format->nAvgBytesPerSec * 8 * 144 /
504 format->nSamplesPerSec + 1;
506 format->nBlockAlign = 4 * (format->nAvgBytesPerSec * 8 * 12 / format->nSamplesPerSec + 1);
508 format->wBitsPerSample = 0;
512 MPEGLAYER3WAVEFORMAT *mp3format = (MPEGLAYER3WAVEFORMAT*)format;
514 format->cbSize = MPEGLAYER3_WFX_EXTRA_BYTES;
516 mp3format->wID = MPEGLAYER3_ID_MPEG;
517 mp3format->fdwFlags = MPEGLAYER3_FLAG_PADDING_ON;
518 mp3format->nBlockSize = format->nBlockAlign;
519 mp3format->nFramesPerBlock = 1;
521 /* Beware the evil magic numbers. This struct is apparently horribly
522 * under-documented, and the only references I could find had it being
523 * set to this with no real explanation. It works fine though, so I'm
524 * not complaining (yet).
526 mp3format->nCodecDelay = 1393;
530 MPEG1WAVEFORMAT *mpgformat = (MPEG1WAVEFORMAT*)format;
534 mpgformat->fwHeadLayer = ((layer == 1) ? ACM_MPEG_LAYER1 :
535 ((layer == 2) ? ACM_MPEG_LAYER2 :
537 mpgformat->dwHeadBitrate = format->nAvgBytesPerSec * 8;
538 mpgformat->fwHeadMode = ((mode == 3) ? ACM_MPEG_SINGLECHANNEL :
539 ((mode == 2) ? ACM_MPEG_DUALCHANNEL :
540 ((mode == 1) ? ACM_MPEG_JOINTSTEREO :
542 mpgformat->fwHeadModeExt = ((mode == 1) ? 0x0F : (1<<mode_ext));
543 mpgformat->wHeadEmphasis = emphasis + 1;
544 mpgformat->fwHeadFlags = ACM_MPEG_ID_MPEG1;
546 pamt->subtype.Data1 = format->wFormatTag;
548 TRACE("MPEG audio stream detected:\n"
551 "\tChannels: %d (%d)\n"
552 "\tBytesPerSec: %d\n",
553 layer, format->wFormatTag, format->nSamplesPerSec,
554 format->nChannels, mode, format->nAvgBytesPerSec);
556 dump_AM_MEDIA_TYPE(pamt);
562 static HRESULT MPEGSplitter_pre_connect(IPin *iface, IPin *pConnectPin)
564 PullPin *pPin = (PullPin *)iface;
565 MPEGSplitterImpl *This = (MPEGSplitterImpl*)pPin->pin.pinInfo.pFilter;
566 ALLOCATOR_PROPERTIES props;
568 LONGLONG pos = 0; /* in bytes */
571 LONGLONG total, avail;
575 IAsyncReader_Length(pPin->pReader, &total, &avail);
576 This->EndOfFile = total;
578 hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
582 /* Skip ID3 v2 tag, if any */
583 if (SUCCEEDED(hr) && !strncmp("ID3", (char*)header, 3))
586 hr = IAsyncReader_SyncRead(pPin->pReader, pos, 6, header + 4);
590 TRACE("Found ID3 v2.%d.%d\n", header[3], header[4]);
591 length = (header[6] & 0x7F) << 21;
592 length += (header[7] & 0x7F) << 14;
593 length += (header[8] & 0x7F) << 7;
594 length += (header[9] & 0x7F);
595 TRACE("Length: %u\n", length);
598 /* Read the real header for the mpeg splitter */
599 hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
602 TRACE("%x:%x:%x:%x\n", header[0], header[1], header[2], header[3]);
605 while(SUCCEEDED(hr) && !(streamtype=MPEGSplitter_head_check(header)))
607 TRACE("%x:%x:%x:%x\n", header[0], header[1], header[2], header[3]);
608 /* No valid header yet; shift by a byte and check again */
609 memmove(header, header+1, 3);
610 hr = IAsyncReader_SyncRead(pPin->pReader, pos++, 1, header + 3);
615 This->skipbytes = pos;
619 case MPEG_AUDIO_HEADER:
621 LONGLONG duration = 0;
622 DWORD ticks = GetTickCount();
624 hr = MPEGSplitter_init_audio(This, header, &piOutput, &amt);
627 WAVEFORMATEX *format = (WAVEFORMATEX*)amt.pbFormat;
631 /* Make the output buffer a multiple of the frame size */
632 props.cbBuffer = 0x4000 / format->nBlockAlign *
635 hr = Parser_AddPin(&(This->Parser), &piOutput, &props, &amt);
641 CoTaskMemFree(amt.pbFormat);
642 ERR("Could not create pin for MPEG audio stream (%x)\n", hr);
646 /* Check for idv1 tag, and remove it from stream if found */
647 hr = IAsyncReader_SyncRead(pPin->pReader, This->EndOfFile-128, 3, header+4);
650 if (!strncmp((char*)header+4, "TAG", 3))
651 This->EndOfFile -= 128;
653 /* http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm has a whole readup on audio headers */
654 while (pos < This->EndOfFile && SUCCEEDED(hr))
657 hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
658 while (parse_header(header, &length, &duration))
660 /* No valid header yet; shift by a byte and check again */
661 memmove(header, header+1, 3);
662 hr = IAsyncReader_SyncRead(pPin->pReader, pos++, 1, header + 3);
667 TRACE("Pos: %x%08x/%x%08x\n", (DWORD)(pos >> 32), (DWORD)pos, (DWORD)(This->EndOfFile>>32), (DWORD)This->EndOfFile);
670 TRACE("Duration: %d seconds\n", (DWORD)(duration / 10000000));
671 TRACE("Parsing took %u ms\n", GetTickCount() - ticks);
674 case MPEG_VIDEO_HEADER:
675 FIXME("MPEG video processing not yet supported!\n");
678 case MPEG_SYSTEM_HEADER:
679 FIXME("MPEG system streams not yet supported!\n");
686 This->remaining_bytes = 0;
692 static HRESULT MPEGSplitter_cleanup(LPVOID iface)
694 MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
696 TRACE("(%p)->()\n", This);
698 if (This->pCurrentSample)
699 IMediaSample_Release(This->pCurrentSample);
700 This->pCurrentSample = NULL;
705 HRESULT MPEGSplitter_create(IUnknown * pUnkOuter, LPVOID * ppv)
707 MPEGSplitterImpl *This;
710 TRACE("(%p, %p)\n", pUnkOuter, ppv);
715 return CLASS_E_NOAGGREGATION;
717 This = CoTaskMemAlloc(sizeof(MPEGSplitterImpl));
719 return E_OUTOFMEMORY;
721 ZeroMemory(This, sizeof(MPEGSplitterImpl));
722 hr = Parser_Create(&(This->Parser), &CLSID_MPEG1Splitter, MPEGSplitter_process_sample, MPEGSplitter_query_accept, MPEGSplitter_pre_connect, MPEGSplitter_cleanup);
729 /* Note: This memory is managed by the parser filter once created */