dbghelp: Implement SymEnumSourceFilesW.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 "shlwapi.h"
34 #include <assert.h>
35
36 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
37
38 static const WCHAR wszOutputPinName[] = { 'O','u','t','p','u','t',0 };
39
40 typedef struct AsyncReader
41 {
42     BaseFilter filter;
43     const IFileSourceFilterVtbl * lpVtblFSF;
44     const IAMFilterMiscFlagsVtbl * IAMFilterMiscFlags_vtbl;
45
46     IPin * pOutputPin;
47     LPOLESTR pszFileName;
48     AM_MEDIA_TYPE * pmt;
49 } AsyncReader;
50
51 static const IBaseFilterVtbl AsyncReader_Vtbl;
52 static const IFileSourceFilterVtbl FileSource_Vtbl;
53 static const IAsyncReaderVtbl FileAsyncReader_Vtbl;
54 static const IAMFilterMiscFlagsVtbl IAMFilterMiscFlags_Vtbl;
55
56 static HRESULT FileAsyncReader_Construct(HANDLE hFile, IBaseFilter * pBaseFilter, LPCRITICAL_SECTION pCritSec, IPin ** ppPin);
57
58 static inline AsyncReader *impl_from_IFileSourceFilter( IFileSourceFilter *iface )
59 {
60     return (AsyncReader *)((char*)iface - FIELD_OFFSET(AsyncReader, lpVtblFSF));
61 }
62
63 static WCHAR const mediatype_name[11] = {
64     'M', 'e', 'd', 'i', 'a', ' ', 'T', 'y', 'p', 'e', 0 };
65 static WCHAR const subtype_name[8] = {
66     'S', 'u', 'b', 't', 'y', 'p', 'e', 0 };
67
68 static HRESULT process_extensions(HKEY hkeyExtensions, LPCOLESTR pszFileName, GUID * majorType, GUID * minorType)
69 {
70     WCHAR *extension;
71     LONG l;
72     HKEY hsub;
73     WCHAR keying[39];
74     DWORD size;
75
76     if (!pszFileName)
77         return E_POINTER;
78
79     /* Get the part of the name that matters */
80     extension = PathFindExtensionW(pszFileName);
81     if (*extension != '.')
82         return E_FAIL;
83
84     l = RegOpenKeyExW(hkeyExtensions, extension, 0, KEY_READ, &hsub);
85     if (l)
86         return E_FAIL;
87
88     size = sizeof(keying);
89     l = RegQueryValueExW(hsub, mediatype_name, NULL, NULL, (LPBYTE)keying, &size);
90     if (!l)
91         CLSIDFromString(keying, majorType);
92
93     size = sizeof(keying);
94     if (!l)
95         l = RegQueryValueExW(hsub, subtype_name, NULL, NULL, (LPBYTE)keying, &size);
96
97     if (!l)
98         CLSIDFromString(keying, minorType);
99
100     RegCloseKey(hsub);
101
102     if (!l)
103         return S_OK;
104     return E_FAIL;
105 }
106
107 static unsigned char byte_from_hex_char(WCHAR wHex)
108 {
109     switch (tolowerW(wHex))
110     {
111     case '0':
112     case '1':
113     case '2':
114     case '3':
115     case '4':
116     case '5':
117     case '6':
118     case '7':
119     case '8':
120     case '9':
121         return (wHex - '0') & 0xf;
122     case 'a':
123     case 'b':
124     case 'c':
125     case 'd':
126     case 'e':
127     case 'f':
128         return (wHex - 'a' + 10) & 0xf;
129     default:
130         return 0;
131     }
132 }
133
134 static HRESULT process_pattern_string(LPCWSTR wszPatternString, IAsyncReader * pReader)
135 {
136     ULONG ulOffset;
137     ULONG ulBytes;
138     BYTE * pbMask;
139     BYTE * pbValue;
140     BYTE * pbFile;
141     HRESULT hr = S_OK;
142     ULONG strpos;
143
144     TRACE("\t\tPattern string: %s\n", debugstr_w(wszPatternString));
145     
146     /* format: "offset, bytestocompare, mask, value" */
147
148     ulOffset = strtolW(wszPatternString, NULL, 10);
149
150     if (!(wszPatternString = strchrW(wszPatternString, ',')))
151         return E_INVALIDARG;
152
153     wszPatternString++; /* skip ',' */
154
155     ulBytes = strtolW(wszPatternString, NULL, 10);
156
157     pbMask = HeapAlloc(GetProcessHeap(), 0, ulBytes);
158     pbValue = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulBytes);
159     pbFile = HeapAlloc(GetProcessHeap(), 0, ulBytes);
160
161     /* default mask is match everything */
162     memset(pbMask, 0xFF, ulBytes);
163
164     if (!(wszPatternString = strchrW(wszPatternString, ',')))
165         hr = E_INVALIDARG;
166
167     if (hr == S_OK)
168     {
169         wszPatternString++; /* skip ',' */
170         while (!isxdigitW(*wszPatternString) && (*wszPatternString != ',')) wszPatternString++;
171
172         for (strpos = 0; isxdigitW(*wszPatternString) && (strpos/2 < ulBytes); wszPatternString++, strpos++)
173         {
174             if ((strpos % 2) == 1) /* odd numbered position */
175                 pbMask[strpos / 2] |= byte_from_hex_char(*wszPatternString);
176             else
177                 pbMask[strpos / 2] = byte_from_hex_char(*wszPatternString) << 4;
178         }
179
180         if (!(wszPatternString = strchrW(wszPatternString, ',')))
181             hr = E_INVALIDARG;
182         else
183             wszPatternString++; /* skip ',' */
184     }
185
186     if (hr == S_OK)
187     {
188         for ( ; !isxdigitW(*wszPatternString) && (*wszPatternString != ','); wszPatternString++)
189             ;
190
191         for (strpos = 0; isxdigitW(*wszPatternString) && (strpos/2 < ulBytes); wszPatternString++, strpos++)
192         {
193             if ((strpos % 2) == 1) /* odd numbered position */
194                 pbValue[strpos / 2] |= byte_from_hex_char(*wszPatternString);
195             else
196                 pbValue[strpos / 2] = byte_from_hex_char(*wszPatternString) << 4;
197         }
198     }
199
200     if (hr == S_OK)
201         hr = IAsyncReader_SyncRead(pReader, ulOffset, ulBytes, pbFile);
202
203     if (hr == S_OK)
204     {
205         ULONG i;
206         for (i = 0; i < ulBytes; i++)
207             if ((pbFile[i] & pbMask[i]) != pbValue[i])
208             {
209                 hr = S_FALSE;
210                 break;
211             }
212     }
213
214     HeapFree(GetProcessHeap(), 0, pbMask);
215     HeapFree(GetProcessHeap(), 0, pbValue);
216     HeapFree(GetProcessHeap(), 0, pbFile);
217
218     /* if we encountered no errors with this string, and there is a following tuple, then we
219      * have to match that as well to succeed */
220     if ((hr == S_OK) && (wszPatternString = strchrW(wszPatternString, ',')))
221         return process_pattern_string(wszPatternString + 1, pReader);
222     else
223         return hr;
224 }
225
226 static HRESULT GetClassMediaFile(IAsyncReader * pReader, LPCOLESTR pszFileName, GUID * majorType, GUID * minorType)
227 {
228     HKEY hkeyMediaType = NULL;
229     LONG lRet;
230     HRESULT hr = S_OK;
231     BOOL bFound = FALSE;
232     static const WCHAR wszMediaType[] = {'M','e','d','i','a',' ','T','y','p','e',0};
233
234     TRACE("(%p, %s, %p, %p)\n", pReader, debugstr_w(pszFileName), majorType, minorType);
235
236     *majorType = GUID_NULL;
237     *minorType = GUID_NULL;
238
239     lRet = RegOpenKeyExW(HKEY_CLASSES_ROOT, wszMediaType, 0, KEY_READ, &hkeyMediaType);
240     hr = HRESULT_FROM_WIN32(lRet);
241
242     if (SUCCEEDED(hr))
243     {
244         DWORD indexMajor;
245
246         for (indexMajor = 0; !bFound; indexMajor++)
247         {
248             HKEY hkeyMajor;
249             WCHAR wszMajorKeyName[CHARS_IN_GUID];
250             DWORD dwKeyNameLength = sizeof(wszMajorKeyName) / sizeof(wszMajorKeyName[0]);
251             static const WCHAR wszExtensions[] = {'E','x','t','e','n','s','i','o','n','s',0};
252
253             if (RegEnumKeyExW(hkeyMediaType, indexMajor, wszMajorKeyName, &dwKeyNameLength, NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
254                 break;
255             if (RegOpenKeyExW(hkeyMediaType, wszMajorKeyName, 0, KEY_READ, &hkeyMajor) != ERROR_SUCCESS)
256                 break;
257             TRACE("%s\n", debugstr_w(wszMajorKeyName));
258             if (!strcmpW(wszExtensions, wszMajorKeyName))
259             {
260                 if (process_extensions(hkeyMajor, pszFileName, majorType, minorType) == S_OK)
261                     bFound = TRUE;
262             }
263             else
264             {
265                 DWORD indexMinor;
266
267                 for (indexMinor = 0; !bFound; indexMinor++)
268                 {
269                     HKEY hkeyMinor;
270                     WCHAR wszMinorKeyName[CHARS_IN_GUID];
271                     DWORD dwMinorKeyNameLen = sizeof(wszMinorKeyName) / sizeof(wszMinorKeyName[0]);
272                     DWORD maxValueLen;
273                     DWORD indexValue;
274
275                     if (RegEnumKeyExW(hkeyMajor, indexMinor, wszMinorKeyName, &dwMinorKeyNameLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
276                         break;
277
278                     if (RegOpenKeyExW(hkeyMajor, wszMinorKeyName, 0, KEY_READ, &hkeyMinor) != ERROR_SUCCESS)
279                         break;
280
281                     TRACE("\t%s\n", debugstr_w(wszMinorKeyName));
282         
283                     if (RegQueryInfoKeyW(hkeyMinor, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &maxValueLen, NULL, NULL) != ERROR_SUCCESS)
284                         break;
285
286                     for (indexValue = 0; !bFound; indexValue++)
287                     {
288                         DWORD dwType;
289                         WCHAR wszValueName[14]; /* longest name we should encounter will be "Source Filter" */
290                         LPWSTR wszPatternString = HeapAlloc(GetProcessHeap(), 0, maxValueLen);
291                         DWORD dwValueNameLen = sizeof(wszValueName) / sizeof(wszValueName[0]); /* remember this is in chars */
292                         DWORD dwDataLen = maxValueLen; /* remember this is in bytes */
293                         static const WCHAR wszSourceFilter[] = {'S','o','u','r','c','e',' ','F','i','l','t','e','r',0};
294                         LONG temp;
295
296                         if ((temp = RegEnumValueW(hkeyMinor, indexValue, wszValueName, &dwValueNameLen, NULL, &dwType, (LPBYTE)wszPatternString, &dwDataLen)) != ERROR_SUCCESS)
297                         {
298                             HeapFree(GetProcessHeap(), 0, wszPatternString);
299                             break;
300                         }
301
302                         /* if it is not the source filter value */
303                         if (strcmpW(wszValueName, wszSourceFilter))
304                         {
305                             if (process_pattern_string(wszPatternString, pReader) == S_OK)
306                             {
307                                 if (SUCCEEDED(CLSIDFromString(wszMajorKeyName, majorType)) &&
308                                     SUCCEEDED(CLSIDFromString(wszMinorKeyName, minorType)))
309                                     bFound = TRUE;
310                             }
311                         }
312                         HeapFree(GetProcessHeap(), 0, wszPatternString);
313                     }
314                     CloseHandle(hkeyMinor);
315                 }
316             }
317             CloseHandle(hkeyMajor);
318         }
319     }
320     CloseHandle(hkeyMediaType);
321
322     if (SUCCEEDED(hr) && !bFound)
323     {
324         ERR("Media class not found\n");
325         hr = E_FAIL;
326     }
327     else if (bFound)
328         TRACE("Found file's class: major = %s, subtype = %s\n", qzdebugstr_guid(majorType), qzdebugstr_guid(minorType));
329
330     return hr;
331 }
332
333 static IPin* WINAPI AsyncReader_GetPin(BaseFilter *iface, int pos)
334 {
335     AsyncReader *This = (AsyncReader *)iface;
336
337     if (pos >= 1 || !This->pOutputPin)
338         return NULL;
339
340     IPin_AddRef(This->pOutputPin);
341     return This->pOutputPin;
342 }
343
344 static LONG WINAPI AsyncReader_GetPinCount(BaseFilter *iface)
345 {
346     AsyncReader *This = (AsyncReader *)iface;
347
348     if (!This->pOutputPin)
349         return 0;
350     else
351         return 1;
352 }
353
354 static const BaseFilterFuncTable BaseFuncTable = {
355     AsyncReader_GetPin,
356     AsyncReader_GetPinCount
357 };
358
359 HRESULT AsyncReader_create(IUnknown * pUnkOuter, LPVOID * ppv)
360 {
361     AsyncReader *pAsyncRead;
362     
363     if( pUnkOuter )
364         return CLASS_E_NOAGGREGATION;
365     
366     pAsyncRead = CoTaskMemAlloc(sizeof(AsyncReader));
367
368     if (!pAsyncRead)
369         return E_OUTOFMEMORY;
370
371     BaseFilter_Init(&pAsyncRead->filter, &AsyncReader_Vtbl, &CLSID_AsyncReader, (DWORD_PTR)(__FILE__ ": AsyncReader.csFilter"), &BaseFuncTable);
372
373     pAsyncRead->lpVtblFSF = &FileSource_Vtbl;
374     pAsyncRead->IAMFilterMiscFlags_vtbl = &IAMFilterMiscFlags_Vtbl;
375     pAsyncRead->pOutputPin = NULL;
376
377     pAsyncRead->pszFileName = NULL;
378     pAsyncRead->pmt = NULL;
379
380     *ppv = pAsyncRead;
381
382     TRACE("-- created at %p\n", pAsyncRead);
383
384     return S_OK;
385 }
386
387 /** IUnknown methods **/
388
389 static HRESULT WINAPI AsyncReader_QueryInterface(IBaseFilter * iface, REFIID riid, LPVOID * ppv)
390 {
391     AsyncReader *This = (AsyncReader *)iface;
392
393     TRACE("(%s, %p)\n", qzdebugstr_guid(riid), ppv);
394
395     *ppv = NULL;
396
397     if (IsEqualIID(riid, &IID_IUnknown))
398         *ppv = This;
399     else if (IsEqualIID(riid, &IID_IPersist))
400         *ppv = This;
401     else if (IsEqualIID(riid, &IID_IMediaFilter))
402         *ppv = This;
403     else if (IsEqualIID(riid, &IID_IBaseFilter))
404         *ppv = This;
405     else if (IsEqualIID(riid, &IID_IFileSourceFilter))
406         *ppv = &This->lpVtblFSF;
407     else if (IsEqualIID(riid, &IID_IAMFilterMiscFlags))
408         *ppv = &This->IAMFilterMiscFlags_vtbl;
409
410     if (*ppv)
411     {
412         IUnknown_AddRef((IUnknown *)(*ppv));
413         return S_OK;
414     }
415
416     if (!IsEqualIID(riid, &IID_IPin) && !IsEqualIID(riid, &IID_IMediaSeeking) &&
417         !IsEqualIID(riid, &IID_IVideoWindow) && !IsEqualIID(riid, &IID_IBasicAudio))
418         FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
419
420     return E_NOINTERFACE;
421 }
422
423 static ULONG WINAPI AsyncReader_Release(IBaseFilter * iface)
424 {
425     AsyncReader *This = (AsyncReader *)iface;
426     ULONG refCount = BaseFilterImpl_Release(iface);
427     
428     TRACE("(%p)->() Release from %d\n", This, refCount + 1);
429     
430     if (!refCount)
431     {
432         if (This->pOutputPin)
433         {
434             IPin *pConnectedTo;
435             if(SUCCEEDED(IPin_ConnectedTo(This->pOutputPin, &pConnectedTo)))
436             {
437                 IPin_Disconnect(pConnectedTo);
438                 IPin_Release(pConnectedTo);
439             }
440             IPin_Disconnect(This->pOutputPin);
441             IPin_Release(This->pOutputPin);
442         }
443         CoTaskMemFree(This->pszFileName);
444         if (This->pmt)
445             FreeMediaType(This->pmt);
446         CoTaskMemFree(This);
447         return 0;
448     }
449     else
450         return refCount;
451 }
452
453 /** IMediaFilter methods **/
454
455 static HRESULT WINAPI AsyncReader_Stop(IBaseFilter * iface)
456 {
457     AsyncReader *This = (AsyncReader *)iface;
458
459     TRACE("()\n");
460
461     This->filter.state = State_Stopped;
462     
463     return S_OK;
464 }
465
466 static HRESULT WINAPI AsyncReader_Pause(IBaseFilter * iface)
467 {
468     AsyncReader *This = (AsyncReader *)iface;
469
470     TRACE("()\n");
471
472     This->filter.state = State_Paused;
473
474     return S_OK;
475 }
476
477 static HRESULT WINAPI AsyncReader_Run(IBaseFilter * iface, REFERENCE_TIME tStart)
478 {
479     AsyncReader *This = (AsyncReader *)iface;
480
481     TRACE("(%x%08x)\n", (ULONG)(tStart >> 32), (ULONG)tStart);
482
483     This->filter.state = State_Running;
484
485     return S_OK;
486 }
487
488 /** IBaseFilter methods **/
489
490 static HRESULT WINAPI AsyncReader_FindPin(IBaseFilter * iface, LPCWSTR Id, IPin **ppPin)
491 {
492     AsyncReader *This = (AsyncReader *)iface;
493     TRACE("(%s, %p)\n", debugstr_w(Id), ppPin);
494
495     if (!Id || !ppPin)
496         return E_POINTER;
497
498     if (strcmpW(Id, wszOutputPinName))
499     {
500         *ppPin = NULL;
501         return VFW_E_NOT_FOUND;
502     }
503
504     *ppPin = (IPin*)This->pOutputPin;
505     IUnknown_AddRef(*ppPin);
506     return S_OK;
507 }
508
509 static const IBaseFilterVtbl AsyncReader_Vtbl =
510 {
511     AsyncReader_QueryInterface,
512     BaseFilterImpl_AddRef,
513     AsyncReader_Release,
514     BaseFilterImpl_GetClassID,
515     AsyncReader_Stop,
516     AsyncReader_Pause,
517     AsyncReader_Run,
518     BaseFilterImpl_GetState,
519     BaseFilterImpl_SetSyncSource,
520     BaseFilterImpl_GetSyncSource,
521     BaseFilterImpl_EnumPins,
522     AsyncReader_FindPin,
523     BaseFilterImpl_QueryFilterInfo,
524     BaseFilterImpl_JoinFilterGraph,
525     BaseFilterImpl_QueryVendorInfo
526 };
527
528 static HRESULT WINAPI FileSource_QueryInterface(IFileSourceFilter * iface, REFIID riid, LPVOID * ppv)
529 {
530     AsyncReader *This = impl_from_IFileSourceFilter(iface);
531
532     return IBaseFilter_QueryInterface((IFileSourceFilter*)&This->filter.lpVtbl, riid, ppv);
533 }
534
535 static ULONG WINAPI FileSource_AddRef(IFileSourceFilter * iface)
536 {
537     AsyncReader *This = impl_from_IFileSourceFilter(iface);
538
539     return IBaseFilter_AddRef((IFileSourceFilter*)&This->filter.lpVtbl);
540 }
541
542 static ULONG WINAPI FileSource_Release(IFileSourceFilter * iface)
543 {
544     AsyncReader *This = impl_from_IFileSourceFilter(iface);
545
546     return IBaseFilter_Release((IFileSourceFilter*)&This->filter.lpVtbl);
547 }
548
549 static HRESULT WINAPI FileSource_Load(IFileSourceFilter * iface, LPCOLESTR pszFileName, const AM_MEDIA_TYPE * pmt)
550 {
551     HRESULT hr;
552     HANDLE hFile;
553     IAsyncReader * pReader = NULL;
554     AsyncReader *This = impl_from_IFileSourceFilter(iface);
555
556     TRACE("(%s, %p)\n", debugstr_w(pszFileName), pmt);
557
558     /* open file */
559     /* FIXME: check the sharing values that native uses */
560     hFile = CreateFileW(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
561
562     if (hFile == INVALID_HANDLE_VALUE)
563     {
564         return HRESULT_FROM_WIN32(GetLastError());
565     }
566
567     /* create pin */
568     hr = FileAsyncReader_Construct(hFile, (IBaseFilter *)&This->filter.lpVtbl, &This->filter.csFilter, &This->pOutputPin);
569     BaseFilterImpl_IncrementPinVersion((BaseFilter *)&This->filter.lpVtbl);
570
571     if (SUCCEEDED(hr))
572         hr = IPin_QueryInterface(This->pOutputPin, &IID_IAsyncReader, (LPVOID *)&pReader);
573
574     /* store file name & media type */
575     if (SUCCEEDED(hr))
576     {
577         CoTaskMemFree(This->pszFileName);
578         if (This->pmt)
579             FreeMediaType(This->pmt);
580
581         This->pszFileName = CoTaskMemAlloc((strlenW(pszFileName) + 1) * sizeof(WCHAR));
582         strcpyW(This->pszFileName, pszFileName);
583
584         This->pmt = CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
585         if (!pmt)
586         {
587             This->pmt->bFixedSizeSamples = TRUE;
588             This->pmt->bTemporalCompression = FALSE;
589             This->pmt->cbFormat = 0;
590             This->pmt->pbFormat = NULL;
591             This->pmt->pUnk = NULL;
592             This->pmt->lSampleSize = 0;
593             This->pmt->formattype = FORMAT_None;
594             hr = GetClassMediaFile(pReader, pszFileName, &This->pmt->majortype, &This->pmt->subtype);
595             if (FAILED(hr))
596             {
597                 CoTaskMemFree(This->pmt);
598                 This->pmt = NULL;
599             }
600         }
601         else
602             CopyMediaType(This->pmt, pmt);
603     }
604
605     if (pReader)
606         IAsyncReader_Release(pReader);
607
608     if (FAILED(hr))
609     {
610         if (This->pOutputPin)
611         {
612             IPin_Release(This->pOutputPin);
613             This->pOutputPin = NULL;
614         }
615
616         CoTaskMemFree(This->pszFileName);
617         if (This->pmt)
618             FreeMediaType(This->pmt);
619         This->pszFileName = NULL;
620         This->pmt = 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     AsyncReader *This = impl_from_IFileSourceFilter(iface);
632     
633     TRACE("(%p, %p)\n", ppszFileName, pmt);
634
635     if (!ppszFileName)
636         return E_POINTER;
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 (pmt)
648     {
649         if (This->pmt)
650             CopyMediaType(pmt, This->pmt);
651         else
652             ZeroMemory(pmt, sizeof(*pmt));
653     }
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 } DATAREQUEST;
675
676 typedef struct FileAsyncReader
677 {
678     BaseOutputPin pin;
679     const struct IAsyncReaderVtbl * lpVtblAR;
680
681     ALLOCATOR_PROPERTIES allocProps;
682     HANDLE hFile;
683     BOOL bFlushing;
684     /* Why would you need more? Every sample has its own handle */
685     LONG queued_number;
686     LONG samples;
687     LONG oldest_sample;
688     CRITICAL_SECTION csList; /* critical section to prevent concurrency issues */
689     DATAREQUEST *sample_list;
690
691     /* Have a handle for every sample, and then one more as flushing handle */
692     HANDLE *handle_list;
693 } FileAsyncReader;
694
695 static inline FileAsyncReader *impl_from_IAsyncReader( IAsyncReader *iface )
696 {
697     return (FileAsyncReader *)((char*)iface - FIELD_OFFSET(FileAsyncReader, lpVtblAR));
698 }
699
700 static HRESULT WINAPI FileAsyncReaderPin_QueryAccept(IPin *iface, const AM_MEDIA_TYPE *pmt)
701 {
702     FileAsyncReader *This = (FileAsyncReader *)iface;
703     AM_MEDIA_TYPE *pmt_filter = ((AsyncReader *)This->pin.pin.pinInfo.pFilter)->pmt;
704
705     FIXME("(%p, %p)\n", iface, pmt);
706
707     if (IsEqualGUID(&pmt->majortype, &pmt_filter->majortype) &&
708         IsEqualGUID(&pmt->subtype, &pmt_filter->subtype) &&
709         IsEqualGUID(&pmt->formattype, &FORMAT_None))
710         return S_OK;
711
712     return S_FALSE;
713 }
714
715 static HRESULT WINAPI FileAsyncReaderPin_GetMediaType(BasePin *iface, int iPosition, AM_MEDIA_TYPE *pmt)
716 {
717     FileAsyncReader *This = (FileAsyncReader *)iface;
718     if (iPosition < 0)
719         return E_INVALIDARG;
720     if (iPosition > 0)
721         return VFW_S_NO_MORE_ITEMS;
722     CopyMediaType(pmt, ((AsyncReader *)This->pin.pin.pinInfo.pFilter)->pmt);
723     return S_OK;
724 }
725
726 /* overridden pin functions */
727
728 static HRESULT WINAPI FileAsyncReaderPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
729 {
730     FileAsyncReader *This = (FileAsyncReader *)iface;
731     TRACE("(%s, %p)\n", qzdebugstr_guid(riid), ppv);
732
733     *ppv = NULL;
734
735     if (IsEqualIID(riid, &IID_IUnknown))
736         *ppv = This;
737     else if (IsEqualIID(riid, &IID_IPin))
738         *ppv = This;
739     else if (IsEqualIID(riid, &IID_IAsyncReader))
740         *ppv = &This->lpVtblAR;
741
742     if (*ppv)
743     {
744         IUnknown_AddRef((IUnknown *)(*ppv));
745         return S_OK;
746     }
747
748     if (!IsEqualIID(riid, &IID_IPin) && !IsEqualIID(riid, &IID_IMediaSeeking))
749         FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
750
751     return E_NOINTERFACE;
752 }
753
754 static ULONG WINAPI FileAsyncReaderPin_Release(IPin * iface)
755 {
756     FileAsyncReader *This = (FileAsyncReader *)iface;
757     ULONG refCount = InterlockedDecrement(&This->pin.pin.refCount);
758     int x;
759
760     TRACE("(%p)->() Release from %d\n", This, refCount + 1);
761
762     if (!refCount)
763     {
764         CoTaskMemFree(This->sample_list);
765         if (This->handle_list)
766         {
767             for (x = 0; x <= This->samples; ++x)
768                 CloseHandle(This->handle_list[x]);
769             CoTaskMemFree(This->handle_list);
770         }
771         CloseHandle(This->hFile);
772         This->csList.DebugInfo->Spare[0] = 0;
773         DeleteCriticalSection(&This->csList);
774         CoTaskMemFree(This);
775         return 0;
776     }
777     return refCount;
778 }
779
780 static const IPinVtbl FileAsyncReaderPin_Vtbl = 
781 {
782     FileAsyncReaderPin_QueryInterface,
783     BasePinImpl_AddRef,
784     FileAsyncReaderPin_Release,
785     BaseOutputPinImpl_Connect,
786     BaseOutputPinImpl_ReceiveConnection,
787     BasePinImpl_Disconnect,
788     BasePinImpl_ConnectedTo,
789     BasePinImpl_ConnectionMediaType,
790     BasePinImpl_QueryPinInfo,
791     BasePinImpl_QueryDirection,
792     BasePinImpl_QueryId,
793     FileAsyncReaderPin_QueryAccept,
794     BasePinImpl_EnumMediaTypes,
795     BasePinImpl_QueryInternalConnections,
796     BaseOutputPinImpl_EndOfStream,
797     BaseOutputPinImpl_BeginFlush,
798     BaseOutputPinImpl_EndFlush,
799     BasePinImpl_NewSegment
800 };
801
802 /* Function called as a helper to IPin_Connect */
803 /* specific AM_MEDIA_TYPE - it cannot be NULL */
804 /* this differs from standard OutputPin_AttemptConnection only in that it
805  * doesn't need the IMemInputPin interface on the receiving pin */
806 static HRESULT WINAPI FileAsyncReaderPin_AttemptConnection(BasePin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
807 {
808     BaseOutputPin *This = (BaseOutputPin *)iface;
809     HRESULT hr;
810
811     TRACE("(%p, %p)\n", pReceivePin, pmt);
812     dump_AM_MEDIA_TYPE(pmt);
813
814     /* FIXME: call queryacceptproc */
815
816     This->pin.pConnectedTo = pReceivePin;
817     IPin_AddRef(pReceivePin);
818     CopyMediaType(&This->pin.mtCurrent, pmt);
819
820     hr = IPin_ReceiveConnection(pReceivePin, (IPin*)iface, pmt);
821
822     if (FAILED(hr))
823     {
824         IPin_Release(This->pin.pConnectedTo);
825         This->pin.pConnectedTo = NULL;
826         FreeMediaType(&This->pin.mtCurrent);
827     }
828
829     TRACE(" -- %x\n", hr);
830     return hr;
831 }
832
833 static HRESULT WINAPI FileAsyncReaderPin_DecideBufferSize(BaseOutputPin *iface, IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *ppropInputRequest)
834 {
835     FileAsyncReader *This = (FileAsyncReader *)iface;
836     ALLOCATOR_PROPERTIES actual;
837
838     if (ppropInputRequest->cbAlign && ppropInputRequest->cbAlign != This->allocProps.cbAlign)
839         FIXME("Requested Buffer cbAlign mismatch %i,%i\n",This->allocProps.cbAlign, ppropInputRequest->cbAlign);
840     if (ppropInputRequest->cbPrefix)
841         FIXME("Requested Buffer cbPrefix mismatch %i,%i\n",This->allocProps.cbPrefix, ppropInputRequest->cbPrefix);
842     if (ppropInputRequest->cbBuffer)
843         FIXME("Requested Buffer cbBuffer mismatch %i,%i\n",This->allocProps.cbBuffer, ppropInputRequest->cbBuffer);
844     if (ppropInputRequest->cBuffers)
845         FIXME("Requested Buffer cBuffers mismatch %i,%i\n",This->allocProps.cBuffers, ppropInputRequest->cBuffers);
846
847     return IMemAllocator_SetProperties(pAlloc, &This->allocProps, &actual);
848 }
849
850 static const  BasePinFuncTable output_BaseFuncTable = {
851     NULL,
852     FileAsyncReaderPin_AttemptConnection,
853     BasePinImpl_GetMediaTypeVersion,
854     FileAsyncReaderPin_GetMediaType
855 };
856
857 static const BaseOutputPinFuncTable output_BaseOutputFuncTable = {
858     FileAsyncReaderPin_DecideBufferSize,
859     BaseOutputPinImpl_DecideAllocator,
860     BaseOutputPinImpl_BreakConnect
861 };
862
863 static HRESULT FileAsyncReader_Construct(HANDLE hFile, IBaseFilter * pBaseFilter, LPCRITICAL_SECTION pCritSec, IPin ** ppPin)
864 {
865     PIN_INFO piOutput;
866     HRESULT hr;
867
868     *ppPin = NULL;
869     piOutput.dir = PINDIR_OUTPUT;
870     piOutput.pFilter = pBaseFilter;
871     strcpyW(piOutput.achName, wszOutputPinName);
872     hr = BaseOutputPin_Construct(&FileAsyncReaderPin_Vtbl, sizeof(FileAsyncReader), &piOutput, &output_BaseFuncTable, &output_BaseOutputFuncTable, pCritSec, ppPin);
873
874     if (SUCCEEDED(hr))
875     {
876         FileAsyncReader *pPinImpl =  (FileAsyncReader *)*ppPin;
877         pPinImpl->lpVtblAR = &FileAsyncReader_Vtbl;
878         pPinImpl->hFile = hFile;
879         pPinImpl->bFlushing = FALSE;
880         pPinImpl->sample_list = NULL;
881         pPinImpl->handle_list = NULL;
882         pPinImpl->queued_number = 0;
883         InitializeCriticalSection(&pPinImpl->csList);
884         pPinImpl->csList.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FileAsyncReader.csList");
885     }
886     return hr;
887 }
888
889 /* IAsyncReader */
890
891 static HRESULT WINAPI FileAsyncReader_QueryInterface(IAsyncReader * iface, REFIID riid, LPVOID * ppv)
892 {
893     FileAsyncReader *This = impl_from_IAsyncReader(iface);
894
895     return IPin_QueryInterface((IPin *)This, riid, ppv);
896 }
897
898 static ULONG WINAPI FileAsyncReader_AddRef(IAsyncReader * iface)
899 {
900     FileAsyncReader *This = impl_from_IAsyncReader(iface);
901
902     return IPin_AddRef((IPin *)This);
903 }
904
905 static ULONG WINAPI FileAsyncReader_Release(IAsyncReader * iface)
906 {
907     FileAsyncReader *This = impl_from_IAsyncReader(iface);
908
909     return IPin_Release((IPin *)This);
910 }
911
912 #define DEF_ALIGNMENT 1
913
914 static HRESULT WINAPI FileAsyncReader_RequestAllocator(IAsyncReader * iface, IMemAllocator * pPreferred, ALLOCATOR_PROPERTIES * pProps, IMemAllocator ** ppActual)
915 {
916     FileAsyncReader *This = impl_from_IAsyncReader(iface);
917
918     HRESULT hr = S_OK;
919
920     TRACE("(%p, %p, %p)\n", pPreferred, pProps, ppActual);
921
922     if (!pProps->cbAlign || (pProps->cbAlign % DEF_ALIGNMENT) != 0)
923         pProps->cbAlign = DEF_ALIGNMENT;
924
925     if (pPreferred)
926     {
927         hr = IMemAllocator_SetProperties(pPreferred, pProps, pProps);
928         /* FIXME: check we are still aligned */
929         if (SUCCEEDED(hr))
930         {
931             IMemAllocator_AddRef(pPreferred);
932             *ppActual = pPreferred;
933             TRACE("FileAsyncReader_RequestAllocator -- %x\n", hr);
934             goto done;
935         }
936     }
937
938     pPreferred = NULL;
939
940     hr = CoCreateInstance(&CLSID_MemoryAllocator, NULL, CLSCTX_INPROC, &IID_IMemAllocator, (LPVOID *)&pPreferred);
941
942     if (SUCCEEDED(hr))
943     {
944         hr = IMemAllocator_SetProperties(pPreferred, pProps, pProps);
945         /* FIXME: check we are still aligned */
946         if (SUCCEEDED(hr))
947         {
948             *ppActual = pPreferred;
949             TRACE("FileAsyncReader_RequestAllocator -- %x\n", hr);
950         }
951     }
952
953 done:
954     if (SUCCEEDED(hr))
955     {
956         CoTaskMemFree(This->sample_list);
957         if (This->handle_list)
958         {
959             int x;
960             for (x = 0; x <= This->samples; ++x)
961                 CloseHandle(This->handle_list[x]);
962             CoTaskMemFree(This->handle_list);
963         }
964
965         This->samples = pProps->cBuffers;
966         This->oldest_sample = 0;
967         TRACE("Samples: %u\n", This->samples);
968         This->sample_list = CoTaskMemAlloc(sizeof(This->sample_list[0]) * pProps->cBuffers);
969         This->handle_list = CoTaskMemAlloc(sizeof(HANDLE) * pProps->cBuffers * 2);
970
971         if (This->sample_list && This->handle_list)
972         {
973             int x;
974             ZeroMemory(This->sample_list, sizeof(This->sample_list[0]) * pProps->cBuffers);
975             for (x = 0; x < This->samples; ++x)
976             {
977                 This->sample_list[x].ovl.hEvent = This->handle_list[x] = CreateEventW(NULL, 0, 0, NULL);
978                 if (x + 1 < This->samples)
979                     This->handle_list[This->samples + 1 + x] = This->handle_list[x];
980             }
981             This->handle_list[This->samples] = CreateEventW(NULL, 1, 0, NULL);
982             This->allocProps = *pProps;
983         }
984         else
985         {
986             hr = E_OUTOFMEMORY;
987             CoTaskMemFree(This->sample_list);
988             CoTaskMemFree(This->handle_list);
989             This->samples = 0;
990             This->sample_list = NULL;
991             This->handle_list = NULL;
992         }
993     }
994
995     if (FAILED(hr))
996     {
997         *ppActual = NULL;
998         if (pPreferred)
999             IMemAllocator_Release(pPreferred);
1000     }
1001
1002     TRACE("-- %x\n", hr);
1003     return hr;
1004 }
1005
1006 /* we could improve the Request/WaitForNext mechanism by allowing out of order samples.
1007  * however, this would be quite complicated to do and may be a bit error prone */
1008 static HRESULT WINAPI FileAsyncReader_Request(IAsyncReader * iface, IMediaSample * pSample, DWORD_PTR dwUser)
1009 {
1010     HRESULT hr = S_OK;
1011     REFERENCE_TIME Start;
1012     REFERENCE_TIME Stop;
1013     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1014     LPBYTE pBuffer = NULL;
1015
1016     TRACE("(%p, %lx)\n", pSample, dwUser);
1017
1018     if (!pSample)
1019         return E_POINTER;
1020
1021     /* get start and stop positions in bytes */
1022     if (SUCCEEDED(hr))
1023         hr = IMediaSample_GetTime(pSample, &Start, &Stop);
1024
1025     if (SUCCEEDED(hr))
1026         hr = IMediaSample_GetPointer(pSample, &pBuffer);
1027
1028     EnterCriticalSection(&This->csList);
1029     if (This->bFlushing)
1030     {
1031         LeaveCriticalSection(&This->csList);
1032         return VFW_E_WRONG_STATE;
1033     }
1034
1035     if (SUCCEEDED(hr))
1036     {
1037         DWORD dwLength = (DWORD) BYTES_FROM_MEDIATIME(Stop - Start);
1038         DATAREQUEST *pDataRq;
1039         int x;
1040
1041         /* Try to insert above the waiting sample if possible */
1042         for (x = This->oldest_sample; x < This->samples; ++x)
1043         {
1044             if (!This->sample_list[x].pSample)
1045                 break;
1046         }
1047
1048         if (x >= This->samples)
1049             for (x = 0; x < This->oldest_sample; ++x)
1050             {
1051                 if (!This->sample_list[x].pSample)
1052                     break;
1053             }
1054
1055         /* There must be a sample we have found */
1056         assert(x < This->samples);
1057         ++This->queued_number;
1058
1059         pDataRq = This->sample_list + x;
1060
1061         pDataRq->ovl.u.s.Offset = (DWORD) BYTES_FROM_MEDIATIME(Start);
1062         pDataRq->ovl.u.s.OffsetHigh = (DWORD)(BYTES_FROM_MEDIATIME(Start) >> (sizeof(DWORD) * 8));
1063         pDataRq->dwUserData = dwUser;
1064
1065         /* we violate traditional COM rules here by maintaining
1066          * a reference to the sample, but not calling AddRef, but
1067          * that's what MSDN says to do */
1068         pDataRq->pSample = pSample;
1069
1070         /* this is definitely not how it is implemented on Win9x
1071          * as they do not support async reads on files, but it is
1072          * sooo much easier to use this than messing around with threads!
1073          */
1074         if (!ReadFile(This->hFile, pBuffer, dwLength, NULL, &pDataRq->ovl))
1075             hr = HRESULT_FROM_WIN32(GetLastError());
1076
1077         /* ERROR_IO_PENDING is not actually an error since this is what we want! */
1078         if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING))
1079             hr = S_OK;
1080     }
1081
1082     LeaveCriticalSection(&This->csList);
1083
1084     TRACE("-- %x\n", hr);
1085     return hr;
1086 }
1087
1088 static HRESULT WINAPI FileAsyncReader_WaitForNext(IAsyncReader * iface, DWORD dwTimeout, IMediaSample ** ppSample, DWORD_PTR * pdwUser)
1089 {
1090     HRESULT hr = S_OK;
1091     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1092     DWORD buffer = ~0;
1093
1094     TRACE("(%u, %p, %p)\n", dwTimeout, ppSample, pdwUser);
1095
1096     *ppSample = NULL;
1097     *pdwUser = 0;
1098
1099     EnterCriticalSection(&This->csList);
1100     if (!This->bFlushing)
1101     {
1102         LONG oldest = This->oldest_sample;
1103
1104         if (!This->queued_number)
1105         {
1106             /* It could be that nothing is queued right now, but that can be fixed */
1107             WARN("Called without samples in queue and not flushing!!\n");
1108         }
1109         LeaveCriticalSection(&This->csList);
1110
1111         /* wait for an object to read, or time out */
1112         buffer = WaitForMultipleObjectsEx(This->samples+1, This->handle_list + oldest, FALSE, dwTimeout, TRUE);
1113
1114         EnterCriticalSection(&This->csList);
1115         if (buffer <= This->samples)
1116         {
1117             /* Re-scale the buffer back to normal */
1118             buffer += oldest;
1119
1120             /* Uh oh, we overshot the flusher handle, renormalize it back to 0..Samples-1 */
1121             if (buffer > This->samples)
1122                 buffer -= This->samples + 1;
1123             assert(buffer <= This->samples);
1124         }
1125
1126         if (buffer >= This->samples)
1127         {
1128             if (buffer != This->samples)
1129             {
1130                 FIXME("Returned: %u (%08x)\n", buffer, GetLastError());
1131                 hr = VFW_E_TIMEOUT;
1132             }
1133             else
1134                 hr = VFW_E_WRONG_STATE;
1135             buffer = ~0;
1136         }
1137         else
1138             --This->queued_number;
1139     }
1140
1141     if (This->bFlushing && buffer == ~0)
1142     {
1143         for (buffer = 0; buffer < This->samples; ++buffer)
1144         {
1145             if (This->sample_list[buffer].pSample)
1146             {
1147                 ResetEvent(This->handle_list[buffer]);
1148                 break;
1149             }
1150         }
1151         if (buffer == This->samples)
1152         {
1153             assert(!This->queued_number);
1154             hr = VFW_E_TIMEOUT;
1155         }
1156         else
1157         {
1158             --This->queued_number;
1159             hr = S_OK;
1160         }
1161     }
1162
1163     if (SUCCEEDED(hr))
1164     {
1165         REFERENCE_TIME rtStart, rtStop;
1166         REFERENCE_TIME rtSampleStart, rtSampleStop;
1167         DATAREQUEST *pDataRq = This->sample_list + buffer;
1168         DWORD dwBytes = 0;
1169
1170         /* get any errors */
1171         if (!This->bFlushing && !GetOverlappedResult(This->hFile, &pDataRq->ovl, &dwBytes, FALSE))
1172             hr = HRESULT_FROM_WIN32(GetLastError());
1173
1174         /* Return the sample no matter what so it can be destroyed */
1175         *ppSample = pDataRq->pSample;
1176         *pdwUser = pDataRq->dwUserData;
1177
1178         if (This->bFlushing)
1179             hr = VFW_E_WRONG_STATE;
1180
1181         if (FAILED(hr))
1182             dwBytes = 0;
1183
1184         /* Set the time on the sample */
1185         IMediaSample_SetActualDataLength(pDataRq->pSample, dwBytes);
1186
1187         rtStart = (DWORD64)pDataRq->ovl.u.s.Offset + ((DWORD64)pDataRq->ovl.u.s.OffsetHigh << 32);
1188         rtStart = MEDIATIME_FROM_BYTES(rtStart);
1189         rtStop = rtStart + MEDIATIME_FROM_BYTES(dwBytes);
1190
1191         IMediaSample_GetTime(pDataRq->pSample, &rtSampleStart, &rtSampleStop);
1192         assert(rtStart == rtSampleStart);
1193         assert(rtStop <= rtSampleStop);
1194
1195         IMediaSample_SetTime(pDataRq->pSample, &rtStart, &rtStop);
1196         assert(rtStart == rtSampleStart);
1197         if (hr == S_OK)
1198             assert(rtStop == rtSampleStop);
1199         else
1200             assert(rtStop == rtStart);
1201
1202         This->sample_list[buffer].pSample = NULL;
1203         assert(This->oldest_sample < This->samples);
1204
1205         if (buffer == This->oldest_sample)
1206         {
1207             LONG x;
1208             for (x = This->oldest_sample + 1; x < This->samples; ++x)
1209                 if (This->sample_list[x].pSample)
1210                     break;
1211             if (x >= This->samples)
1212                 for (x = 0; x < This->oldest_sample; ++x)
1213                     if (This->sample_list[x].pSample)
1214                         break;
1215             if (This->oldest_sample == x)
1216                 /* No samples found, reset to 0 */
1217                 x = 0;
1218             This->oldest_sample = x;
1219         }
1220     }
1221     LeaveCriticalSection(&This->csList);
1222
1223     TRACE("-- %x\n", hr);
1224     return hr;
1225 }
1226
1227 static HRESULT WINAPI FileAsyncReader_SyncRead(IAsyncReader * iface, LONGLONG llPosition, LONG lLength, BYTE * pBuffer);
1228
1229 static HRESULT WINAPI FileAsyncReader_SyncReadAligned(IAsyncReader * iface, IMediaSample * pSample)
1230 {
1231     BYTE * pBuffer;
1232     REFERENCE_TIME tStart;
1233     REFERENCE_TIME tStop;
1234     HRESULT hr;
1235
1236     TRACE("(%p)\n", pSample);
1237
1238     hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
1239
1240     if (SUCCEEDED(hr))
1241         hr = IMediaSample_GetPointer(pSample, &pBuffer);
1242
1243     if (SUCCEEDED(hr))
1244         hr = FileAsyncReader_SyncRead(iface, 
1245             BYTES_FROM_MEDIATIME(tStart),
1246             (LONG) BYTES_FROM_MEDIATIME(tStop - tStart),
1247             pBuffer);
1248
1249     TRACE("-- %x\n", hr);
1250     return hr;
1251 }
1252
1253 static HRESULT WINAPI FileAsyncReader_SyncRead(IAsyncReader * iface, LONGLONG llPosition, LONG lLength, BYTE * pBuffer)
1254 {
1255     OVERLAPPED ovl;
1256     HRESULT hr = S_OK;
1257     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1258
1259     TRACE("(%x%08x, %d, %p)\n", (ULONG)(llPosition >> 32), (ULONG)llPosition, lLength, pBuffer);
1260
1261     ZeroMemory(&ovl, sizeof(ovl));
1262
1263     ovl.hEvent = CreateEventW(NULL, 0, 0, NULL);
1264     /* NOTE: llPosition is the actual byte position to start reading from */
1265     ovl.u.s.Offset = (DWORD) llPosition;
1266     ovl.u.s.OffsetHigh = (DWORD) (llPosition >> (sizeof(DWORD) * 8));
1267
1268     if (!ReadFile(This->hFile, pBuffer, lLength, NULL, &ovl))
1269         hr = HRESULT_FROM_WIN32(GetLastError());
1270
1271     if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING))
1272         hr = S_OK;
1273
1274     if (SUCCEEDED(hr))
1275     {
1276         DWORD dwBytesRead;
1277
1278         if (!GetOverlappedResult(This->hFile, &ovl, &dwBytesRead, TRUE))
1279             hr = HRESULT_FROM_WIN32(GetLastError());
1280     }
1281
1282     CloseHandle(ovl.hEvent);
1283
1284     TRACE("-- %x\n", hr);
1285     return hr;
1286 }
1287
1288 static HRESULT WINAPI FileAsyncReader_Length(IAsyncReader * iface, LONGLONG * pTotal, LONGLONG * pAvailable)
1289 {
1290     DWORD dwSizeLow;
1291     DWORD dwSizeHigh;
1292     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1293
1294     TRACE("(%p, %p)\n", pTotal, pAvailable);
1295
1296     if (((dwSizeLow = GetFileSize(This->hFile, &dwSizeHigh)) == -1) &&
1297         (GetLastError() != NO_ERROR))
1298         return HRESULT_FROM_WIN32(GetLastError());
1299
1300     *pTotal = (LONGLONG)dwSizeLow | (LONGLONG)dwSizeHigh << (sizeof(DWORD) * 8);
1301
1302     *pAvailable = *pTotal;
1303
1304     return S_OK;
1305 }
1306
1307 static HRESULT WINAPI FileAsyncReader_BeginFlush(IAsyncReader * iface)
1308 {
1309     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1310
1311     TRACE("()\n");
1312
1313     EnterCriticalSection(&This->csList);
1314     This->bFlushing = TRUE;
1315     CancelIo(This->hFile);
1316     SetEvent(This->handle_list[This->samples]);
1317     LeaveCriticalSection(&This->csList);
1318
1319     return S_OK;
1320 }
1321
1322 static HRESULT WINAPI FileAsyncReader_EndFlush(IAsyncReader * iface)
1323 {
1324     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1325     int x;
1326
1327     TRACE("()\n");
1328
1329     EnterCriticalSection(&This->csList);
1330     ResetEvent(This->handle_list[This->samples]);
1331     This->bFlushing = FALSE;
1332     for (x = 0; x < This->samples; ++x)
1333         assert(!This->sample_list[x].pSample);
1334
1335     LeaveCriticalSection(&This->csList);
1336
1337     return S_OK;
1338 }
1339
1340 static const IAsyncReaderVtbl FileAsyncReader_Vtbl = 
1341 {
1342     FileAsyncReader_QueryInterface,
1343     FileAsyncReader_AddRef,
1344     FileAsyncReader_Release,
1345     FileAsyncReader_RequestAllocator,
1346     FileAsyncReader_Request,
1347     FileAsyncReader_WaitForNext,
1348     FileAsyncReader_SyncReadAligned,
1349     FileAsyncReader_SyncRead,
1350     FileAsyncReader_Length,
1351     FileAsyncReader_BeginFlush,
1352     FileAsyncReader_EndFlush,
1353 };
1354
1355
1356 static AsyncReader *from_IAMFilterMiscFlags(IAMFilterMiscFlags *iface) {
1357     return (AsyncReader*)((char*)iface - offsetof(AsyncReader, IAMFilterMiscFlags_vtbl));
1358 }
1359
1360 static HRESULT WINAPI AMFilterMiscFlags_QueryInterface(IAMFilterMiscFlags *iface, REFIID riid, void **ppv) {
1361     AsyncReader *This = from_IAMFilterMiscFlags(iface);
1362     return IUnknown_QueryInterface((IUnknown*)This, riid, ppv);
1363 }
1364
1365 static ULONG WINAPI AMFilterMiscFlags_AddRef(IAMFilterMiscFlags *iface) {
1366     AsyncReader *This = from_IAMFilterMiscFlags(iface);
1367     return IUnknown_AddRef((IUnknown*)This);
1368 }
1369
1370 static ULONG WINAPI AMFilterMiscFlags_Release(IAMFilterMiscFlags *iface) {
1371     AsyncReader *This = from_IAMFilterMiscFlags(iface);
1372     return IUnknown_Release((IUnknown*)This);
1373 }
1374
1375 static ULONG WINAPI AMFilterMiscFlags_GetMiscFlags(IAMFilterMiscFlags *iface) {
1376     return AM_FILTER_MISC_FLAGS_IS_SOURCE;
1377 }
1378
1379 static const IAMFilterMiscFlagsVtbl IAMFilterMiscFlags_Vtbl = {
1380     AMFilterMiscFlags_QueryInterface,
1381     AMFilterMiscFlags_AddRef,
1382     AMFilterMiscFlags_Release,
1383     AMFilterMiscFlags_GetMiscFlags
1384 };