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