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