Fixed clock release in transform template.
[wine] / dlls / quartz / filesource.c
1 /*
2  * File Source Filter
3  *
4  * Copyright 2003 Robert Shearman
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #define NONAMELESSUNION
22 #define NONAMELESSSTRUCT
23
24 #include "quartz_private.h"
25
26 #include "wine/debug.h"
27 #include "wine/unicode.h"
28 #include "pin.h"
29 #include "uuids.h"
30 #include "vfwmsgs.h"
31 #include "winbase.h"
32 #include "winreg.h"
33 #include "ntstatus.h"
34 #include <assert.h>
35
36 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
37
38 static const WCHAR wszOutputPinName[] = { 'O','u','t','p','u','t',0 };
39
40 typedef struct AsyncReader
41 {
42     const struct IBaseFilterVtbl * lpVtbl;
43     const struct IFileSourceFilterVtbl * lpVtblFSF;
44
45     ULONG refCount;
46     FILTER_INFO filterInfo;
47     FILTER_STATE state;
48     CRITICAL_SECTION csFilter;
49
50     IPin * pOutputPin;
51     LPOLESTR pszFileName;
52     AM_MEDIA_TYPE * pmt;
53 } AsyncReader;
54
55 static const struct IBaseFilterVtbl AsyncReader_Vtbl;
56 static const struct IFileSourceFilterVtbl FileSource_Vtbl;
57 static const struct IAsyncReaderVtbl FileAsyncReader_Vtbl;
58
59 static HRESULT FileAsyncReader_Construct(HANDLE hFile, IBaseFilter * pBaseFilter, LPCRITICAL_SECTION pCritSec, IPin ** ppPin);
60
61 #define _IFileSourceFilter_Offset ((int)(&(((AsyncReader*)0)->lpVtblFSF)))
62 #define ICOM_THIS_From_IFileSourceFilter(impl, iface) impl* This = (impl*)(((char*)iface)-_IFileSourceFilter_Offset);
63
64 #define _IAsyncReader_Offset ((int)(&(((FileAsyncReader*)0)->lpVtblAR)))
65 #define ICOM_THIS_From_IAsyncReader(impl, iface) impl* This = (impl*)(((char*)iface)-_IAsyncReader_Offset);
66
67 static HRESULT process_extensions(HKEY hkeyExtensions, LPCOLESTR pszFileName, GUID * majorType, GUID * minorType)
68 {
69     /* FIXME: implement */
70     return E_NOTIMPL;
71 }
72
73 static unsigned char byte_from_hex_char(WCHAR wHex)
74 {
75     switch (tolowerW(wHex))
76     {
77     case '0':
78     case '1':
79     case '2':
80     case '3':
81     case '4':
82     case '5':
83     case '6':
84     case '7':
85     case '8':
86     case '9':
87         return wHex - '0';
88     case 'a':
89     case 'b':
90     case 'c':
91     case 'd':
92     case 'e':
93     case 'f':
94         return wHex - 'a' + 10;
95     default:
96         return 0;
97     }
98 }
99
100 static HRESULT process_pattern_string(LPCWSTR wszPatternString, IAsyncReader * pReader)
101 {
102     ULONG ulOffset;
103     ULONG ulBytes;
104     BYTE * pbMask;
105     BYTE * pbValue;
106     BYTE * pbFile;
107     HRESULT hr = S_OK;
108     ULONG strpos;
109
110     TRACE("\t\tPattern string: %s\n", debugstr_w(wszPatternString));
111     
112     /* format: "offset, bytestocompare, mask, value" */
113
114     ulOffset = strtolW(wszPatternString, NULL, 10);
115
116     if (!(wszPatternString = strchrW(wszPatternString, ',')))
117         return E_INVALIDARG;
118
119     wszPatternString++; /* skip ',' */
120
121     ulBytes = strtolW(wszPatternString, NULL, 10);
122
123     pbMask = HeapAlloc(GetProcessHeap(), 0, ulBytes);
124     pbValue = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulBytes);
125     pbFile = HeapAlloc(GetProcessHeap(), 0, ulBytes);
126
127     /* default mask is match everything */
128     memset(pbMask, 0xFF, ulBytes);
129
130     if (!(wszPatternString = strchrW(wszPatternString, ',')))
131         hr = E_INVALIDARG;
132
133     wszPatternString++; /* skip ',' */
134
135     if (hr == S_OK)
136     {
137         for ( ; !isxdigitW(*wszPatternString) && (*wszPatternString != ','); wszPatternString++)
138             ;
139
140         for (strpos = 0; isxdigitW(*wszPatternString) && (strpos/2 < ulBytes); wszPatternString++, strpos++)
141         {
142             if ((strpos % 2) == 1) /* odd numbered position */
143                 pbMask[strpos / 2] |= byte_from_hex_char(*wszPatternString);
144             else
145                 pbMask[strpos / 2] = byte_from_hex_char(*wszPatternString) << 4;
146         }
147
148         if (!(wszPatternString = strchrW(wszPatternString, ',')))
149             hr = E_INVALIDARG;
150     
151         wszPatternString++; /* skip ',' */
152     }
153
154     if (hr == S_OK)
155     {
156         for ( ; !isxdigitW(*wszPatternString) && (*wszPatternString != ','); wszPatternString++)
157             ;
158
159         for (strpos = 0; isxdigitW(*wszPatternString) && (strpos/2 < ulBytes); wszPatternString++, strpos++)
160         {
161             if ((strpos % 2) == 1) /* odd numbered position */
162                 pbValue[strpos / 2] |= byte_from_hex_char(*wszPatternString);
163             else
164                 pbValue[strpos / 2] = byte_from_hex_char(*wszPatternString) << 4;
165         }
166     }
167
168     if (hr == S_OK)
169         hr = IAsyncReader_SyncRead(pReader, ulOffset, ulBytes, pbFile);
170
171     if (hr == S_OK)
172     {
173         ULONG i;
174         for (i = 0; i < ulBytes; i++)
175             if ((pbFile[i] & pbMask[i]) != pbValue[i])
176             {
177                 hr = S_FALSE;
178                 break;
179             }
180     }
181
182     HeapFree(GetProcessHeap(), 0, pbMask);
183     HeapFree(GetProcessHeap(), 0, pbValue);
184     HeapFree(GetProcessHeap(), 0, pbFile);
185
186     /* if we encountered no errors with this string, and there is a following tuple, then we
187      * have to match that as well to succeed */
188     if ((hr == S_OK) && (wszPatternString = strchrW(wszPatternString, ',')))
189         return process_pattern_string(wszPatternString + 1, pReader);
190     else
191         return hr;
192 }
193
194 static HRESULT GetClassMediaFile(IAsyncReader * pReader, LPCOLESTR pszFileName, GUID * majorType, GUID * minorType)
195 {
196     HKEY hkeyMediaType = NULL;
197     HRESULT hr = S_OK;
198     BOOL bFound = FALSE;
199     static const WCHAR wszMediaType[] = {'M','e','d','i','a',' ','T','y','p','e',0};
200
201     CopyMemory(majorType, &GUID_NULL, sizeof(*majorType));
202     CopyMemory(minorType, &GUID_NULL, sizeof(*minorType));
203
204     hr = HRESULT_FROM_WIN32(RegOpenKeyExW(HKEY_CLASSES_ROOT, wszMediaType, 0, KEY_READ, &hkeyMediaType));
205
206     if (SUCCEEDED(hr))
207     {
208         DWORD indexMajor;
209
210         for (indexMajor = 0; !bFound; indexMajor++)
211         {
212             HKEY hkeyMajor;
213             WCHAR wszMajorKeyName[CHARS_IN_GUID];
214             DWORD dwKeyNameLength = sizeof(wszMajorKeyName) / sizeof(wszMajorKeyName[0]);
215             static const WCHAR wszExtensions[] = {'E','x','t','e','n','s','i','o','n','s',0};
216     
217             if (RegEnumKeyExW(hkeyMediaType, indexMajor, wszMajorKeyName, &dwKeyNameLength, NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
218                 break;
219             if (RegOpenKeyExW(hkeyMediaType, wszMajorKeyName, 0, KEY_READ, &hkeyMajor) != ERROR_SUCCESS)
220                 break;
221             TRACE("%s\n", debugstr_w(wszMajorKeyName));
222             if (!strcmpW(wszExtensions, wszMajorKeyName))
223             {
224                 if (process_extensions(hkeyMajor, pszFileName, majorType, minorType) == S_OK)
225                     bFound = TRUE;
226             }
227             else
228             {
229                 DWORD indexMinor;
230
231                 for (indexMinor = 0; !bFound; indexMinor++)
232                 {
233                     HKEY hkeyMinor;
234                     WCHAR wszMinorKeyName[CHARS_IN_GUID];
235                     DWORD dwMinorKeyNameLen = sizeof(wszMinorKeyName) / sizeof(wszMinorKeyName[0]);
236                     DWORD maxValueLen;
237                     DWORD indexValue;
238
239                     if (RegEnumKeyExW(hkeyMajor, indexMinor, wszMinorKeyName, &dwMinorKeyNameLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
240                         break;
241
242                     if (RegOpenKeyExW(hkeyMajor, wszMinorKeyName, 0, KEY_READ, &hkeyMinor) != ERROR_SUCCESS)
243                         break;
244
245                     TRACE("\t%s\n", debugstr_w(wszMinorKeyName));
246         
247                     if (RegQueryInfoKeyW(hkeyMinor, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &maxValueLen, NULL, NULL) != ERROR_SUCCESS)
248                         break;
249
250                     for (indexValue = 0; !bFound; indexValue++)
251                     {
252                         DWORD dwType;
253                         WCHAR wszValueName[14]; /* longest name we should encounter will be "Source Filter" */
254                         LPWSTR wszPatternString = HeapAlloc(GetProcessHeap(), 0, maxValueLen);
255                         DWORD dwValueNameLen = sizeof(wszValueName) / sizeof(wszValueName[0]); /* remember this is in chars */
256                         DWORD dwDataLen = maxValueLen; /* remember this is in bytes */
257                         static const WCHAR wszSourceFilter[] = {'S','o','u','r','c','e',' ','F','i','l','t','e','r',0};
258                         LONG temp;
259
260                         if ((temp = RegEnumValueW(hkeyMinor, indexValue, wszValueName, &dwValueNameLen, NULL, &dwType, (LPBYTE)wszPatternString, &dwDataLen)) != ERROR_SUCCESS)
261                         {
262                             HeapFree(GetProcessHeap(), 0, wszPatternString);
263                             break;
264                         }
265
266                         /* if it is not the source filter value */
267                         if (strcmpW(wszValueName, wszSourceFilter))
268                         {
269                             if (process_pattern_string(wszPatternString, pReader) == S_OK)
270                             {
271                                 if (SUCCEEDED(CLSIDFromString(wszMajorKeyName, majorType)) &&
272                                     SUCCEEDED(CLSIDFromString(wszMinorKeyName, minorType)))
273                                     bFound = TRUE;
274                             }
275                         }
276                         HeapFree(GetProcessHeap(), 0, wszPatternString);
277                     }
278                     CloseHandle(hkeyMinor);
279                 }
280             }
281             CloseHandle(hkeyMajor);
282         }
283     }
284     CloseHandle(hkeyMediaType);
285
286     if (SUCCEEDED(hr) && !bFound)
287     {
288         ERR("Media class not found\n");
289         hr = E_FAIL;
290     }
291     else if (bFound)
292         TRACE("Found file's class: major = %s, subtype = %s\n", qzdebugstr_guid(majorType), qzdebugstr_guid(minorType));
293
294     return hr;
295 }
296
297 HRESULT AsyncReader_create(IUnknown * pUnkOuter, LPVOID * ppv)
298 {
299     AsyncReader *pAsyncRead;
300     
301     if( pUnkOuter )
302         return CLASS_E_NOAGGREGATION;
303     
304     pAsyncRead = CoTaskMemAlloc(sizeof(AsyncReader));
305
306     if (!pAsyncRead)
307         return E_OUTOFMEMORY;
308
309     pAsyncRead->lpVtbl = &AsyncReader_Vtbl;
310     pAsyncRead->lpVtblFSF = &FileSource_Vtbl;
311     pAsyncRead->refCount = 1;
312     pAsyncRead->filterInfo.achName[0] = '\0';
313     pAsyncRead->filterInfo.pGraph = NULL;
314     pAsyncRead->pOutputPin = NULL;
315
316     InitializeCriticalSection(&pAsyncRead->csFilter);
317
318     pAsyncRead->pszFileName = NULL;
319     pAsyncRead->pmt = NULL;
320
321     *ppv = (LPVOID)pAsyncRead;
322
323     TRACE("-- created at %p\n", pAsyncRead);
324
325     return S_OK;
326 }
327
328 /** IUnkown methods **/
329
330 static HRESULT WINAPI AsyncReader_QueryInterface(IBaseFilter * iface, REFIID riid, LPVOID * ppv)
331 {
332     AsyncReader *This = (AsyncReader *)iface;
333
334     TRACE("(%s, %p)\n", qzdebugstr_guid(riid), ppv);
335
336     *ppv = NULL;
337
338     if (IsEqualIID(riid, &IID_IUnknown))
339         *ppv = (LPVOID)This;
340     else if (IsEqualIID(riid, &IID_IPersist))
341         *ppv = (LPVOID)This;
342     else if (IsEqualIID(riid, &IID_IMediaFilter))
343         *ppv = (LPVOID)This;
344     else if (IsEqualIID(riid, &IID_IBaseFilter))
345         *ppv = (LPVOID)This;
346     else if (IsEqualIID(riid, &IID_IFileSourceFilter))
347         *ppv = (LPVOID)(&This->lpVtblFSF);
348
349     if (*ppv)
350     {
351         IUnknown_AddRef((IUnknown *)(*ppv));
352         return S_OK;
353     }
354
355     FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
356
357     return E_NOINTERFACE;
358 }
359
360 static ULONG WINAPI AsyncReader_AddRef(IBaseFilter * iface)
361 {
362     AsyncReader *This = (AsyncReader *)iface;
363     ULONG refCount = InterlockedIncrement(&This->refCount);
364     
365     TRACE("(%p/%p)->() AddRef from %ld\n", This, iface, refCount - 1);
366     
367     return refCount;
368 }
369
370 static ULONG WINAPI AsyncReader_Release(IBaseFilter * iface)
371 {
372     AsyncReader *This = (AsyncReader *)iface;
373     ULONG refCount = InterlockedDecrement(&This->refCount);
374     
375     TRACE("(%p/%p)->() Release from %ld\n", This, iface, refCount + 1);
376     
377     if (!refCount)
378     {
379         if (This->pOutputPin)
380             IPin_Release(This->pOutputPin);
381         DeleteCriticalSection(&This->csFilter);
382         This->lpVtbl = NULL;
383         CoTaskMemFree(This);
384         return 0;
385     }
386     else
387         return refCount;
388 }
389
390 /** IPersist methods **/
391
392 static HRESULT WINAPI AsyncReader_GetClassID(IBaseFilter * iface, CLSID * pClsid)
393 {
394     TRACE("(%p)\n", pClsid);
395
396     *pClsid = CLSID_AsyncReader;
397
398     return S_OK;
399 }
400
401 /** IMediaFilter methods **/
402
403 static HRESULT WINAPI AsyncReader_Stop(IBaseFilter * iface)
404 {
405     AsyncReader *This = (AsyncReader *)iface;
406
407     TRACE("()\n");
408
409     This->state = State_Stopped;
410     
411     return S_OK;
412 }
413
414 static HRESULT WINAPI AsyncReader_Pause(IBaseFilter * iface)
415 {
416     AsyncReader *This = (AsyncReader *)iface;
417
418     TRACE("()\n");
419
420     This->state = State_Paused;
421
422     return S_OK;
423 }
424
425 static HRESULT WINAPI AsyncReader_Run(IBaseFilter * iface, REFERENCE_TIME tStart)
426 {
427     AsyncReader *This = (AsyncReader *)iface;
428
429     TRACE("(%lx%08lx)\n", (ULONG)(tStart >> 32), (ULONG)tStart);
430
431     This->state = State_Running;
432
433     return S_OK;
434 }
435
436 static HRESULT WINAPI AsyncReader_GetState(IBaseFilter * iface, DWORD dwMilliSecsTimeout, FILTER_STATE *pState)
437 {
438     AsyncReader *This = (AsyncReader *)iface;
439
440     TRACE("(%lu, %p)\n", dwMilliSecsTimeout, pState);
441
442     *pState = This->state;
443     
444     return S_OK;
445 }
446
447 static HRESULT WINAPI AsyncReader_SetSyncSource(IBaseFilter * iface, IReferenceClock *pClock)
448 {
449 /*    AsyncReader *This = (AsyncReader *)iface;*/
450
451     TRACE("(%p)\n", pClock);
452
453     return S_OK;
454 }
455
456 static HRESULT WINAPI AsyncReader_GetSyncSource(IBaseFilter * iface, IReferenceClock **ppClock)
457 {
458 /*    AsyncReader *This = (AsyncReader *)iface;*/
459
460     TRACE("(%p)\n", ppClock);
461
462     return S_OK;
463 }
464
465 /** IBaseFilter methods **/
466
467 static HRESULT WINAPI AsyncReader_EnumPins(IBaseFilter * iface, IEnumPins **ppEnum)
468 {
469     ENUMPINDETAILS epd;
470     AsyncReader *This = (AsyncReader *)iface;
471
472     TRACE("(%p)\n", ppEnum);
473
474     epd.cPins = This->pOutputPin ? 1 : 0;
475     epd.ppPins = &This->pOutputPin;
476     return IEnumPinsImpl_Construct(&epd, ppEnum);
477 }
478
479 static HRESULT WINAPI AsyncReader_FindPin(IBaseFilter * iface, LPCWSTR Id, IPin **ppPin)
480 {
481     FIXME("(%s, %p)\n", debugstr_w(Id), ppPin);
482
483     return E_NOTIMPL;
484 }
485
486 static HRESULT WINAPI AsyncReader_QueryFilterInfo(IBaseFilter * iface, FILTER_INFO *pInfo)
487 {
488     AsyncReader *This = (AsyncReader *)iface;
489
490     TRACE("(%p)\n", pInfo);
491
492     strcpyW(pInfo->achName, This->filterInfo.achName);
493     pInfo->pGraph = This->filterInfo.pGraph;
494
495     if (pInfo->pGraph)
496         IFilterGraph_AddRef(pInfo->pGraph);
497     
498     return S_OK;
499 }
500
501 static HRESULT WINAPI AsyncReader_JoinFilterGraph(IBaseFilter * iface, IFilterGraph *pGraph, LPCWSTR pName)
502 {
503     AsyncReader *This = (AsyncReader *)iface;
504
505     TRACE("(%p, %s)\n", pGraph, debugstr_w(pName));
506
507     if (pName)
508         strcpyW(This->filterInfo.achName, pName);
509     else
510         *This->filterInfo.achName = 0;
511     This->filterInfo.pGraph = pGraph; /* NOTE: do NOT increase ref. count */
512
513     return S_OK;
514 }
515
516 static HRESULT WINAPI AsyncReader_QueryVendorInfo(IBaseFilter * iface, LPWSTR *pVendorInfo)
517 {
518     FIXME("(%p)\n", pVendorInfo);
519
520     return E_NOTIMPL;
521 }
522
523 static const IBaseFilterVtbl AsyncReader_Vtbl =
524 {
525     AsyncReader_QueryInterface,
526     AsyncReader_AddRef,
527     AsyncReader_Release,
528     AsyncReader_GetClassID,
529     AsyncReader_Stop,
530     AsyncReader_Pause,
531     AsyncReader_Run,
532     AsyncReader_GetState,
533     AsyncReader_SetSyncSource,
534     AsyncReader_GetSyncSource,
535     AsyncReader_EnumPins,
536     AsyncReader_FindPin,
537     AsyncReader_QueryFilterInfo,
538     AsyncReader_JoinFilterGraph,
539     AsyncReader_QueryVendorInfo
540 };
541
542 static HRESULT WINAPI FileSource_QueryInterface(IFileSourceFilter * iface, REFIID riid, LPVOID * ppv)
543 {
544     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
545
546     return IBaseFilter_QueryInterface((IFileSourceFilter*)&This->lpVtbl, riid, ppv);
547 }
548
549 static ULONG WINAPI FileSource_AddRef(IFileSourceFilter * iface)
550 {
551     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
552
553     return IBaseFilter_AddRef((IFileSourceFilter*)&This->lpVtbl);
554 }
555
556 static ULONG WINAPI FileSource_Release(IFileSourceFilter * iface)
557 {
558     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
559
560     return IBaseFilter_Release((IFileSourceFilter*)&This->lpVtbl);
561 }
562
563 static HRESULT WINAPI FileSource_Load(IFileSourceFilter * iface, LPCOLESTR pszFileName, const AM_MEDIA_TYPE * pmt)
564 {
565     HRESULT hr;
566     HANDLE hFile;
567     IAsyncReader * pReader = NULL;
568     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
569
570     TRACE("(%s, %p)\n", debugstr_w(pszFileName), pmt);
571
572     /* open file */
573     /* FIXME: check the sharing values that native uses */
574     hFile = CreateFileW(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
575
576     if (hFile == INVALID_HANDLE_VALUE)
577     {
578         return HRESULT_FROM_WIN32(GetLastError());
579     }
580
581     /* create pin */
582     hr = FileAsyncReader_Construct(hFile, (IBaseFilter *)&This->lpVtbl, &This->csFilter, &This->pOutputPin);
583
584     if (SUCCEEDED(hr))
585         hr = IPin_QueryInterface(This->pOutputPin, &IID_IAsyncReader, (LPVOID *)&pReader);
586
587     /* store file name & media type */
588     if (SUCCEEDED(hr))
589     {
590         This->pszFileName = CoTaskMemAlloc((strlenW(pszFileName) + 1) * sizeof(WCHAR));
591         strcpyW(This->pszFileName, pszFileName);
592         This->pmt = CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
593         if (!pmt)
594         {
595             This->pmt->bFixedSizeSamples = TRUE;
596             This->pmt->bTemporalCompression = FALSE;
597             This->pmt->cbFormat = 0;
598             This->pmt->pbFormat = NULL;
599             This->pmt->pUnk = NULL;
600             This->pmt->lSampleSize = 0;
601             memcpy(&This->pmt->formattype, &FORMAT_None, sizeof(FORMAT_None));
602             hr = GetClassMediaFile(pReader, pszFileName, &This->pmt->majortype, &This->pmt->subtype);
603             if (FAILED(hr))
604             {
605                 CoTaskMemFree(This->pmt);
606                 This->pmt = NULL;
607             }
608         }
609         else
610             CopyMediaType(This->pmt, pmt);
611     }
612
613     if (pReader)
614         IAsyncReader_Release(pReader);
615
616     if (FAILED(hr))
617     {
618         if (This->pOutputPin)
619         {
620             IPin_Release(This->pOutputPin);
621             This->pOutputPin = NULL;
622         }
623         if (This->pszFileName)
624         {
625             CoTaskMemFree(This->pszFileName);
626             This->pszFileName = NULL;
627         }
628         CloseHandle(hFile);
629     }
630
631     /* FIXME: check return codes */
632     return hr;
633 }
634
635 static HRESULT WINAPI FileSource_GetCurFile(IFileSourceFilter * iface, LPOLESTR * ppszFileName, AM_MEDIA_TYPE * pmt)
636 {
637     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
638     
639     TRACE("(%p, %p)\n", ppszFileName, pmt);
640
641     /* copy file name & media type if available, otherwise clear the outputs */
642     if (This->pszFileName)
643     {
644         *ppszFileName = CoTaskMemAlloc((strlenW(This->pszFileName) + 1) * sizeof(WCHAR));
645         strcpyW(*ppszFileName, This->pszFileName);
646     }
647     else
648         *ppszFileName = NULL;
649
650     if (This->pmt)
651     {
652         CopyMediaType(pmt, This->pmt);
653     }
654     else
655         ZeroMemory(pmt, sizeof(*pmt));
656
657     return S_OK;
658 }
659
660 static const IFileSourceFilterVtbl FileSource_Vtbl = 
661 {
662     FileSource_QueryInterface,
663     FileSource_AddRef,
664     FileSource_Release,
665     FileSource_Load,
666     FileSource_GetCurFile
667 };
668
669
670 /* the dwUserData passed back to user */
671 typedef struct DATAREQUEST
672 {
673     IMediaSample * pSample; /* sample passed to us by user */
674     DWORD_PTR dwUserData; /* user data passed to us */
675     OVERLAPPED ovl; /* our overlapped structure */
676
677     struct DATAREQUEST * pNext; /* next data request in list */
678 } DATAREQUEST;
679
680 void queue(DATAREQUEST * pHead, DATAREQUEST * pItem)
681 {
682     DATAREQUEST * pCurrent;
683     for (pCurrent = pHead; pCurrent->pNext; pCurrent = pCurrent->pNext)
684         ;
685     pCurrent->pNext = pItem;
686 }
687
688 typedef struct FileAsyncReader
689 {
690     OutputPin pin;
691     const struct IAsyncReaderVtbl * lpVtblAR;
692
693     HANDLE hFile;
694     HANDLE hEvent;
695     BOOL bFlushing;
696     DATAREQUEST * pHead; /* head of data request list */
697     CRITICAL_SECTION csList; /* critical section to protect operations on list */
698 } FileAsyncReader;
699
700 static HRESULT AcceptProcAFR(LPVOID iface, const AM_MEDIA_TYPE *pmt)
701 {
702     AsyncReader *This = (AsyncReader *)iface;
703     
704     FIXME("(%p, %p)\n", iface, pmt);
705
706     if (IsEqualGUID(&pmt->majortype, &This->pmt->majortype) &&
707         IsEqualGUID(&pmt->subtype, &This->pmt->subtype) &&
708         IsEqualGUID(&pmt->formattype, &FORMAT_None))
709         return S_OK;
710     
711     return S_FALSE;
712 }
713
714 /* overriden pin functions */
715
716 static HRESULT WINAPI FileAsyncReaderPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
717 {
718     FileAsyncReader *This = (FileAsyncReader *)iface;
719     TRACE("(%s, %p)\n", qzdebugstr_guid(riid), ppv);
720
721     *ppv = NULL;
722
723     if (IsEqualIID(riid, &IID_IUnknown))
724         *ppv = (LPVOID)This;
725     else if (IsEqualIID(riid, &IID_IPin))
726         *ppv = (LPVOID)This;
727     else if (IsEqualIID(riid, &IID_IAsyncReader))
728         *ppv = (LPVOID)&This->lpVtblAR;
729
730     if (*ppv)
731     {
732         IUnknown_AddRef((IUnknown *)(*ppv));
733         return S_OK;
734     }
735
736     FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
737
738     return E_NOINTERFACE;
739 }
740
741 static ULONG WINAPI FileAsyncReaderPin_Release(IPin * iface)
742 {
743     FileAsyncReader *This = (FileAsyncReader *)iface;
744     ULONG refCount = InterlockedDecrement(&This->pin.pin.refCount);
745     
746     TRACE("()\n");
747     
748     if (!refCount)
749     {
750         DATAREQUEST * pCurrent;
751         DATAREQUEST * pNext;
752         for (pCurrent = This->pHead; pCurrent; pCurrent = pNext)
753         {
754             pNext = pCurrent->pNext;
755             CoTaskMemFree(pCurrent);
756         }
757         CloseHandle(This->hFile);
758         CloseHandle(This->hEvent);
759         CoTaskMemFree(This);
760         return 0;
761     }
762     return refCount;
763 }
764
765 static HRESULT WINAPI FileAsyncReaderPin_EnumMediaTypes(IPin * iface, IEnumMediaTypes ** ppEnum)
766 {
767     ENUMMEDIADETAILS emd;
768     FileAsyncReader *This = (FileAsyncReader *)iface;
769
770     TRACE("(%p)\n", ppEnum);
771
772     emd.cMediaTypes = 1;
773     emd.pMediaTypes = ((AsyncReader *)This->pin.pin.pinInfo.pFilter)->pmt;
774
775     return IEnumMediaTypesImpl_Construct(&emd, ppEnum);
776 }
777
778 static const IPinVtbl FileAsyncReaderPin_Vtbl = 
779 {
780     FileAsyncReaderPin_QueryInterface,
781     IPinImpl_AddRef,
782     FileAsyncReaderPin_Release,
783     OutputPin_Connect,
784     OutputPin_ReceiveConnection,
785     IPinImpl_Disconnect,
786     IPinImpl_ConnectedTo,
787     IPinImpl_ConnectionMediaType,
788     IPinImpl_QueryPinInfo,
789     IPinImpl_QueryDirection,
790     IPinImpl_QueryId,
791     IPinImpl_QueryAccept,
792     FileAsyncReaderPin_EnumMediaTypes,
793     IPinImpl_QueryInternalConnections,
794     OutputPin_EndOfStream,
795     OutputPin_BeginFlush,
796     OutputPin_EndFlush,
797     OutputPin_NewSegment
798 };
799
800 /* Function called as a helper to IPin_Connect */
801 /* specific AM_MEDIA_TYPE - it cannot be NULL */
802 /* this differs from standard OutputPin_ConnectSpecific only in that it
803  * doesn't need the IMemInputPin interface on the receiving pin */
804 static HRESULT FileAsyncReaderPin_ConnectSpecific(IPin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
805 {
806     OutputPin *This = (OutputPin *)iface;
807     HRESULT hr;
808
809     TRACE("(%p, %p)\n", pReceivePin, pmt);
810     dump_AM_MEDIA_TYPE(pmt);
811
812     /* FIXME: call queryacceptproc */
813
814     This->pin.pConnectedTo = pReceivePin;
815     IPin_AddRef(pReceivePin);
816     CopyMediaType(&This->pin.mtCurrent, pmt);
817
818     hr = IPin_ReceiveConnection(pReceivePin, iface, pmt);
819
820     if (FAILED(hr))
821     {
822         IPin_Release(This->pin.pConnectedTo);
823         This->pin.pConnectedTo = NULL;
824         FreeMediaType(&This->pin.mtCurrent);
825     }
826
827     TRACE(" -- %lx\n", hr);
828     return hr;
829 }
830
831 static HRESULT FileAsyncReader_Construct(HANDLE hFile, IBaseFilter * pBaseFilter, LPCRITICAL_SECTION pCritSec, IPin ** ppPin)
832 {
833     FileAsyncReader * pPinImpl;
834     PIN_INFO piOutput;
835
836     *ppPin = NULL;
837
838     pPinImpl = CoTaskMemAlloc(sizeof(*pPinImpl));
839
840     if (!pPinImpl)
841         return E_OUTOFMEMORY;
842
843     piOutput.dir = PINDIR_OUTPUT;
844     piOutput.pFilter = pBaseFilter;
845     strcpyW(piOutput.achName, wszOutputPinName);
846
847     if (SUCCEEDED(OutputPin_Init(&piOutput, NULL, pBaseFilter, AcceptProcAFR, pCritSec, &pPinImpl->pin)))
848     {
849         pPinImpl->pin.pin.lpVtbl = &FileAsyncReaderPin_Vtbl;
850         pPinImpl->lpVtblAR = &FileAsyncReader_Vtbl;
851         pPinImpl->hFile = hFile;
852         pPinImpl->hEvent = CreateEventW(NULL, 0, 0, NULL);
853         pPinImpl->bFlushing = FALSE;
854         pPinImpl->pHead = NULL;
855         pPinImpl->pin.pConnectSpecific = FileAsyncReaderPin_ConnectSpecific;
856         InitializeCriticalSection(&pPinImpl->csList);
857
858         *ppPin = (IPin *)(&pPinImpl->pin.pin.lpVtbl);
859         return S_OK;
860     }
861     return E_FAIL;
862 }
863
864 /* IAsyncReader */
865
866 static HRESULT WINAPI FileAsyncReader_QueryInterface(IAsyncReader * iface, REFIID riid, LPVOID * ppv)
867 {
868     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
869
870     return IPin_QueryInterface((IPin *)This, riid, ppv);
871 }
872
873 static ULONG WINAPI FileAsyncReader_AddRef(IAsyncReader * iface)
874 {
875     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
876
877     return IPin_AddRef((IPin *)This);
878 }
879
880 static ULONG WINAPI FileAsyncReader_Release(IAsyncReader * iface)
881 {
882     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
883
884     return IPin_Release((IPin *)This);
885 }
886
887 #define DEF_ALIGNMENT 1
888
889 static HRESULT WINAPI FileAsyncReader_RequestAllocator(IAsyncReader * iface, IMemAllocator * pPreferred, ALLOCATOR_PROPERTIES * pProps, IMemAllocator ** ppActual)
890 {
891     HRESULT hr = S_OK;
892
893     TRACE("(%p, %p, %p)\n", pPreferred, pProps, ppActual);
894
895     if (!pProps->cbAlign || (pProps->cbAlign % DEF_ALIGNMENT) != 0)
896         pProps->cbAlign = DEF_ALIGNMENT;
897
898     if (pPreferred)
899     {
900         ALLOCATOR_PROPERTIES PropsActual;
901         hr = IMemAllocator_SetProperties(pPreferred, pProps, &PropsActual);
902         /* FIXME: check we are still aligned */
903         if (SUCCEEDED(hr))
904         {
905             IMemAllocator_AddRef(pPreferred);
906             *ppActual = pPreferred;
907             TRACE("FileAsyncReader_RequestAllocator -- %lx\n", hr);
908             return S_OK;
909         }
910     }
911
912     pPreferred = NULL;
913
914     hr = CoCreateInstance(&CLSID_MemoryAllocator, NULL, CLSCTX_INPROC, &IID_IMemAllocator, (LPVOID *)&pPreferred);
915
916     if (SUCCEEDED(hr))
917     {
918         ALLOCATOR_PROPERTIES PropsActual;
919         hr = IMemAllocator_SetProperties(pPreferred, pProps, &PropsActual);
920         /* FIXME: check we are still aligned */
921         if (SUCCEEDED(hr))
922         {
923             IMemAllocator_AddRef(pPreferred);
924             *ppActual = pPreferred;
925             TRACE("FileAsyncReader_RequestAllocator -- %lx\n", hr);
926             return S_OK;
927         }
928     }
929
930     if (FAILED(hr))
931     {
932         *ppActual = NULL;
933         if (pPreferred)
934             IMemAllocator_Release(pPreferred);
935     }
936
937     TRACE("-- %lx\n", hr);
938     return hr;
939 }
940
941 /* we could improve the Request/WaitForNext mechanism by allowing out of order samples.
942  * however, this would be quite complicated to do and may be a bit error prone */
943 static HRESULT WINAPI FileAsyncReader_Request(IAsyncReader * iface, IMediaSample * pSample, DWORD_PTR dwUser)
944 {
945     REFERENCE_TIME Start;
946     REFERENCE_TIME Stop;
947     DATAREQUEST * pDataRq;
948     BYTE * pBuffer;
949     HRESULT hr = S_OK;
950     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
951
952     TRACE("(%p, %lx)\n", pSample, dwUser);
953
954     /* check flushing state */
955     if (This->bFlushing)
956         return VFW_E_WRONG_STATE;
957
958     if (!(pDataRq = CoTaskMemAlloc(sizeof(*pDataRq))))
959         hr = E_OUTOFMEMORY;
960
961     /* get start and stop positions in bytes */
962     if (SUCCEEDED(hr))
963         hr = IMediaSample_GetTime(pSample, &Start, &Stop);
964
965     if (SUCCEEDED(hr))
966         hr = IMediaSample_GetPointer(pSample, &pBuffer);
967
968     if (SUCCEEDED(hr))
969     {
970         DWORD dwLength = (DWORD) BYTES_FROM_MEDIATIME(Stop - Start);
971
972         pDataRq->ovl.u.s.Offset = (DWORD) BYTES_FROM_MEDIATIME(Start);
973         pDataRq->ovl.u.s.OffsetHigh = (DWORD)(BYTES_FROM_MEDIATIME(Start) >> (sizeof(DWORD) * 8));
974         pDataRq->ovl.hEvent = This->hEvent;
975         pDataRq->dwUserData = dwUser;
976         pDataRq->pNext = NULL;
977         /* we violate traditional COM rules here by maintaining
978          * a reference to the sample, but not calling AddRef, but
979          * that's what MSDN says to do */
980         pDataRq->pSample = pSample;
981
982         EnterCriticalSection(&This->csList);
983         {
984             if (This->pHead)
985                 /* adds data request to end of list */
986                 queue(This->pHead, pDataRq);
987             else
988                 This->pHead = pDataRq;
989         }
990         LeaveCriticalSection(&This->csList);
991
992         /* this is definitely not how it is implemented on Win9x
993          * as they do not support async reads on files, but it is
994          * sooo much easier to use this than messing around with threads!
995          */
996         if (!ReadFile(This->hFile, pBuffer, dwLength, NULL, &pDataRq->ovl))
997             hr = HRESULT_FROM_WIN32(GetLastError());
998
999         /* ERROR_IO_PENDING is not actually an error since this is what we want! */
1000         if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING))
1001             hr = S_OK;
1002     }
1003
1004     if (FAILED(hr) && pDataRq)
1005     {
1006         EnterCriticalSection(&This->csList);
1007         {
1008             DATAREQUEST * pCurrent;
1009             for (pCurrent = This->pHead; pCurrent && pCurrent->pNext; pCurrent = pCurrent->pNext)
1010                 if (pCurrent->pNext == pDataRq)
1011                 {
1012                     pCurrent->pNext = pDataRq->pNext;
1013                     break;
1014                 }
1015         }
1016         LeaveCriticalSection(&This->csList);
1017         CoTaskMemFree(pDataRq);
1018     }
1019
1020     TRACE("-- %lx\n", hr);
1021     return hr;
1022 }
1023
1024 static HRESULT WINAPI FileAsyncReader_WaitForNext(IAsyncReader * iface, DWORD dwTimeout, IMediaSample ** ppSample, DWORD_PTR * pdwUser)
1025 {
1026     HRESULT hr = S_OK;
1027     DATAREQUEST * pDataRq = NULL;
1028     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1029
1030     TRACE("(%lu, %p, %p)\n", dwTimeout, ppSample, pdwUser);
1031
1032     /* FIXME: we could do with improving this by waiting for an array of event handles
1033      * and then determining which one finished and removing that from the list, otherwise
1034      * we will end up waiting for longer than we should do, if a later request finishes
1035      * before an earlier one */
1036
1037     *ppSample = NULL;
1038     *pdwUser = 0;
1039
1040     /* we return immediately if flushing */
1041     if (This->bFlushing)
1042         hr = VFW_E_WRONG_STATE;
1043
1044     if (SUCCEEDED(hr))
1045     {
1046         /* wait for the read to finish or timeout */
1047         if (WaitForSingleObject(This->hEvent, dwTimeout) == WAIT_TIMEOUT)
1048             hr = VFW_E_TIMEOUT;
1049     }
1050     if (SUCCEEDED(hr))
1051     {
1052         EnterCriticalSection(&This->csList);
1053         {
1054             pDataRq = This->pHead;
1055             if (pDataRq == NULL)
1056                 hr = E_FAIL;
1057             else
1058                 This->pHead = pDataRq->pNext;
1059         }
1060         LeaveCriticalSection(&This->csList);
1061     }
1062
1063     if (SUCCEEDED(hr))
1064     {
1065         DWORD dwBytes;
1066         /* get any errors */
1067         if (!GetOverlappedResult(This->hFile, &pDataRq->ovl, &dwBytes, FALSE))
1068             hr = HRESULT_FROM_WIN32(GetLastError());
1069     }
1070
1071     if (SUCCEEDED(hr))
1072     {
1073         *ppSample = pDataRq->pSample;
1074         *pdwUser = pDataRq->dwUserData;
1075     }
1076
1077     /* clean up */
1078     if (pDataRq)
1079     {
1080         /* no need to close event handle since we will close it when the pin is destroyed */
1081         CoTaskMemFree(pDataRq);
1082     }
1083     
1084     TRACE("-- %lx\n", hr);
1085     return hr;
1086 }
1087
1088 static HRESULT WINAPI FileAsyncReader_SyncRead(IAsyncReader * iface, LONGLONG llPosition, LONG lLength, BYTE * pBuffer);
1089
1090 static HRESULT WINAPI FileAsyncReader_SyncReadAligned(IAsyncReader * iface, IMediaSample * pSample)
1091 {
1092     BYTE * pBuffer;
1093     REFERENCE_TIME tStart;
1094     REFERENCE_TIME tStop;
1095     HRESULT hr;
1096
1097     TRACE("(%p)\n", pSample);
1098
1099     hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
1100
1101     if (SUCCEEDED(hr))
1102         hr = IMediaSample_GetPointer(pSample, &pBuffer);
1103
1104     if (SUCCEEDED(hr))
1105         hr = FileAsyncReader_SyncRead(iface, 
1106             BYTES_FROM_MEDIATIME(tStart),
1107             (LONG) BYTES_FROM_MEDIATIME(tStop - tStart),
1108             pBuffer);
1109
1110     TRACE("-- %lx\n", hr);
1111     return hr;
1112 }
1113
1114 static HRESULT WINAPI FileAsyncReader_SyncRead(IAsyncReader * iface, LONGLONG llPosition, LONG lLength, BYTE * pBuffer)
1115 {
1116     OVERLAPPED ovl;
1117     HRESULT hr = S_OK;
1118     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1119
1120     TRACE("(%lx%08lx, %ld, %p)\n", (ULONG)(llPosition >> 32), (ULONG)llPosition, lLength, pBuffer);
1121
1122     ZeroMemory(&ovl, sizeof(ovl));
1123
1124     ovl.hEvent = CreateEventW(NULL, 0, 0, NULL);
1125     /* NOTE: llPosition is the actual byte position to start reading from */
1126     ovl.u.s.Offset = (DWORD) llPosition;
1127     ovl.u.s.OffsetHigh = (DWORD) (llPosition >> (sizeof(DWORD) * 8));
1128
1129     if (!ReadFile(This->hFile, pBuffer, lLength, NULL, &ovl))
1130         hr = HRESULT_FROM_WIN32(GetLastError());
1131
1132     if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING))
1133         hr = S_OK;
1134
1135     if (SUCCEEDED(hr))
1136     {
1137         DWORD dwBytesRead;
1138
1139         if (!GetOverlappedResult(This->hFile, &ovl, &dwBytesRead, TRUE))
1140             hr = HRESULT_FROM_WIN32(GetLastError());
1141     }
1142
1143     CloseHandle(ovl.hEvent);
1144
1145     TRACE("-- %lx\n", hr);
1146     return hr;
1147 }
1148
1149 static HRESULT WINAPI FileAsyncReader_Length(IAsyncReader * iface, LONGLONG * pTotal, LONGLONG * pAvailable)
1150 {
1151     DWORD dwSizeLow;
1152     DWORD dwSizeHigh;
1153     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1154
1155     TRACE("(%p, %p)\n", pTotal, pAvailable);
1156
1157     if (((dwSizeLow = GetFileSize(This->hFile, &dwSizeHigh)) == -1) &&
1158         (GetLastError() != NO_ERROR))
1159         return HRESULT_FROM_WIN32(GetLastError());
1160
1161     *pTotal = (LONGLONG)dwSizeLow | (LONGLONG)dwSizeHigh << (sizeof(DWORD) * 8);
1162
1163     *pAvailable = *pTotal;
1164
1165     return S_OK;
1166 }
1167
1168 static HRESULT WINAPI FileAsyncReader_BeginFlush(IAsyncReader * iface)
1169 {
1170     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1171
1172     TRACE("()\n");
1173
1174     This->bFlushing = TRUE;
1175     CancelIo(This->hFile);
1176     SetEvent(This->hEvent);
1177     
1178     /* FIXME: free list */
1179
1180     return S_OK;
1181 }
1182
1183 static HRESULT WINAPI FileAsyncReader_EndFlush(IAsyncReader * iface)
1184 {
1185     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1186
1187     TRACE("()\n");
1188
1189     This->bFlushing = FALSE;
1190
1191     return S_OK;
1192 }
1193
1194 static const IAsyncReaderVtbl FileAsyncReader_Vtbl = 
1195 {
1196     FileAsyncReader_QueryInterface,
1197     FileAsyncReader_AddRef,
1198     FileAsyncReader_Release,
1199     FileAsyncReader_RequestAllocator,
1200     FileAsyncReader_Request,
1201     FileAsyncReader_WaitForNext,
1202     FileAsyncReader_SyncReadAligned,
1203     FileAsyncReader_SyncRead,
1204     FileAsyncReader_Length,
1205     FileAsyncReader_BeginFlush,
1206     FileAsyncReader_EndFlush,
1207 };