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