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