strmbase: COM cleanup for cleanup SourceSeeking.
[wine] / dlls / quartz / waveparser.c
1 /*
2  * WAVE Parser Filter
3  *
4  * Copyright 2005 Christian Costa
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "quartz_private.h"
22 #include "pin.h"
23
24 #include "uuids.h"
25 #include "aviriff.h"
26 #include "vfwmsgs.h"
27 #include "mmsystem.h"
28
29 #include "wine/unicode.h"
30 #include "wine/debug.h"
31
32 #include <math.h>
33 #include <assert.h>
34
35 #include "parser.h"
36
37 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
38
39 static const WCHAR wcsOutputPinName[] = {'o','u','t','p','u','t',' ','p','i','n',0};
40
41 typedef struct WAVEParserImpl
42 {
43     ParserImpl Parser;
44     LONGLONG StartOfFile; /* in media time */
45     LONGLONG EndOfFile;
46     DWORD dwSampleSize;
47     DWORD nSamplesPerSec;
48     DWORD dwLength;
49 } WAVEParserImpl;
50
51 static inline WAVEParserImpl *impl_from_IMediaSeeking( IMediaSeeking *iface )
52 {
53     return CONTAINING_RECORD(iface, WAVEParserImpl, Parser.sourceSeeking.IMediaSeeking_iface);
54 }
55
56 static LONGLONG bytepos_to_duration(WAVEParserImpl *This, LONGLONG bytepos)
57 {
58     LONGLONG duration = BYTES_FROM_MEDIATIME(bytepos - This->StartOfFile);
59     duration *= 10000000;
60     duration /= (This->dwSampleSize * This->nSamplesPerSec);
61
62     return duration;
63 }
64
65 static LONGLONG duration_to_bytepos(WAVEParserImpl *This, LONGLONG duration)
66 {
67     LONGLONG bytepos;
68
69     bytepos = (This->dwSampleSize * This->nSamplesPerSec);
70     bytepos *= duration;
71     bytepos /= 10000000;
72     bytepos += BYTES_FROM_MEDIATIME(This->StartOfFile);
73     bytepos -= bytepos % This->dwSampleSize;
74
75     return MEDIATIME_FROM_BYTES(bytepos);
76 }
77
78 static HRESULT WAVEParser_Sample(LPVOID iface, IMediaSample * pSample, DWORD_PTR cookie)
79 {
80     WAVEParserImpl *This = iface;
81     LPBYTE pbSrcStream = NULL;
82     ULONG cbSrcStream = 0;
83     REFERENCE_TIME tStart, tStop;
84     HRESULT hr;
85     IMediaSample *newsample = NULL;
86     Parser_OutputPin *pOutputPin;
87     PullPin *pin = This->Parser.pInputPin;
88
89     IMediaSample_GetPointer(pSample, &pbSrcStream);
90     hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
91
92     cbSrcStream = IMediaSample_GetActualDataLength(pSample);
93
94     /* Flush occurring */
95     if (cbSrcStream == 0)
96     {
97         TRACE(".. Why do I need you?\n");
98         return S_OK;
99     }
100
101     pOutputPin = (Parser_OutputPin *)This->Parser.ppPins[1];
102
103     if (SUCCEEDED(hr))
104         hr = IMemAllocator_GetBuffer(pin->pAlloc, &newsample, NULL, NULL, 0);
105
106     if (SUCCEEDED(hr))
107     {
108         LONGLONG rtSampleStart = pin->rtNext;
109         /* Add 4 for the next header, which should hopefully work */
110         LONGLONG rtSampleStop = rtSampleStart + MEDIATIME_FROM_BYTES(IMediaSample_GetSize(newsample));
111
112         if (rtSampleStop > pin->rtStop)
113             rtSampleStop = MEDIATIME_FROM_BYTES(ALIGNUP(BYTES_FROM_MEDIATIME(pin->rtStop), pin->cbAlign));
114
115         hr = IMediaSample_SetTime(newsample, &rtSampleStart, &rtSampleStop);
116
117         pin->rtCurrent = pin->rtNext;
118         pin->rtNext = rtSampleStop;
119
120         IMediaSample_SetPreroll(newsample, 0);
121         IMediaSample_SetDiscontinuity(newsample, 0);
122         IMediaSample_SetSyncPoint(newsample, 1);
123
124         hr = IAsyncReader_Request(pin->pReader, newsample, 0);
125     }
126
127     if (SUCCEEDED(hr))
128     {
129         REFERENCE_TIME tAviStart, tAviStop;
130
131         IMediaSample_SetSyncPoint(pSample, TRUE);
132         pOutputPin->dwSamplesProcessed++;
133
134         tAviStart = bytepos_to_duration(This, tStart);
135         tAviStop = bytepos_to_duration(This, tStart + MEDIATIME_FROM_BYTES(IMediaSample_GetActualDataLength(pSample)));
136
137         IMediaSample_SetTime(pSample, &tAviStart, &tAviStop);
138
139         hr = BaseOutputPinImpl_Deliver(&pOutputPin->pin, pSample);
140         if (hr != S_OK && hr != S_FALSE && hr != VFW_E_WRONG_STATE)
141             ERR("Error sending sample (%x)\n", hr);
142         else if (hr != S_OK)
143             /* Unset progression if denied! */
144             This->Parser.pInputPin->rtCurrent = tStart;
145     }
146
147     if (tStop >= This->EndOfFile || (bytepos_to_duration(This, tStop) >= This->Parser.sourceSeeking.llStop) || hr == VFW_E_NOT_CONNECTED)
148     {
149         unsigned int i;
150
151         TRACE("End of file reached\n");
152
153         for (i = 0; i < This->Parser.cStreams; i++)
154         {
155             IPin* ppin;
156             HRESULT hr;
157
158             TRACE("Send End Of Stream to output pin %u\n", i);
159
160             hr = IPin_ConnectedTo(This->Parser.ppPins[i+1], &ppin);
161             if (SUCCEEDED(hr))
162             {
163                 hr = IPin_EndOfStream(ppin);
164                 IPin_Release(ppin);
165             }
166             if (FAILED(hr))
167             {
168                 ERR("%x\n", hr);
169                 break;
170             }
171         }
172
173         /* Force the pullpin thread to stop */
174         hr = S_FALSE;
175     }
176
177     return hr;
178 }
179
180 static HRESULT WAVEParser_QueryAccept(LPVOID iface, const AM_MEDIA_TYPE * pmt)
181 {
182     if (!IsEqualIID(&pmt->majortype, &MEDIATYPE_Stream))
183         return S_FALSE;
184     if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_WAVE))
185         return S_OK;
186     if (IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_AU) || IsEqualIID(&pmt->subtype, &MEDIASUBTYPE_AIFF))
187         FIXME("AU and AIFF files not supported yet!\n");
188     return S_FALSE;
189 }
190
191 static HRESULT WINAPI WAVEParserImpl_seek(IMediaSeeking *iface)
192 {
193     WAVEParserImpl *This = impl_from_IMediaSeeking(iface);
194     PullPin *pPin = This->Parser.pInputPin;
195     IPin *victim = NULL;
196     LONGLONG newpos, curpos, endpos, bytepos;
197
198     newpos = This->Parser.sourceSeeking.llCurrent;
199     curpos = bytepos_to_duration(This, pPin->rtCurrent);
200     endpos = bytepos_to_duration(This, This->EndOfFile);
201     bytepos = duration_to_bytepos(This, newpos);
202
203     if (newpos > endpos)
204     {
205         WARN("Requesting position %x%08x beyond end of stream %x%08x\n", (DWORD)(newpos>>32), (DWORD)newpos, (DWORD)(endpos>>32), (DWORD)endpos);
206         return E_INVALIDARG;
207     }
208
209     if (curpos/1000000 == newpos/1000000)
210     {
211         TRACE("Requesting position %x%08x same as current position %x%08x\n", (DWORD)(newpos>>32), (DWORD)newpos, (DWORD)(curpos>>32), (DWORD)curpos);
212         return S_OK;
213     }
214
215     TRACE("Moving sound to %08u bytes!\n", (DWORD)BYTES_FROM_MEDIATIME(bytepos));
216
217     EnterCriticalSection(&pPin->thread_lock);
218     IPin_BeginFlush((IPin *)pPin);
219
220     /* Make sure this is done while stopped, BeginFlush takes care of this */
221     EnterCriticalSection(&This->Parser.filter.csFilter);
222     IPin_ConnectedTo(This->Parser.ppPins[1], &victim);
223     if (victim)
224     {
225         IPin_NewSegment(victim, newpos, endpos, pPin->dRate);
226         IPin_Release(victim);
227     }
228
229     pPin->rtStart = pPin->rtCurrent = bytepos;
230     ((Parser_OutputPin *)This->Parser.ppPins[1])->dwSamplesProcessed = 0;
231     LeaveCriticalSection(&This->Parser.filter.csFilter);
232
233     TRACE("Done flushing\n");
234     IPin_EndFlush((IPin *)pPin);
235     LeaveCriticalSection(&pPin->thread_lock);
236
237     return S_OK;
238 }
239
240 static HRESULT WAVEParser_InputPin_PreConnect(IPin * iface, IPin * pConnectPin, ALLOCATOR_PROPERTIES *props)
241 {
242     PullPin *This = (PullPin *)iface;
243     HRESULT hr;
244     RIFFLIST list;
245     RIFFCHUNK chunk;
246     LONGLONG pos = 0; /* in bytes */
247     PIN_INFO piOutput;
248     AM_MEDIA_TYPE amt;
249     WAVEParserImpl * pWAVEParser = (WAVEParserImpl *)This->pin.pinInfo.pFilter;
250     LONGLONG length, avail;
251
252     piOutput.dir = PINDIR_OUTPUT;
253     piOutput.pFilter = (IBaseFilter *)This;
254     lstrcpynW(piOutput.achName, wcsOutputPinName, sizeof(piOutput.achName) / sizeof(piOutput.achName[0]));
255     
256     hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(list), (BYTE *)&list);
257     pos += sizeof(list);
258
259    if (list.fcc != FOURCC_RIFF)
260     {
261         ERR("Input stream not a RIFF file\n");
262         return E_FAIL;
263     }
264     if (list.cb > 1 * 1024 * 1024 * 1024) /* cannot be more than 1Gb in size */
265     {
266         ERR("Input stream violates RIFF spec\n");
267         return E_FAIL;
268     }
269     if (list.fccListType != mmioFOURCC('W','A','V','E'))
270     {
271         ERR("Input stream not an WAVE RIFF file\n");
272         return E_FAIL;
273     }
274
275     hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(chunk), (BYTE *)&chunk);
276     pos += sizeof(chunk);
277     if (chunk.fcc != mmioFOURCC('f','m','t',' '))
278     {
279         ERR("Expected 'fmt ' chunk, but got %.04s\n", (LPSTR)&chunk.fcc);
280         return E_FAIL;
281     }
282
283     amt.majortype = MEDIATYPE_Audio;
284     amt.formattype = FORMAT_WaveFormatEx;
285     amt.cbFormat = chunk.cb;
286     amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
287     amt.pUnk = NULL;
288     hr = IAsyncReader_SyncRead(This->pReader, pos, amt.cbFormat, amt.pbFormat);
289     amt.subtype = MEDIATYPE_Audio;
290     amt.subtype.Data1 = ((WAVEFORMATEX*)amt.pbFormat)->wFormatTag;
291
292     pos += chunk.cb;
293     hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(chunk), (BYTE *)&chunk);
294     if (chunk.fcc == mmioFOURCC('f','a','c','t'))
295     {
296         FIXME("'fact' chunk not supported yet\n");
297         pos += sizeof(chunk) + chunk.cb;
298         hr = IAsyncReader_SyncRead(This->pReader, pos, sizeof(chunk), (BYTE *)&chunk);
299     }
300     if (chunk.fcc != mmioFOURCC('d','a','t','a'))
301     {
302         ERR("Expected 'data' chunk, but got %.04s\n", (LPSTR)&chunk.fcc);
303         return E_FAIL;
304     }
305
306     if (hr == S_OK)
307     {
308         pWAVEParser->StartOfFile = MEDIATIME_FROM_BYTES(pos + sizeof(RIFFCHUNK));
309         pWAVEParser->EndOfFile = MEDIATIME_FROM_BYTES(pos + chunk.cb + sizeof(RIFFCHUNK));
310     }
311
312     if (hr != S_OK)
313         return E_FAIL;
314
315     props->cbAlign = ((WAVEFORMATEX*)amt.pbFormat)->nBlockAlign;
316     props->cbPrefix = 0;
317     props->cbBuffer = 4096;
318     props->cBuffers = 3;
319     pWAVEParser->dwSampleSize = ((WAVEFORMATEX*)amt.pbFormat)->nBlockAlign;
320     IAsyncReader_Length(This->pReader, &length, &avail);
321     pWAVEParser->dwLength = length / (ULONGLONG)pWAVEParser->dwSampleSize;
322     pWAVEParser->nSamplesPerSec = ((WAVEFORMATEX*)amt.pbFormat)->nSamplesPerSec;
323     hr = Parser_AddPin(&(pWAVEParser->Parser), &piOutput, props, &amt);
324     CoTaskMemFree(amt.pbFormat);
325
326     pWAVEParser->Parser.sourceSeeking.llCurrent = 0;
327     pWAVEParser->Parser.sourceSeeking.llStop = pWAVEParser->Parser.sourceSeeking.llDuration = bytepos_to_duration(pWAVEParser, pWAVEParser->EndOfFile);
328     TRACE("Duration: %u seconds\n", (DWORD)(pWAVEParser->Parser.sourceSeeking.llDuration / (LONGLONG)10000000));
329
330     This->rtStop = pWAVEParser->EndOfFile;
331     This->rtStart = pWAVEParser->StartOfFile;
332
333     TRACE("WAVE File ok\n");
334
335     return hr;
336 }
337
338 static HRESULT WAVEParser_Cleanup(LPVOID iface)
339 {
340     WAVEParserImpl *This = iface;
341
342     TRACE("(%p)->()\n", This);
343
344     return S_OK;
345 }
346
347 static HRESULT WAVEParser_first_request(LPVOID iface)
348 {
349     WAVEParserImpl *This = iface;
350     PullPin *pin = This->Parser.pInputPin;
351     HRESULT hr;
352     IMediaSample *sample;
353
354     if (pin->rtCurrent >= pin->rtStop)
355     {
356         /* Last sample has already been queued, request nothing more */
357         TRACE("Done!\n");
358         return S_OK;
359     }
360
361     hr = IMemAllocator_GetBuffer(pin->pAlloc, &sample, NULL, NULL, 0);
362
363     pin->rtNext = pin->rtCurrent;
364     if (SUCCEEDED(hr))
365     {
366         LONGLONG rtSampleStart = pin->rtNext;
367         /* Add 4 for the next header, which should hopefully work */
368         LONGLONG rtSampleStop = rtSampleStart + MEDIATIME_FROM_BYTES(IMediaSample_GetSize(sample));
369         Parser_OutputPin *outpin = (Parser_OutputPin *)This->Parser.ppPins[1];
370
371         if (rtSampleStop > pin->rtStop)
372             rtSampleStop = MEDIATIME_FROM_BYTES(ALIGNUP(BYTES_FROM_MEDIATIME(pin->rtStop), pin->cbAlign));
373
374         hr = IMediaSample_SetTime(sample, &rtSampleStart, &rtSampleStop);
375
376         pin->rtCurrent = pin->rtNext;
377         pin->rtNext = rtSampleStop;
378
379         IMediaSample_SetPreroll(sample, FALSE);
380         if (!outpin->dwSamplesProcessed++)
381             IMediaSample_SetDiscontinuity(sample, TRUE);
382         else
383             IMediaSample_SetDiscontinuity(sample, FALSE);
384
385         hr = IAsyncReader_Request(pin->pReader, sample, 0);
386     }
387     if (FAILED(hr))
388         ERR("Horsemen of the apocalypse came to bring error 0x%08x %p\n", hr, sample);
389
390     return hr;
391 }
392
393 static HRESULT WAVEParser_disconnect(LPVOID iface)
394 {
395     /* TODO: Find and plug memory leaks */
396     return S_OK;
397 }
398
399 static const IBaseFilterVtbl WAVEParser_Vtbl =
400 {
401     Parser_QueryInterface,
402     Parser_AddRef,
403     Parser_Release,
404     Parser_GetClassID,
405     Parser_Stop,
406     Parser_Pause,
407     Parser_Run,
408     Parser_GetState,
409     Parser_SetSyncSource,
410     Parser_GetSyncSource,
411     Parser_EnumPins,
412     Parser_FindPin,
413     Parser_QueryFilterInfo,
414     Parser_JoinFilterGraph,
415     Parser_QueryVendorInfo
416 };
417
418 HRESULT WAVEParser_create(IUnknown * pUnkOuter, LPVOID * ppv)
419 {
420     HRESULT hr;
421     WAVEParserImpl * This;
422
423     TRACE("(%p, %p)\n", pUnkOuter, ppv);
424
425     *ppv = NULL;
426
427     if (pUnkOuter)
428         return CLASS_E_NOAGGREGATION;
429
430     /* Note: This memory is managed by the transform filter once created */
431     This = CoTaskMemAlloc(sizeof(WAVEParserImpl));
432
433     hr = Parser_Create(&(This->Parser), &WAVEParser_Vtbl, &CLSID_WAVEParser, WAVEParser_Sample, WAVEParser_QueryAccept, WAVEParser_InputPin_PreConnect, WAVEParser_Cleanup, WAVEParser_disconnect, WAVEParser_first_request, NULL, NULL, WAVEParserImpl_seek, NULL);
434
435     if (FAILED(hr))
436         return hr;
437
438     *ppv = This;
439
440     return hr;
441 }