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