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