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