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