shell32: Only print "HCR_GetFolderAttributes should be called for simple PIDL's"...
[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
56 typedef struct MPEGSplitterImpl
57 {
58     ParserImpl Parser;
59     IMediaSample *pCurrentSample;
60     LONGLONG EndOfFile;
61 } MPEGSplitterImpl;
62
63 static int MPEGSplitter_head_check(const BYTE *header)
64 {
65     /* If this is a possible start code, check for a system or video header */
66     if (header[0] == 0 && header[1] == 0 && header[2] == 1)
67     {
68         /* Check if we got a system or elementary stream start code */
69         if (header[3] == PACK_START_CODE ||
70             header[3] == VIDEO_ELEMENTARY_STREAM ||
71             header[3] == AUDIO_ELEMENTARY_STREAM)
72             return MPEG_SYSTEM_HEADER;
73
74         /* Check for a MPEG video sequence start code */
75         if (header[3] == SEQUENCE_HEADER_CODE)
76             return MPEG_VIDEO_HEADER;
77     }
78
79     /* This should give a good guess if we have an MPEG audio header */
80     if(header[0] == 0xff && ((header[1]>>5)&0x7) == 0x7 &&
81        ((header[1]>>1)&0x3) != 0 && ((header[2]>>4)&0xf) != 0xf &&
82        ((header[2]>>2)&0x3) != 0x3)
83         return MPEG_AUDIO_HEADER;
84
85     /* Nothing yet.. */
86     return MPEG_NO_HEADER;
87 }
88
89
90 static HRESULT MPEGSplitter_process_sample(LPVOID iface, IMediaSample * pSample)
91 {
92     MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
93     LPBYTE pbSrcStream = NULL;
94     DWORD cbSrcStream = 0;
95     DWORD used_bytes = 0;
96     REFERENCE_TIME tStart, tStop;
97     HRESULT hr;
98     BYTE *pbDstStream;
99     DWORD cbDstStream;
100     long remaining_bytes = 0;
101     Parser_OutputPin * pOutputPin;
102     DWORD bytes_written = 0;
103
104     pOutputPin = (Parser_OutputPin*)This->Parser.ppPins[1];
105
106     hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
107     if (SUCCEEDED(hr))
108     {
109         cbSrcStream = IMediaSample_GetActualDataLength(pSample);
110         hr = IMediaSample_GetPointer(pSample, &pbSrcStream);
111     }
112
113     /* trace removed for performance reasons */
114     /* TRACE("(%p), %llu -> %llu\n", pSample, tStart, tStop); */
115
116     if (This->pCurrentSample)
117         bytes_written = IMediaSample_GetActualDataLength(This->pCurrentSample);
118
119     while (hr == S_OK && used_bytes < cbSrcStream)
120     {
121         remaining_bytes = (long)(This->EndOfFile - BYTES_FROM_MEDIATIME(tStart) - used_bytes);
122         if (remaining_bytes <= 0)
123             break;
124
125         if (!This->pCurrentSample)
126         {
127             /* cache media sample until it is ready to be despatched
128              * (i.e. we reach the end of the chunk) */
129             hr = OutputPin_GetDeliveryBuffer(&pOutputPin->pin, &This->pCurrentSample, NULL, NULL, 0);
130             if (FAILED(hr))
131             {
132                 TRACE("Skipping sending sample due to error (%x)\n", hr);
133                 This->pCurrentSample = NULL;
134                 break;
135             }
136
137             IMediaSample_SetTime(This->pCurrentSample, NULL, NULL);
138             hr = IMediaSample_SetActualDataLength(This->pCurrentSample, 0);
139             assert(hr == S_OK);
140             bytes_written = 0;
141         }
142
143         hr = IMediaSample_GetPointer(This->pCurrentSample, &pbDstStream);
144         if (SUCCEEDED(hr))
145         {
146             cbDstStream = IMediaSample_GetSize(This->pCurrentSample);
147             remaining_bytes = min(remaining_bytes, (long)(cbDstStream - bytes_written));
148
149             assert(remaining_bytes >= 0);
150
151             /* trace removed for performance reasons */
152             /* TRACE("remaining_bytes: %d, cbSrcStream: 0x%x\n", remaining_bytes, cbSrcStream); */
153         }
154
155         if (remaining_bytes <= (long)(cbSrcStream-used_bytes))
156         {
157             if (SUCCEEDED(hr))
158             {
159                 memcpy(pbDstStream + bytes_written, pbSrcStream + used_bytes, remaining_bytes);
160                 bytes_written += remaining_bytes;
161
162                 hr = IMediaSample_SetActualDataLength(This->pCurrentSample, bytes_written);
163                 assert(hr == S_OK);
164
165                 used_bytes += remaining_bytes;
166             }
167
168             if (SUCCEEDED(hr))
169             {
170                 REFERENCE_TIME tMPEGStart, tMPEGStop;
171
172                 pOutputPin->dwSamplesProcessed = (BYTES_FROM_MEDIATIME(tStart)+used_bytes) / pOutputPin->dwSampleSize;
173
174                 tMPEGStart = (tStart + MEDIATIME_FROM_BYTES(used_bytes-bytes_written)) /
175                              (pOutputPin->fSamplesPerSec*pOutputPin->dwSampleSize);
176                 tMPEGStop  = (tStart + MEDIATIME_FROM_BYTES(used_bytes)) /
177                              (pOutputPin->fSamplesPerSec*pOutputPin->dwSampleSize);
178
179                 /* If the start of the sample has a valid MPEG header, it's a
180                  * sync point */
181                 if (MPEGSplitter_head_check(pbDstStream) == MPEG_AUDIO_HEADER)
182                     IMediaSample_SetSyncPoint(This->pCurrentSample, TRUE);
183                 else
184                     IMediaSample_SetSyncPoint(This->pCurrentSample, FALSE);
185                 IMediaSample_SetTime(This->pCurrentSample, &tMPEGStart, &tMPEGStop);
186
187                 hr = OutputPin_SendSample(&pOutputPin->pin, This->pCurrentSample);
188                 if (FAILED(hr))
189                     WARN("Error sending sample (%x)\n", hr);
190             }
191
192             if (This->pCurrentSample)
193                 IMediaSample_Release(This->pCurrentSample);
194             This->pCurrentSample = NULL;
195         }
196         else
197         {
198             if (SUCCEEDED(hr))
199             {
200                 memcpy(pbDstStream + bytes_written, pbSrcStream + used_bytes, cbSrcStream - used_bytes);
201                 bytes_written += cbSrcStream - used_bytes;
202                 IMediaSample_SetActualDataLength(This->pCurrentSample, bytes_written);
203
204                 used_bytes += cbSrcStream - used_bytes;
205             }
206         }
207     }
208
209     if (BYTES_FROM_MEDIATIME(tStop) >= This->EndOfFile)
210     {
211         int i;
212
213         TRACE("End of file reached (%d out of %d bytes used)\n", used_bytes, cbSrcStream);
214
215         if (This->pCurrentSample)
216         {
217             /* Make sure the last bit of data, if any, is sent */
218             if (IMediaSample_GetActualDataLength(This->pCurrentSample) > 0)
219             {
220                 REFERENCE_TIME tMPEGStart, tMPEGStop;
221
222                 pOutputPin->dwSamplesProcessed = (BYTES_FROM_MEDIATIME(tStart)+used_bytes) / pOutputPin->dwSampleSize;
223
224                 tMPEGStart = (tStart + MEDIATIME_FROM_BYTES(used_bytes-bytes_written)) /
225                              (pOutputPin->fSamplesPerSec*pOutputPin->dwSampleSize);
226                 tMPEGStop  = (tStart + MEDIATIME_FROM_BYTES(used_bytes)) /
227                              (pOutputPin->fSamplesPerSec*pOutputPin->dwSampleSize);
228
229                 if (MPEGSplitter_head_check(pbDstStream) == MPEG_AUDIO_HEADER)
230                     IMediaSample_SetSyncPoint(This->pCurrentSample, TRUE);
231                 else
232                     IMediaSample_SetSyncPoint(This->pCurrentSample, FALSE);
233                 IMediaSample_SetTime(This->pCurrentSample, &tMPEGStart, &tMPEGStop);
234
235                 hr = OutputPin_SendSample(&pOutputPin->pin, This->pCurrentSample);
236                 if (FAILED(hr))
237                     WARN("Error sending sample (%x)\n", hr);
238             }
239             IMediaSample_Release(This->pCurrentSample);
240         }
241         This->pCurrentSample = NULL;
242
243         for (i = 0; i < This->Parser.cStreams; i++)
244         {
245             IPin* ppin;
246             HRESULT hr;
247
248             TRACE("Send End Of Stream to output pin %d\n", i);
249
250             hr = IPin_ConnectedTo(This->Parser.ppPins[i+1], &ppin);
251             if (SUCCEEDED(hr))
252             {
253                 hr = IPin_EndOfStream(ppin);
254                 IPin_Release(ppin);
255             }
256             if (FAILED(hr))
257                 WARN("Error sending EndOfStream to pin %d (%x)\n", i, hr);
258         }
259
260         /* Force the pullpin thread to stop */
261         hr = S_FALSE;
262     }
263
264     return hr;
265 }
266
267
268 static HRESULT MPEGSplitter_query_accept(LPVOID iface, const AM_MEDIA_TYPE *pmt)
269 {
270     if (!IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream))
271         return S_FALSE;
272
273     if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1Audio))
274         return S_OK;
275
276     if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1Video))
277         FIXME("MPEG-1 video streams not yet supported.\n");
278     else if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1System))
279         FIXME("MPEG-1 system streams not yet supported.\n");
280     else if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_MPEG1VideoCD))
281         FIXME("MPEG-1 VideoCD streams not yet supported.\n");
282
283     return S_FALSE;
284 }
285
286
287 static const WCHAR wszAudioStream[] = {'A','u','d','i','o',0};
288 static const WCHAR wszVideoStream[] = {'V','i','d','e','o',0};
289
290 static HRESULT MPEGSplitter_init_audio(MPEGSplitterImpl *This, const BYTE *header, PIN_INFO *ppiOutput, AM_MEDIA_TYPE *pamt)
291 {
292     static const DWORD freqs[10] = { 44100, 48000, 32000, 22050, 24000,
293                                      16000, 11025, 12000,  8000, 0 };
294     static const DWORD tabsel_123[2][3][16] = {
295         { {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,},
296           {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,},
297           {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,} },
298
299         { {0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,},
300           {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,},
301           {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,} }
302     };
303
304     WAVEFORMATEX *format;
305     int bitrate_index;
306     int freq_index;
307     int mode_ext;
308     int emphasis;
309     int padding;
310     int lsf = 1;
311     int mpeg1;
312     int layer;
313     int mode;
314
315     ZeroMemory(pamt, sizeof(*pamt));
316     ppiOutput->dir = PINDIR_OUTPUT;
317     ppiOutput->pFilter = (IBaseFilter*)This;
318     wsprintfW(ppiOutput->achName, wszAudioStream);
319
320     pamt->formattype = FORMAT_WaveFormatEx;
321     pamt->majortype = MEDIATYPE_Audio;
322     pamt->subtype = MEDIASUBTYPE_MPEG1AudioPayload;
323
324     pamt->lSampleSize = 0;
325     pamt->bFixedSizeSamples = TRUE;
326     pamt->bTemporalCompression = 0;
327
328     mpeg1 = (header[1]>>4)&0x1;
329     if (mpeg1)
330         lsf = ((header[1]>>3)&0x1)^1;
331
332     layer         = 4-((header[1]>>1)&0x3);
333     bitrate_index =   ((header[2]>>4)&0xf);
334     freq_index    =   ((header[2]>>2)&0x3) + (mpeg1?(lsf*3):6);
335     padding       =   ((header[2]>>1)&0x1);
336     mode          =   ((header[3]>>6)&0x3);
337     mode_ext      =   ((header[3]>>4)&0x3);
338     emphasis      =   ((header[3]>>0)&0x3);
339
340     pamt->cbFormat = ((layer==3)? sizeof(MPEGLAYER3WAVEFORMAT) :
341                                   sizeof(MPEG1WAVEFORMAT));
342     pamt->pbFormat = CoTaskMemAlloc(pamt->cbFormat);
343     if (!pamt->pbFormat)
344         return E_OUTOFMEMORY;
345     ZeroMemory(pamt->pbFormat, pamt->cbFormat);
346     format = (WAVEFORMATEX*)pamt->pbFormat;
347
348     format->wFormatTag      = ((layer == 3) ? WAVE_FORMAT_MPEGLAYER3 :
349                                               WAVE_FORMAT_MPEG);
350     format->nChannels       = ((mode == 3) ? 1 : 2);
351     format->nSamplesPerSec  = freqs[freq_index];
352     format->nAvgBytesPerSec = tabsel_123[lsf][layer-1][bitrate_index] * 1000 / 8;
353     if (format->nAvgBytesPerSec == 0)
354     {
355         WARN("Variable-bitrate audio is not supported.\n");
356         return E_FAIL;
357     }
358
359     if (layer == 3)
360         format->nBlockAlign = format->nAvgBytesPerSec * 8 * 144 /
361                               (format->nSamplesPerSec<<lsf) +
362                               (padding - 4);
363     else if (layer == 2)
364         format->nBlockAlign = format->nAvgBytesPerSec * 8 * 144 /
365                               format->nSamplesPerSec + (padding - 4);
366     else
367         format->nBlockAlign = ((format->nAvgBytesPerSec * 8 * 12 /
368                                 format->nSamplesPerSec + padding) << 2) - 4;
369
370     format->wBitsPerSample = 0;
371
372     if (layer == 3)
373     {
374         MPEGLAYER3WAVEFORMAT *mp3format = (MPEGLAYER3WAVEFORMAT*)format;
375
376         format->cbSize = MPEGLAYER3_WFX_EXTRA_BYTES;
377
378         mp3format->wID = MPEGLAYER3_ID_MPEG;
379         mp3format->fdwFlags = (padding ?
380                                MPEGLAYER3_FLAG_PADDING_OFF :
381                                MPEGLAYER3_FLAG_PADDING_ON);
382         mp3format->nBlockSize = format->nBlockAlign;
383         mp3format->nFramesPerBlock = 1;
384
385         /* Beware the evil magic numbers. This struct is apparently horribly
386          * under-documented, and the only references I could find had it being
387          * set to this with no real explanation. It works fine though, so I'm
388          * not complaining (yet).
389          */
390         mp3format->nCodecDelay = 1393;
391     }
392     else
393     {
394         MPEG1WAVEFORMAT *mpgformat = (MPEG1WAVEFORMAT*)format;
395
396         format->cbSize = 22;
397
398         mpgformat->fwHeadLayer   = ((layer == 1) ? ACM_MPEG_LAYER1 :
399                                     ((layer == 2) ? ACM_MPEG_LAYER2 :
400                                      ACM_MPEG_LAYER3));
401         mpgformat->dwHeadBitrate = format->nAvgBytesPerSec * 8;
402         mpgformat->fwHeadMode    = ((mode == 3) ? ACM_MPEG_SINGLECHANNEL :
403                                     ((mode == 2) ? ACM_MPEG_DUALCHANNEL :
404                                      ((mode == 1) ? ACM_MPEG_JOINTSTEREO :
405                                       ACM_MPEG_STEREO)));
406         mpgformat->fwHeadModeExt = ((mode == 1) ? 0x0F : (1<<mode_ext));
407         mpgformat->wHeadEmphasis = emphasis + 1;
408         mpgformat->fwHeadFlags   = ACM_MPEG_ID_MPEG1;
409     }
410     pamt->subtype.Data1 = format->wFormatTag;
411
412     TRACE("MPEG audio stream detected:\n"
413           "\tLayer %d (%#x)\n"
414           "\tFrequency: %d\n"
415           "\tChannels: %d (%d)\n"
416           "\tBytesPerSec: %d\n",
417           layer, format->wFormatTag, format->nSamplesPerSec,
418           format->nChannels, mode, format->nAvgBytesPerSec);
419
420     dump_AM_MEDIA_TYPE(pamt);
421
422     return S_OK;
423 }
424
425
426 static HRESULT MPEGSplitter_pre_connect(IPin *iface, IPin *pConnectPin)
427 {
428     PullPin *pPin = (PullPin *)iface;
429     MPEGSplitterImpl *This = (MPEGSplitterImpl*)pPin->pin.pinInfo.pFilter;
430     ALLOCATOR_PROPERTIES props;
431     HRESULT hr;
432     LONGLONG pos = 0; /* in bytes */
433     BYTE header[10];
434     int streamtype = 0;
435     LONGLONG total, avail;
436     AM_MEDIA_TYPE amt;
437     PIN_INFO piOutput;
438
439     IAsyncReader_Length(pPin->pReader, &total, &avail);
440     This->EndOfFile = total;
441
442     hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
443     if (SUCCEEDED(hr))
444         pos += 4;
445
446     /* Skip ID3 v2 tag, if any */
447     if (SUCCEEDED(hr) && !strncmp("ID3", (char*)header, 3))
448     do {
449         UINT length;
450         hr = IAsyncReader_SyncRead(pPin->pReader, pos, 6, header + 4);
451         if (FAILED(hr))
452             break;
453         pos += 6;
454         TRACE("Found ID3 v2.%d.%d\n", header[3], header[4]);
455         length  = (header[6] & 0x7F) << 21;
456         length += (header[7] & 0x7F) << 14;
457         length += (header[8] & 0x7F) << 7;
458         length += (header[9] & 0x7F);
459         TRACE("Length: %u\n", length);
460         pos += length;
461
462         /* Read the real header for the mpeg splitter */
463         hr = IAsyncReader_SyncRead(pPin->pReader, pos, 4, header);
464         if (SUCCEEDED(hr))
465             pos += 4;
466         TRACE("%x:%x:%x:%x\n", header[0], header[1], header[2], header[3]);
467     } while (0);
468
469     while(SUCCEEDED(hr) && !(streamtype=MPEGSplitter_head_check(header)))
470     {
471         TRACE("%x:%x:%x:%x\n", header[0], header[1], header[2], header[3]);
472         /* No valid header yet; shift by a byte and check again */
473         memcpy(header, header+1, 3);
474         hr = IAsyncReader_SyncRead(pPin->pReader, pos++, 1, header + 3);
475     }
476     if (FAILED(hr))
477         return hr;
478
479     switch(streamtype)
480     {
481         case MPEG_AUDIO_HEADER:
482             hr = MPEGSplitter_init_audio(This, header, &piOutput, &amt);
483             if (SUCCEEDED(hr))
484             {
485                 WAVEFORMATEX *format = (WAVEFORMATEX*)amt.pbFormat;
486
487                 props.cbAlign = 1;
488                 props.cbPrefix = 0;
489                 /* Make the output buffer a multiple of the frame size */
490                 props.cbBuffer = 0x4000 / format->nBlockAlign *
491                                  format->nBlockAlign;
492                 props.cBuffers = 1;
493
494                 hr = Parser_AddPin(&(This->Parser), &piOutput, &props, &amt,
495                                    (float)format->nAvgBytesPerSec /
496                                     (float)format->nBlockAlign,
497                                    format->nBlockAlign,
498                                    total);
499             }
500
501             if (FAILED(hr))
502             {
503                 if (amt.pbFormat)
504                     CoTaskMemFree(amt.pbFormat);
505                 ERR("Could not create pin for MPEG audio stream (%x)\n", hr);
506             }
507             break;
508         case MPEG_VIDEO_HEADER:
509             FIXME("MPEG video processing not yet supported!\n");
510             hr = E_FAIL;
511             break;
512         case MPEG_SYSTEM_HEADER:
513             FIXME("MPEG system streams not yet supported!\n");
514             hr = E_FAIL;
515             break;
516
517         default:
518             break;
519     }
520
521     return hr;
522 }
523
524 static HRESULT MPEGSplitter_cleanup(LPVOID iface)
525 {
526     MPEGSplitterImpl *This = (MPEGSplitterImpl*)iface;
527
528     TRACE("(%p)->()\n", This);
529
530     if (This->pCurrentSample)
531         IMediaSample_Release(This->pCurrentSample);
532     This->pCurrentSample = NULL;
533
534     return S_OK;
535 }
536
537 HRESULT MPEGSplitter_create(IUnknown * pUnkOuter, LPVOID * ppv)
538 {
539     MPEGSplitterImpl *This;
540     HRESULT hr = E_FAIL;
541
542     TRACE("(%p, %p)\n", pUnkOuter, ppv);
543
544     *ppv = NULL;
545
546     if (pUnkOuter)
547         return CLASS_E_NOAGGREGATION;
548
549     This = CoTaskMemAlloc(sizeof(MPEGSplitterImpl));
550     if (!This)
551         return E_OUTOFMEMORY;
552
553     ZeroMemory(This, sizeof(MPEGSplitterImpl));
554     hr = Parser_Create(&(This->Parser), &CLSID_MPEG1Splitter, MPEGSplitter_process_sample, MPEGSplitter_query_accept, MPEGSplitter_pre_connect, MPEGSplitter_cleanup);
555     if (FAILED(hr))
556     {
557         CoTaskMemFree(This);
558         return hr;
559     }
560
561     /* Note: This memory is managed by the parser filter once created */
562     *ppv = (LPVOID)This;
563
564     return hr;
565 }