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