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