Removed W->A from DEFWND_ImmIsUIMessageW.
[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;
297     
298     if( pUnkOuter )
299         return CLASS_E_NOAGGREGATION;
300     
301     pAsyncRead = CoTaskMemAlloc(sizeof(AsyncReader));
302
303     if (!pAsyncRead)
304         return E_OUTOFMEMORY;
305
306     pAsyncRead->lpVtbl = &AsyncReader_Vtbl;
307     pAsyncRead->lpVtblFSF = &FileSource_Vtbl;
308     pAsyncRead->refCount = 1;
309     pAsyncRead->filterInfo.achName[0] = '\0';
310     pAsyncRead->filterInfo.pGraph = NULL;
311     pAsyncRead->pOutputPin = NULL;
312
313     InitializeCriticalSection(&pAsyncRead->csFilter);
314
315     pAsyncRead->pszFileName = NULL;
316     pAsyncRead->pmt = NULL;
317
318     *ppv = (LPVOID)pAsyncRead;
319
320     TRACE("-- created at %p\n", pAsyncRead);
321
322     return S_OK;
323 }
324
325 /** IUnkown methods **/
326
327 static HRESULT WINAPI AsyncReader_QueryInterface(IBaseFilter * iface, REFIID riid, LPVOID * ppv)
328 {
329     AsyncReader *This = (AsyncReader *)iface;
330
331     TRACE("(%s, %p)\n", qzdebugstr_guid(riid), ppv);
332
333     *ppv = NULL;
334
335     if (IsEqualIID(riid, &IID_IUnknown))
336         *ppv = (LPVOID)This;
337     else if (IsEqualIID(riid, &IID_IPersist))
338         *ppv = (LPVOID)This;
339     else if (IsEqualIID(riid, &IID_IMediaFilter))
340         *ppv = (LPVOID)This;
341     else if (IsEqualIID(riid, &IID_IBaseFilter))
342         *ppv = (LPVOID)This;
343     else if (IsEqualIID(riid, &IID_IFileSourceFilter))
344         *ppv = (LPVOID)(&This->lpVtblFSF);
345
346     if (*ppv)
347     {
348         IUnknown_AddRef((IUnknown *)(*ppv));
349         return S_OK;
350     }
351
352     FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
353
354     return E_NOINTERFACE;
355 }
356
357 static ULONG WINAPI AsyncReader_AddRef(IBaseFilter * iface)
358 {
359     AsyncReader *This = (AsyncReader *)iface;
360     
361     TRACE("()\n");
362     
363     return InterlockedIncrement(&This->refCount);
364 }
365
366 static ULONG WINAPI AsyncReader_Release(IBaseFilter * iface)
367 {
368     AsyncReader *This = (AsyncReader *)iface;
369     
370     TRACE("()\n");
371     
372     if (!InterlockedDecrement(&This->refCount))
373     {
374         if (This->pOutputPin)
375             IPin_Release(This->pOutputPin);
376         DeleteCriticalSection(&This->csFilter);
377         This->lpVtbl = NULL;
378         CoTaskMemFree(This);
379         return 0;
380     }
381     else
382         return This->refCount;
383 }
384
385 /** IPersist methods **/
386
387 static HRESULT WINAPI AsyncReader_GetClassID(IBaseFilter * iface, CLSID * pClsid)
388 {
389     TRACE("(%p)\n", pClsid);
390
391     *pClsid = CLSID_AsyncReader;
392
393     return S_OK;
394 }
395
396 /** IMediaFilter methods **/
397
398 static HRESULT WINAPI AsyncReader_Stop(IBaseFilter * iface)
399 {
400     AsyncReader *This = (AsyncReader *)iface;
401
402     TRACE("()\n");
403
404     This->state = State_Stopped;
405     
406     return S_OK;
407 }
408
409 static HRESULT WINAPI AsyncReader_Pause(IBaseFilter * iface)
410 {
411     AsyncReader *This = (AsyncReader *)iface;
412
413     TRACE("()\n");
414
415     This->state = State_Paused;
416
417     return S_OK;
418 }
419
420 static HRESULT WINAPI AsyncReader_Run(IBaseFilter * iface, REFERENCE_TIME tStart)
421 {
422     AsyncReader *This = (AsyncReader *)iface;
423
424     TRACE("(%lx%08lx)\n", (ULONG)(tStart >> 32), (ULONG)tStart);
425
426     This->state = State_Running;
427
428     return S_OK;
429 }
430
431 static HRESULT WINAPI AsyncReader_GetState(IBaseFilter * iface, DWORD dwMilliSecsTimeout, FILTER_STATE *pState)
432 {
433     AsyncReader *This = (AsyncReader *)iface;
434
435     TRACE("(%lu, %p)\n", dwMilliSecsTimeout, pState);
436
437     *pState = This->state;
438     
439     return S_OK;
440 }
441
442 static HRESULT WINAPI AsyncReader_SetSyncSource(IBaseFilter * iface, IReferenceClock *pClock)
443 {
444 /*    AsyncReader *This = (AsyncReader *)iface;*/
445
446     TRACE("(%p)\n", pClock);
447
448     return S_OK;
449 }
450
451 static HRESULT WINAPI AsyncReader_GetSyncSource(IBaseFilter * iface, IReferenceClock **ppClock)
452 {
453 /*    AsyncReader *This = (AsyncReader *)iface;*/
454
455     TRACE("(%p)\n", ppClock);
456
457     return S_OK;
458 }
459
460 /** IBaseFilter methods **/
461
462 static HRESULT WINAPI AsyncReader_EnumPins(IBaseFilter * iface, IEnumPins **ppEnum)
463 {
464     ENUMPINDETAILS epd;
465     AsyncReader *This = (AsyncReader *)iface;
466
467     TRACE("(%p)\n", ppEnum);
468
469     epd.cPins = This->pOutputPin ? 1 : 0;
470     epd.ppPins = &This->pOutputPin;
471     return IEnumPinsImpl_Construct(&epd, ppEnum);
472 }
473
474 static HRESULT WINAPI AsyncReader_FindPin(IBaseFilter * iface, LPCWSTR Id, IPin **ppPin)
475 {
476     FIXME("(%s, %p)\n", debugstr_w(Id), ppPin);
477
478     return E_NOTIMPL;
479 }
480
481 static HRESULT WINAPI AsyncReader_QueryFilterInfo(IBaseFilter * iface, FILTER_INFO *pInfo)
482 {
483     AsyncReader *This = (AsyncReader *)iface;
484
485     TRACE("(%p)\n", pInfo);
486
487     strcpyW(pInfo->achName, This->filterInfo.achName);
488     pInfo->pGraph = This->filterInfo.pGraph;
489
490     if (pInfo->pGraph)
491         IFilterGraph_AddRef(pInfo->pGraph);
492     
493     return S_OK;
494 }
495
496 static HRESULT WINAPI AsyncReader_JoinFilterGraph(IBaseFilter * iface, IFilterGraph *pGraph, LPCWSTR pName)
497 {
498     AsyncReader *This = (AsyncReader *)iface;
499
500     TRACE("(%p, %s)\n", pGraph, debugstr_w(pName));
501
502     if (pName)
503         strcpyW(This->filterInfo.achName, pName);
504     else
505         *This->filterInfo.achName = 0;
506     This->filterInfo.pGraph = pGraph; /* NOTE: do NOT increase ref. count */
507
508     return S_OK;
509 }
510
511 static HRESULT WINAPI AsyncReader_QueryVendorInfo(IBaseFilter * iface, LPWSTR *pVendorInfo)
512 {
513     FIXME("(%p)\n", pVendorInfo);
514
515     return E_NOTIMPL;
516 }
517
518 static const IBaseFilterVtbl AsyncReader_Vtbl =
519 {
520     AsyncReader_QueryInterface,
521     AsyncReader_AddRef,
522     AsyncReader_Release,
523     AsyncReader_GetClassID,
524     AsyncReader_Stop,
525     AsyncReader_Pause,
526     AsyncReader_Run,
527     AsyncReader_GetState,
528     AsyncReader_SetSyncSource,
529     AsyncReader_GetSyncSource,
530     AsyncReader_EnumPins,
531     AsyncReader_FindPin,
532     AsyncReader_QueryFilterInfo,
533     AsyncReader_JoinFilterGraph,
534     AsyncReader_QueryVendorInfo
535 };
536
537 static HRESULT WINAPI FileSource_QueryInterface(IFileSourceFilter * iface, REFIID riid, LPVOID * ppv)
538 {
539     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
540
541     return IBaseFilter_QueryInterface((IFileSourceFilter*)&This->lpVtbl, riid, ppv);
542 }
543
544 static ULONG WINAPI FileSource_AddRef(IFileSourceFilter * iface)
545 {
546     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
547
548     return IBaseFilter_AddRef((IFileSourceFilter*)&This->lpVtbl);
549 }
550
551 static ULONG WINAPI FileSource_Release(IFileSourceFilter * iface)
552 {
553     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
554
555     return IBaseFilter_Release((IFileSourceFilter*)&This->lpVtbl);
556 }
557
558 static HRESULT WINAPI FileSource_Load(IFileSourceFilter * iface, LPCOLESTR pszFileName, const AM_MEDIA_TYPE * pmt)
559 {
560     HRESULT hr;
561     HANDLE hFile;
562     IAsyncReader * pReader = NULL;
563     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
564
565     TRACE("(%s, %p)\n", debugstr_w(pszFileName), pmt);
566
567     /* open file */
568     /* FIXME: check the sharing values that native uses */
569     hFile = CreateFileW(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
570
571     if (hFile == INVALID_HANDLE_VALUE)
572     {
573         return HRESULT_FROM_WIN32(GetLastError());
574     }
575
576     /* create pin */
577     hr = FileAsyncReader_Construct(hFile, (IBaseFilter *)&This->lpVtbl, &This->csFilter, &This->pOutputPin);
578
579     if (SUCCEEDED(hr))
580         hr = IPin_QueryInterface(This->pOutputPin, &IID_IAsyncReader, (LPVOID *)&pReader);
581
582     /* store file name & media type */
583     if (SUCCEEDED(hr))
584     {
585         This->pszFileName = CoTaskMemAlloc((strlenW(pszFileName) + 1) * sizeof(WCHAR));
586         strcpyW(This->pszFileName, pszFileName);
587         This->pmt = CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
588         if (!pmt)
589         {
590             This->pmt->bFixedSizeSamples = TRUE;
591             This->pmt->bTemporalCompression = FALSE;
592             This->pmt->cbFormat = 0;
593             This->pmt->pbFormat = NULL;
594             This->pmt->pUnk = NULL;
595             This->pmt->lSampleSize = 0;
596             memcpy(&This->pmt->formattype, &FORMAT_None, sizeof(FORMAT_None));
597             hr = GetClassMediaFile(pReader, pszFileName, &This->pmt->majortype, &This->pmt->subtype);
598             if (FAILED(hr))
599             {
600                 CoTaskMemFree(This->pmt);
601                 This->pmt = NULL;
602             }
603         }
604         else
605             CopyMediaType(This->pmt, pmt);
606     }
607
608     if (pReader)
609         IAsyncReader_Release(pReader);
610
611     if (FAILED(hr))
612     {
613         if (This->pOutputPin)
614         {
615             IPin_Release(This->pOutputPin);
616             This->pOutputPin = NULL;
617         }
618         if (This->pszFileName)
619         {
620             CoTaskMemFree(This->pszFileName);
621             This->pszFileName = NULL;
622         }
623         CloseHandle(hFile);
624     }
625
626     /* FIXME: check return codes */
627     return hr;
628 }
629
630 static HRESULT WINAPI FileSource_GetCurFile(IFileSourceFilter * iface, LPOLESTR * ppszFileName, AM_MEDIA_TYPE * pmt)
631 {
632     ICOM_THIS_From_IFileSourceFilter(AsyncReader, iface);
633     
634     TRACE("(%p, %p)\n", ppszFileName, pmt);
635
636     /* copy file name & media type if available, otherwise clear the outputs */
637     if (This->pszFileName)
638     {
639         *ppszFileName = CoTaskMemAlloc((strlenW(This->pszFileName) + 1) * sizeof(WCHAR));
640         strcpyW(*ppszFileName, This->pszFileName);
641     }
642     else
643         *ppszFileName = NULL;
644
645     if (This->pmt)
646     {
647         CopyMediaType(pmt, This->pmt);
648     }
649     else
650         ZeroMemory(pmt, sizeof(*pmt));
651
652     return S_OK;
653 }
654
655 static const IFileSourceFilterVtbl FileSource_Vtbl = 
656 {
657     FileSource_QueryInterface,
658     FileSource_AddRef,
659     FileSource_Release,
660     FileSource_Load,
661     FileSource_GetCurFile
662 };
663
664
665 /* the dwUserData passed back to user */
666 typedef struct DATAREQUEST
667 {
668     IMediaSample * pSample; /* sample passed to us by user */
669     DWORD_PTR dwUserData; /* user data passed to us */
670     OVERLAPPED ovl; /* our overlapped structure */
671
672     struct DATAREQUEST * pNext; /* next data request in list */
673 } DATAREQUEST;
674
675 void queue(DATAREQUEST * pHead, DATAREQUEST * pItem)
676 {
677     DATAREQUEST * pCurrent;
678     for (pCurrent = pHead; pCurrent->pNext; pCurrent = pCurrent->pNext)
679         ;
680     pCurrent->pNext = pItem;
681 }
682
683 typedef struct FileAsyncReader
684 {
685     OutputPin pin;
686     const struct IAsyncReaderVtbl * lpVtblAR;
687
688     HANDLE hFile;
689     HANDLE hEvent;
690     BOOL bFlushing;
691     DATAREQUEST * pHead; /* head of data request list */
692     CRITICAL_SECTION csList; /* critical section to protect operations on list */
693 } FileAsyncReader;
694
695 static HRESULT AcceptProcAFR(LPVOID iface, const AM_MEDIA_TYPE *pmt)
696 {
697     AsyncReader *This = (AsyncReader *)iface;
698     
699     FIXME("(%p, %p)\n", iface, pmt);
700
701     if (IsEqualGUID(&pmt->majortype, &This->pmt->majortype) &&
702         IsEqualGUID(&pmt->subtype, &This->pmt->subtype) &&
703         IsEqualGUID(&pmt->formattype, &FORMAT_None))
704         return S_OK;
705     
706     return S_FALSE;
707 }
708
709 /* overriden pin functions */
710
711 static HRESULT WINAPI FileAsyncReaderPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
712 {
713     FileAsyncReader *This = (FileAsyncReader *)iface;
714     TRACE("(%s, %p)\n", qzdebugstr_guid(riid), ppv);
715
716     *ppv = NULL;
717
718     if (IsEqualIID(riid, &IID_IUnknown))
719         *ppv = (LPVOID)This;
720     else if (IsEqualIID(riid, &IID_IPin))
721         *ppv = (LPVOID)This;
722     else if (IsEqualIID(riid, &IID_IAsyncReader))
723         *ppv = (LPVOID)&This->lpVtblAR;
724
725     if (*ppv)
726     {
727         IUnknown_AddRef((IUnknown *)(*ppv));
728         return S_OK;
729     }
730
731     FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
732
733     return E_NOINTERFACE;
734 }
735
736 static ULONG WINAPI FileAsyncReaderPin_Release(IPin * iface)
737 {
738     FileAsyncReader *This = (FileAsyncReader *)iface;
739     
740     TRACE("()\n");
741     
742     if (!InterlockedDecrement(&This->pin.pin.refCount))
743     {
744         DATAREQUEST * pCurrent;
745         DATAREQUEST * pNext;
746         for (pCurrent = This->pHead; pCurrent; pCurrent = pNext)
747         {
748             pNext = pCurrent->pNext;
749             CoTaskMemFree(pCurrent);
750         }
751         CloseHandle(This->hFile);
752         CloseHandle(This->hEvent);
753         CoTaskMemFree(This);
754         return 0;
755     }
756     return This->pin.pin.refCount;
757 }
758
759 static HRESULT WINAPI FileAsyncReaderPin_EnumMediaTypes(IPin * iface, IEnumMediaTypes ** ppEnum)
760 {
761     ENUMMEDIADETAILS emd;
762     FileAsyncReader *This = (FileAsyncReader *)iface;
763
764     TRACE("(%p)\n", ppEnum);
765
766     emd.cMediaTypes = 1;
767     emd.pMediaTypes = ((AsyncReader *)This->pin.pin.pinInfo.pFilter)->pmt;
768
769     return IEnumMediaTypesImpl_Construct(&emd, ppEnum);
770 }
771
772 static const IPinVtbl FileAsyncReaderPin_Vtbl = 
773 {
774     FileAsyncReaderPin_QueryInterface,
775     IPinImpl_AddRef,
776     FileAsyncReaderPin_Release,
777     OutputPin_Connect,
778     OutputPin_ReceiveConnection,
779     IPinImpl_Disconnect,
780     IPinImpl_ConnectedTo,
781     IPinImpl_ConnectionMediaType,
782     IPinImpl_QueryPinInfo,
783     IPinImpl_QueryDirection,
784     IPinImpl_QueryId,
785     IPinImpl_QueryAccept,
786     FileAsyncReaderPin_EnumMediaTypes,
787     IPinImpl_QueryInternalConnections,
788     OutputPin_EndOfStream,
789     OutputPin_BeginFlush,
790     OutputPin_EndFlush,
791     OutputPin_NewSegment
792 };
793
794 /* Function called as a helper to IPin_Connect */
795 /* specific AM_MEDIA_TYPE - it cannot be NULL */
796 /* this differs from standard OutputPin_ConnectSpecific only in that it
797  * doesn't need the IMemInputPin interface on the receiving pin */
798 static HRESULT FileAsyncReaderPin_ConnectSpecific(IPin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
799 {
800     OutputPin *This = (OutputPin *)iface;
801     HRESULT hr;
802
803     TRACE("(%p, %p)\n", pReceivePin, pmt);
804     dump_AM_MEDIA_TYPE(pmt);
805
806     /* FIXME: call queryacceptproc */
807
808     This->pin.pConnectedTo = pReceivePin;
809     IPin_AddRef(pReceivePin);
810     CopyMediaType(&This->pin.mtCurrent, pmt);
811
812     hr = IPin_ReceiveConnection(pReceivePin, iface, pmt);
813
814     if (FAILED(hr))
815     {
816         IPin_Release(This->pin.pConnectedTo);
817         This->pin.pConnectedTo = NULL;
818         DeleteMediaType(&This->pin.mtCurrent);
819     }
820
821     TRACE(" -- %lx\n", hr);
822     return hr;
823 }
824
825 static HRESULT FileAsyncReader_Construct(HANDLE hFile, IBaseFilter * pBaseFilter, LPCRITICAL_SECTION pCritSec, IPin ** ppPin)
826 {
827     FileAsyncReader * pPinImpl;
828     PIN_INFO piOutput;
829
830     *ppPin = NULL;
831
832     pPinImpl = CoTaskMemAlloc(sizeof(*pPinImpl));
833
834     if (!pPinImpl)
835         return E_OUTOFMEMORY;
836
837     piOutput.dir = PINDIR_OUTPUT;
838     piOutput.pFilter = pBaseFilter;
839     strcpyW(piOutput.achName, wszOutputPinName);
840
841     if (SUCCEEDED(OutputPin_Init(&piOutput, NULL, pBaseFilter, AcceptProcAFR, pCritSec, &pPinImpl->pin)))
842     {
843         pPinImpl->pin.pin.lpVtbl = &FileAsyncReaderPin_Vtbl;
844         pPinImpl->lpVtblAR = &FileAsyncReader_Vtbl;
845         pPinImpl->hFile = hFile;
846         pPinImpl->hEvent = CreateEventW(NULL, 0, 0, NULL);
847         pPinImpl->bFlushing = FALSE;
848         pPinImpl->pHead = NULL;
849         pPinImpl->pin.pConnectSpecific = FileAsyncReaderPin_ConnectSpecific;
850         InitializeCriticalSection(&pPinImpl->csList);
851
852         *ppPin = (IPin *)(&pPinImpl->pin.pin.lpVtbl);
853         return S_OK;
854     }
855     return E_FAIL;
856 }
857
858 /* IAsyncReader */
859
860 static HRESULT WINAPI FileAsyncReader_QueryInterface(IAsyncReader * iface, REFIID riid, LPVOID * ppv)
861 {
862     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
863
864     return IPin_QueryInterface((IPin *)This, riid, ppv);
865 }
866
867 static ULONG WINAPI FileAsyncReader_AddRef(IAsyncReader * iface)
868 {
869     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
870
871     return IPin_AddRef((IPin *)This);
872 }
873
874 static ULONG WINAPI FileAsyncReader_Release(IAsyncReader * iface)
875 {
876     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
877
878     return IPin_Release((IPin *)This);
879 }
880
881 #define DEF_ALIGNMENT 1
882
883 static HRESULT WINAPI FileAsyncReader_RequestAllocator(IAsyncReader * iface, IMemAllocator * pPreferred, ALLOCATOR_PROPERTIES * pProps, IMemAllocator ** ppActual)
884 {
885     HRESULT hr = S_OK;
886
887     TRACE("(%p, %p, %p)\n", pPreferred, pProps, ppActual);
888
889     if (!pProps->cbAlign || (pProps->cbAlign % DEF_ALIGNMENT) != 0)
890         pProps->cbAlign = DEF_ALIGNMENT;
891
892     if (pPreferred)
893     {
894         ALLOCATOR_PROPERTIES PropsActual;
895         hr = IMemAllocator_SetProperties(pPreferred, pProps, &PropsActual);
896         /* FIXME: check we are still aligned */
897         if (SUCCEEDED(hr))
898         {
899             IMemAllocator_AddRef(pPreferred);
900             *ppActual = pPreferred;
901             TRACE("FileAsyncReader_RequestAllocator -- %lx\n", hr);
902             return S_OK;
903         }
904     }
905
906     pPreferred = NULL;
907
908     hr = CoCreateInstance(&CLSID_MemoryAllocator, NULL, CLSCTX_INPROC, &IID_IMemAllocator, (LPVOID *)&pPreferred);
909
910     if (SUCCEEDED(hr))
911     {
912         ALLOCATOR_PROPERTIES PropsActual;
913         hr = IMemAllocator_SetProperties(pPreferred, pProps, &PropsActual);
914         /* FIXME: check we are still aligned */
915         if (SUCCEEDED(hr))
916         {
917             IMemAllocator_AddRef(pPreferred);
918             *ppActual = pPreferred;
919             TRACE("FileAsyncReader_RequestAllocator -- %lx\n", hr);
920             return S_OK;
921         }
922     }
923
924     if (FAILED(hr))
925     {
926         *ppActual = NULL;
927         if (pPreferred)
928             IMemAllocator_Release(pPreferred);
929     }
930
931     TRACE("-- %lx\n", hr);
932     return hr;
933 }
934
935 /* we could improve the Request/WaitForNext mechanism by allowing out of order samples.
936  * however, this would be quite complicated to do and may be a bit error prone */
937 static HRESULT WINAPI FileAsyncReader_Request(IAsyncReader * iface, IMediaSample * pSample, DWORD_PTR dwUser)
938 {
939     REFERENCE_TIME Start;
940     REFERENCE_TIME Stop;
941     DATAREQUEST * pDataRq;
942     BYTE * pBuffer;
943     HRESULT hr = S_OK;
944     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
945
946     TRACE("(%p, %lx)\n", pSample, dwUser);
947
948     /* check flushing state */
949     if (This->bFlushing)
950         return VFW_E_WRONG_STATE;
951
952     if (!(pDataRq = CoTaskMemAlloc(sizeof(*pDataRq))))
953         hr = E_OUTOFMEMORY;
954
955     /* get start and stop positions in bytes */
956     if (SUCCEEDED(hr))
957         hr = IMediaSample_GetTime(pSample, &Start, &Stop);
958
959     if (SUCCEEDED(hr))
960         hr = IMediaSample_GetPointer(pSample, &pBuffer);
961
962     if (SUCCEEDED(hr))
963     {
964         DWORD dwLength = (DWORD) BYTES_FROM_MEDIATIME(Stop - Start);
965
966         pDataRq->ovl.Offset = (DWORD) BYTES_FROM_MEDIATIME(Start);
967         pDataRq->ovl.OffsetHigh = (DWORD)(BYTES_FROM_MEDIATIME(Start) >> (sizeof(DWORD) * 8));
968         pDataRq->ovl.hEvent = This->hEvent;
969         pDataRq->dwUserData = dwUser;
970         pDataRq->pNext = NULL;
971         /* we violate traditional COM rules here by maintaining
972          * a reference to the sample, but not calling AddRef, but
973          * that's what MSDN says to do */
974         pDataRq->pSample = pSample;
975
976         EnterCriticalSection(&This->csList);
977         {
978             if (This->pHead)
979                 /* adds data request to end of list */
980                 queue(This->pHead, pDataRq);
981             else
982                 This->pHead = pDataRq;
983         }
984         LeaveCriticalSection(&This->csList);
985
986         /* this is definitely not how it is implemented on Win9x
987          * as they do not support async reads on files, but it is
988          * sooo much easier to use this than messing around with threads!
989          */
990         if (!ReadFile(This->hFile, pBuffer, dwLength, NULL, &pDataRq->ovl))
991             hr = HRESULT_FROM_WIN32(GetLastError());
992
993         /* ERROR_IO_PENDING is not actually an error since this is what we want! */
994         if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING))
995             hr = S_OK;
996     }
997
998     if (FAILED(hr) && pDataRq)
999     {
1000         EnterCriticalSection(&This->csList);
1001         {
1002             DATAREQUEST * pCurrent;
1003             for (pCurrent = This->pHead; pCurrent && pCurrent->pNext; pCurrent = pCurrent->pNext)
1004                 if (pCurrent->pNext == pDataRq)
1005                 {
1006                     pCurrent->pNext = pDataRq->pNext;
1007                     break;
1008                 }
1009         }
1010         LeaveCriticalSection(&This->csList);
1011         CoTaskMemFree(pDataRq);
1012     }
1013
1014     TRACE("-- %lx\n", hr);
1015     return hr;
1016 }
1017
1018 static HRESULT WINAPI FileAsyncReader_WaitForNext(IAsyncReader * iface, DWORD dwTimeout, IMediaSample ** ppSample, DWORD_PTR * pdwUser)
1019 {
1020     HRESULT hr = S_OK;
1021     DATAREQUEST * pDataRq = NULL;
1022     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1023
1024     TRACE("(%lu, %p, %p)\n", dwTimeout, ppSample, pdwUser);
1025
1026     /* FIXME: we could do with improving this by waiting for an array of event handles
1027      * and then determining which one finished and removing that from the list, otherwise
1028      * we will end up waiting for longer than we should do, if a later request finishes
1029      * before an earlier one */
1030
1031     *ppSample = NULL;
1032     *pdwUser = 0;
1033
1034     /* we return immediately if flushing */
1035     if (This->bFlushing)
1036         hr = VFW_E_WRONG_STATE;
1037
1038     if (SUCCEEDED(hr))
1039     {
1040         /* wait for the read to finish or timeout */
1041         if (WaitForSingleObject(This->hEvent, dwTimeout) == WAIT_TIMEOUT)
1042             hr = VFW_E_TIMEOUT;
1043     }
1044     if (SUCCEEDED(hr))
1045     {
1046         EnterCriticalSection(&This->csList);
1047         {
1048             pDataRq = This->pHead;
1049             if (pDataRq == NULL)
1050                 hr = E_FAIL;
1051             else
1052                 This->pHead = pDataRq->pNext;
1053         }
1054         LeaveCriticalSection(&This->csList);
1055     }
1056
1057     if (SUCCEEDED(hr))
1058     {
1059         DWORD dwBytes;
1060         /* get any errors */
1061         if (!GetOverlappedResult(This->hFile, &pDataRq->ovl, &dwBytes, FALSE))
1062             hr = HRESULT_FROM_WIN32(GetLastError());
1063     }
1064
1065     if (SUCCEEDED(hr))
1066     {
1067         *ppSample = pDataRq->pSample;
1068         *pdwUser = pDataRq->dwUserData;
1069     }
1070
1071     /* clean up */
1072     if (pDataRq)
1073     {
1074         /* no need to close event handle since we will close it when the pin is destroyed */
1075         CoTaskMemFree(pDataRq);
1076     }
1077     
1078     TRACE("-- %lx\n", hr);
1079     return hr;
1080 }
1081
1082 static HRESULT WINAPI FileAsyncReader_SyncRead(IAsyncReader * iface, LONGLONG llPosition, LONG lLength, BYTE * pBuffer);
1083
1084 static HRESULT WINAPI FileAsyncReader_SyncReadAligned(IAsyncReader * iface, IMediaSample * pSample)
1085 {
1086     BYTE * pBuffer;
1087     REFERENCE_TIME tStart;
1088     REFERENCE_TIME tStop;
1089     HRESULT hr;
1090
1091     TRACE("(%p)\n", pSample);
1092
1093     hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
1094
1095     if (SUCCEEDED(hr))
1096         hr = IMediaSample_GetPointer(pSample, &pBuffer);
1097
1098     if (SUCCEEDED(hr))
1099         hr = FileAsyncReader_SyncRead(iface, 
1100             BYTES_FROM_MEDIATIME(tStart),
1101             (LONG) BYTES_FROM_MEDIATIME(tStop - tStart),
1102             pBuffer);
1103
1104     TRACE("-- %lx\n", hr);
1105     return hr;
1106 }
1107
1108 static HRESULT WINAPI FileAsyncReader_SyncRead(IAsyncReader * iface, LONGLONG llPosition, LONG lLength, BYTE * pBuffer)
1109 {
1110     OVERLAPPED ovl;
1111     HRESULT hr = S_OK;
1112     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1113
1114     TRACE("(%lx%08lx, %ld, %p)\n", (ULONG)(llPosition >> 32), (ULONG)llPosition, lLength, pBuffer);
1115
1116     ZeroMemory(&ovl, sizeof(ovl));
1117
1118     ovl.hEvent = CreateEventW(NULL, 0, 0, NULL);
1119     /* NOTE: llPosition is the actual byte position to start reading from */
1120     ovl.Offset = (DWORD) llPosition;
1121     ovl.OffsetHigh = (DWORD) (llPosition >> (sizeof(DWORD) * 8));
1122
1123     if (!ReadFile(This->hFile, pBuffer, lLength, NULL, &ovl))
1124         hr = HRESULT_FROM_WIN32(GetLastError());
1125
1126     if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING))
1127         hr = S_OK;
1128
1129     if (SUCCEEDED(hr))
1130     {
1131         DWORD dwBytesRead;
1132
1133         if (!GetOverlappedResult(This->hFile, &ovl, &dwBytesRead, TRUE))
1134             hr = HRESULT_FROM_WIN32(GetLastError());
1135     }
1136
1137     CloseHandle(ovl.hEvent);
1138
1139     TRACE("-- %lx\n", hr);
1140     return hr;
1141 }
1142
1143 static HRESULT WINAPI FileAsyncReader_Length(IAsyncReader * iface, LONGLONG * pTotal, LONGLONG * pAvailable)
1144 {
1145     DWORD dwSizeLow;
1146     DWORD dwSizeHigh;
1147     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1148
1149     TRACE("(%p, %p)\n", pTotal, pAvailable);
1150
1151     if (((dwSizeLow = GetFileSize(This->hFile, &dwSizeHigh)) == -1) &&
1152         (GetLastError() != NO_ERROR))
1153         return HRESULT_FROM_WIN32(GetLastError());
1154
1155     *pTotal = (LONGLONG)dwSizeLow | (LONGLONG)dwSizeHigh << (sizeof(DWORD) * 8);
1156
1157     *pAvailable = *pTotal;
1158
1159     return S_OK;
1160 }
1161
1162 static HRESULT WINAPI FileAsyncReader_BeginFlush(IAsyncReader * iface)
1163 {
1164     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1165
1166     TRACE("()\n");
1167
1168     This->bFlushing = TRUE;
1169     CancelIo(This->hFile);
1170     SetEvent(This->hEvent);
1171     
1172     /* FIXME: free list */
1173
1174     return S_OK;
1175 }
1176
1177 static HRESULT WINAPI FileAsyncReader_EndFlush(IAsyncReader * iface)
1178 {
1179     ICOM_THIS_From_IAsyncReader(FileAsyncReader, iface);
1180
1181     TRACE("()\n");
1182
1183     This->bFlushing = FALSE;
1184
1185     return S_OK;
1186 }
1187
1188 static const IAsyncReaderVtbl FileAsyncReader_Vtbl = 
1189 {
1190     FileAsyncReader_QueryInterface,
1191     FileAsyncReader_AddRef,
1192     FileAsyncReader_Release,
1193     FileAsyncReader_RequestAllocator,
1194     FileAsyncReader_Request,
1195     FileAsyncReader_WaitForNext,
1196     FileAsyncReader_SyncReadAligned,
1197     FileAsyncReader_SyncRead,
1198     FileAsyncReader_Length,
1199     FileAsyncReader_BeginFlush,
1200     FileAsyncReader_EndFlush,
1201 };