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