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