mshtml: Added more IHTMLStyle implementation.
[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     pAsyncRead->csFilter.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": AsyncReader.csFilter");
318
319     pAsyncRead->pszFileName = NULL;
320     pAsyncRead->pmt = NULL;
321
322     *ppv = (LPVOID)pAsyncRead;
323
324     TRACE("-- created at %p\n", pAsyncRead);
325
326     return S_OK;
327 }
328
329 /** IUnknown methods **/
330
331 static HRESULT WINAPI AsyncReader_QueryInterface(IBaseFilter * iface, REFIID riid, LPVOID * ppv)
332 {
333     AsyncReader *This = (AsyncReader *)iface;
334
335     TRACE("(%s, %p)\n", qzdebugstr_guid(riid), ppv);
336
337     *ppv = NULL;
338
339     if (IsEqualIID(riid, &IID_IUnknown))
340         *ppv = (LPVOID)This;
341     else if (IsEqualIID(riid, &IID_IPersist))
342         *ppv = (LPVOID)This;
343     else if (IsEqualIID(riid, &IID_IMediaFilter))
344         *ppv = (LPVOID)This;
345     else if (IsEqualIID(riid, &IID_IBaseFilter))
346         *ppv = (LPVOID)This;
347     else if (IsEqualIID(riid, &IID_IFileSourceFilter))
348         *ppv = (LPVOID)(&This->lpVtblFSF);
349
350     if (*ppv)
351     {
352         IUnknown_AddRef((IUnknown *)(*ppv));
353         return S_OK;
354     }
355
356     FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
357
358     return E_NOINTERFACE;
359 }
360
361 static ULONG WINAPI AsyncReader_AddRef(IBaseFilter * iface)
362 {
363     AsyncReader *This = (AsyncReader *)iface;
364     ULONG refCount = InterlockedIncrement(&This->refCount);
365     
366     TRACE("(%p)->() AddRef from %d\n", This, refCount - 1);
367     
368     return refCount;
369 }
370
371 static ULONG WINAPI AsyncReader_Release(IBaseFilter * iface)
372 {
373     AsyncReader *This = (AsyncReader *)iface;
374     ULONG refCount = InterlockedDecrement(&This->refCount);
375     
376     TRACE("(%p)->() Release from %d\n", This, refCount + 1);
377     
378     if (!refCount)
379     {
380         if (This->pOutputPin)
381         {
382             IPin *pConnectedTo;
383             if(SUCCEEDED(IPin_ConnectedTo(This->pOutputPin, &pConnectedTo)))
384             {
385                 IPin_Disconnect(pConnectedTo);
386                 IPin_Release(pConnectedTo);
387             }
388             IPin_Disconnect(This->pOutputPin);
389             IPin_Release(This->pOutputPin);
390         }
391         This->csFilter.DebugInfo->Spare[0] = 0;
392         DeleteCriticalSection(&This->csFilter);
393         This->lpVtbl = NULL;
394         CoTaskMemFree(This);
395         return 0;
396     }
397     else
398         return refCount;
399 }
400
401 /** IPersist methods **/
402
403 static HRESULT WINAPI AsyncReader_GetClassID(IBaseFilter * iface, CLSID * pClsid)
404 {
405     TRACE("(%p)\n", pClsid);
406
407     *pClsid = CLSID_AsyncReader;
408
409     return S_OK;
410 }
411
412 /** IMediaFilter methods **/
413
414 static HRESULT WINAPI AsyncReader_Stop(IBaseFilter * iface)
415 {
416     AsyncReader *This = (AsyncReader *)iface;
417
418     TRACE("()\n");
419
420     This->state = State_Stopped;
421     
422     return S_OK;
423 }
424
425 static HRESULT WINAPI AsyncReader_Pause(IBaseFilter * iface)
426 {
427     AsyncReader *This = (AsyncReader *)iface;
428
429     TRACE("()\n");
430
431     This->state = State_Paused;
432
433     return S_OK;
434 }
435
436 static HRESULT WINAPI AsyncReader_Run(IBaseFilter * iface, REFERENCE_TIME tStart)
437 {
438     AsyncReader *This = (AsyncReader *)iface;
439
440     TRACE("(%x%08x)\n", (ULONG)(tStart >> 32), (ULONG)tStart);
441
442     This->state = State_Running;
443
444     return S_OK;
445 }
446
447 static HRESULT WINAPI AsyncReader_GetState(IBaseFilter * iface, DWORD dwMilliSecsTimeout, FILTER_STATE *pState)
448 {
449     AsyncReader *This = (AsyncReader *)iface;
450
451     TRACE("(%u, %p)\n", dwMilliSecsTimeout, pState);
452
453     *pState = This->state;
454     
455     return S_OK;
456 }
457
458 static HRESULT WINAPI AsyncReader_SetSyncSource(IBaseFilter * iface, IReferenceClock *pClock)
459 {
460 /*    AsyncReader *This = (AsyncReader *)iface;*/
461
462     TRACE("(%p)\n", pClock);
463
464     return S_OK;
465 }
466
467 static HRESULT WINAPI AsyncReader_GetSyncSource(IBaseFilter * iface, IReferenceClock **ppClock)
468 {
469 /*    AsyncReader *This = (AsyncReader *)iface;*/
470
471     TRACE("(%p)\n", ppClock);
472
473     return S_OK;
474 }
475
476 /** IBaseFilter methods **/
477
478 static HRESULT WINAPI AsyncReader_EnumPins(IBaseFilter * iface, IEnumPins **ppEnum)
479 {
480     ENUMPINDETAILS epd;
481     AsyncReader *This = (AsyncReader *)iface;
482
483     TRACE("(%p)\n", ppEnum);
484
485     epd.cPins = This->pOutputPin ? 1 : 0;
486     epd.ppPins = &This->pOutputPin;
487     return IEnumPinsImpl_Construct(&epd, ppEnum);
488 }
489
490 static HRESULT WINAPI AsyncReader_FindPin(IBaseFilter * iface, LPCWSTR Id, IPin **ppPin)
491 {
492     FIXME("(%s, %p)\n", debugstr_w(Id), ppPin);
493
494     return E_NOTIMPL;
495 }
496
497 static HRESULT WINAPI AsyncReader_QueryFilterInfo(IBaseFilter * iface, FILTER_INFO *pInfo)
498 {
499     AsyncReader *This = (AsyncReader *)iface;
500
501     TRACE("(%p)\n", pInfo);
502
503     strcpyW(pInfo->achName, This->filterInfo.achName);
504     pInfo->pGraph = This->filterInfo.pGraph;
505
506     if (pInfo->pGraph)
507         IFilterGraph_AddRef(pInfo->pGraph);
508     
509     return S_OK;
510 }
511
512 static HRESULT WINAPI AsyncReader_JoinFilterGraph(IBaseFilter * iface, IFilterGraph *pGraph, LPCWSTR pName)
513 {
514     AsyncReader *This = (AsyncReader *)iface;
515
516     TRACE("(%p, %s)\n", pGraph, debugstr_w(pName));
517
518     if (pName)
519         strcpyW(This->filterInfo.achName, pName);
520     else
521         *This->filterInfo.achName = 0;
522     This->filterInfo.pGraph = pGraph; /* NOTE: do NOT increase ref. count */
523
524     return S_OK;
525 }
526
527 static HRESULT WINAPI AsyncReader_QueryVendorInfo(IBaseFilter * iface, LPWSTR *pVendorInfo)
528 {
529     FIXME("(%p)\n", pVendorInfo);
530
531     return E_NOTIMPL;
532 }
533
534 static const IBaseFilterVtbl AsyncReader_Vtbl =
535 {
536     AsyncReader_QueryInterface,
537     AsyncReader_AddRef,
538     AsyncReader_Release,
539     AsyncReader_GetClassID,
540     AsyncReader_Stop,
541     AsyncReader_Pause,
542     AsyncReader_Run,
543     AsyncReader_GetState,
544     AsyncReader_SetSyncSource,
545     AsyncReader_GetSyncSource,
546     AsyncReader_EnumPins,
547     AsyncReader_FindPin,
548     AsyncReader_QueryFilterInfo,
549     AsyncReader_JoinFilterGraph,
550     AsyncReader_QueryVendorInfo
551 };
552
553 static HRESULT WINAPI FileSource_QueryInterface(IFileSourceFilter * iface, REFIID riid, LPVOID * ppv)
554 {
555     AsyncReader *This = impl_from_IFileSourceFilter(iface);
556
557     return IBaseFilter_QueryInterface((IFileSourceFilter*)&This->lpVtbl, riid, ppv);
558 }
559
560 static ULONG WINAPI FileSource_AddRef(IFileSourceFilter * iface)
561 {
562     AsyncReader *This = impl_from_IFileSourceFilter(iface);
563
564     return IBaseFilter_AddRef((IFileSourceFilter*)&This->lpVtbl);
565 }
566
567 static ULONG WINAPI FileSource_Release(IFileSourceFilter * iface)
568 {
569     AsyncReader *This = impl_from_IFileSourceFilter(iface);
570
571     return IBaseFilter_Release((IFileSourceFilter*)&This->lpVtbl);
572 }
573
574 static HRESULT WINAPI FileSource_Load(IFileSourceFilter * iface, LPCOLESTR pszFileName, const AM_MEDIA_TYPE * pmt)
575 {
576     HRESULT hr;
577     HANDLE hFile;
578     IAsyncReader * pReader = NULL;
579     AsyncReader *This = impl_from_IFileSourceFilter(iface);
580
581     TRACE("(%s, %p)\n", debugstr_w(pszFileName), pmt);
582
583     /* open file */
584     /* FIXME: check the sharing values that native uses */
585     hFile = CreateFileW(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
586
587     if (hFile == INVALID_HANDLE_VALUE)
588     {
589         return HRESULT_FROM_WIN32(GetLastError());
590     }
591
592     /* create pin */
593     hr = FileAsyncReader_Construct(hFile, (IBaseFilter *)&This->lpVtbl, &This->csFilter, &This->pOutputPin);
594
595     if (SUCCEEDED(hr))
596         hr = IPin_QueryInterface(This->pOutputPin, &IID_IAsyncReader, (LPVOID *)&pReader);
597
598     /* store file name & media type */
599     if (SUCCEEDED(hr))
600     {
601         This->pszFileName = CoTaskMemAlloc((strlenW(pszFileName) + 1) * sizeof(WCHAR));
602         strcpyW(This->pszFileName, pszFileName);
603         This->pmt = CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
604         if (!pmt)
605         {
606             This->pmt->bFixedSizeSamples = TRUE;
607             This->pmt->bTemporalCompression = FALSE;
608             This->pmt->cbFormat = 0;
609             This->pmt->pbFormat = NULL;
610             This->pmt->pUnk = NULL;
611             This->pmt->lSampleSize = 0;
612             memcpy(&This->pmt->formattype, &FORMAT_None, sizeof(FORMAT_None));
613             hr = GetClassMediaFile(pReader, pszFileName, &This->pmt->majortype, &This->pmt->subtype);
614             if (FAILED(hr))
615             {
616                 CoTaskMemFree(This->pmt);
617                 This->pmt = NULL;
618             }
619         }
620         else
621             CopyMediaType(This->pmt, pmt);
622     }
623
624     if (pReader)
625         IAsyncReader_Release(pReader);
626
627     if (FAILED(hr))
628     {
629         if (This->pOutputPin)
630         {
631             IPin_Release(This->pOutputPin);
632             This->pOutputPin = NULL;
633         }
634
635         CoTaskMemFree(This->pszFileName);
636         This->pszFileName = NULL;
637
638         CloseHandle(hFile);
639     }
640
641     /* FIXME: check return codes */
642     return hr;
643 }
644
645 static HRESULT WINAPI FileSource_GetCurFile(IFileSourceFilter * iface, LPOLESTR * ppszFileName, AM_MEDIA_TYPE * pmt)
646 {
647     AsyncReader *This = impl_from_IFileSourceFilter(iface);
648     
649     TRACE("(%p, %p)\n", ppszFileName, pmt);
650
651     if (!ppszFileName)
652         return E_POINTER;
653
654     /* copy file name & media type if available, otherwise clear the outputs */
655     if (This->pszFileName)
656     {
657         *ppszFileName = CoTaskMemAlloc((strlenW(This->pszFileName) + 1) * sizeof(WCHAR));
658         strcpyW(*ppszFileName, This->pszFileName);
659     }
660     else
661         *ppszFileName = NULL;
662
663     if (pmt)
664     {
665         if (This->pmt)
666             CopyMediaType(pmt, This->pmt);
667         else
668             ZeroMemory(pmt, sizeof(*pmt));
669     }
670
671     return S_OK;
672 }
673
674 static const IFileSourceFilterVtbl FileSource_Vtbl = 
675 {
676     FileSource_QueryInterface,
677     FileSource_AddRef,
678     FileSource_Release,
679     FileSource_Load,
680     FileSource_GetCurFile
681 };
682
683
684 /* the dwUserData passed back to user */
685 typedef struct DATAREQUEST
686 {
687     IMediaSample * pSample; /* sample passed to us by user */
688     DWORD_PTR dwUserData; /* user data passed to us */
689     OVERLAPPED ovl; /* our overlapped structure */
690
691     struct DATAREQUEST * pNext; /* next data request in list */
692 } DATAREQUEST;
693
694 static void queue(DATAREQUEST * pHead, DATAREQUEST * pItem)
695 {
696     DATAREQUEST * pCurrent;
697     for (pCurrent = pHead; pCurrent->pNext; pCurrent = pCurrent->pNext)
698         ;
699     pCurrent->pNext = pItem;
700 }
701
702 typedef struct FileAsyncReader
703 {
704     OutputPin pin;
705     const struct IAsyncReaderVtbl * lpVtblAR;
706
707     HANDLE hFile;
708     HANDLE hEvent;
709     BOOL bFlushing;
710     DATAREQUEST * pHead; /* head of data request list */
711     CRITICAL_SECTION csList; /* critical section to protect operations on list */
712 } FileAsyncReader;
713
714 static inline FileAsyncReader *impl_from_IAsyncReader( IAsyncReader *iface )
715 {
716     return (FileAsyncReader *)((char*)iface - FIELD_OFFSET(FileAsyncReader, lpVtblAR));
717 }
718
719 static HRESULT AcceptProcAFR(LPVOID iface, const AM_MEDIA_TYPE *pmt)
720 {
721     AsyncReader *This = (AsyncReader *)iface;
722     
723     FIXME("(%p, %p)\n", iface, pmt);
724
725     if (IsEqualGUID(&pmt->majortype, &This->pmt->majortype) &&
726         IsEqualGUID(&pmt->subtype, &This->pmt->subtype) &&
727         IsEqualGUID(&pmt->formattype, &FORMAT_None))
728         return S_OK;
729     
730     return S_FALSE;
731 }
732
733 /* overriden pin functions */
734
735 static HRESULT WINAPI FileAsyncReaderPin_QueryInterface(IPin * iface, REFIID riid, LPVOID * ppv)
736 {
737     FileAsyncReader *This = (FileAsyncReader *)iface;
738     TRACE("(%s, %p)\n", qzdebugstr_guid(riid), ppv);
739
740     *ppv = NULL;
741
742     if (IsEqualIID(riid, &IID_IUnknown))
743         *ppv = (LPVOID)This;
744     else if (IsEqualIID(riid, &IID_IPin))
745         *ppv = (LPVOID)This;
746     else if (IsEqualIID(riid, &IID_IAsyncReader))
747         *ppv = (LPVOID)&This->lpVtblAR;
748
749     if (*ppv)
750     {
751         IUnknown_AddRef((IUnknown *)(*ppv));
752         return S_OK;
753     }
754
755     FIXME("No interface for %s!\n", qzdebugstr_guid(riid));
756
757     return E_NOINTERFACE;
758 }
759
760 static ULONG WINAPI FileAsyncReaderPin_Release(IPin * iface)
761 {
762     FileAsyncReader *This = (FileAsyncReader *)iface;
763     ULONG refCount = InterlockedDecrement(&This->pin.pin.refCount);
764     
765     TRACE("(%p)->() Release from %d\n", This, refCount + 1);
766     
767     if (!refCount)
768     {
769         DATAREQUEST * pCurrent;
770         DATAREQUEST * pNext;
771         for (pCurrent = This->pHead; pCurrent; pCurrent = pNext)
772         {
773             pNext = pCurrent->pNext;
774             CoTaskMemFree(pCurrent);
775         }
776         CloseHandle(This->hFile);
777         CloseHandle(This->hEvent);
778         This->csList.DebugInfo->Spare[0] = 0;
779         DeleteCriticalSection(&This->csList);
780         CoTaskMemFree(This);
781         return 0;
782     }
783     return refCount;
784 }
785
786 static HRESULT WINAPI FileAsyncReaderPin_EnumMediaTypes(IPin * iface, IEnumMediaTypes ** ppEnum)
787 {
788     ENUMMEDIADETAILS emd;
789     FileAsyncReader *This = (FileAsyncReader *)iface;
790
791     TRACE("(%p)\n", ppEnum);
792
793     emd.cMediaTypes = 1;
794     emd.pMediaTypes = ((AsyncReader *)This->pin.pin.pinInfo.pFilter)->pmt;
795
796     return IEnumMediaTypesImpl_Construct(&emd, ppEnum);
797 }
798
799 static const IPinVtbl FileAsyncReaderPin_Vtbl = 
800 {
801     FileAsyncReaderPin_QueryInterface,
802     IPinImpl_AddRef,
803     FileAsyncReaderPin_Release,
804     OutputPin_Connect,
805     OutputPin_ReceiveConnection,
806     IPinImpl_Disconnect,
807     IPinImpl_ConnectedTo,
808     IPinImpl_ConnectionMediaType,
809     IPinImpl_QueryPinInfo,
810     IPinImpl_QueryDirection,
811     IPinImpl_QueryId,
812     IPinImpl_QueryAccept,
813     FileAsyncReaderPin_EnumMediaTypes,
814     IPinImpl_QueryInternalConnections,
815     OutputPin_EndOfStream,
816     OutputPin_BeginFlush,
817     OutputPin_EndFlush,
818     OutputPin_NewSegment
819 };
820
821 /* Function called as a helper to IPin_Connect */
822 /* specific AM_MEDIA_TYPE - it cannot be NULL */
823 /* this differs from standard OutputPin_ConnectSpecific only in that it
824  * doesn't need the IMemInputPin interface on the receiving pin */
825 static HRESULT FileAsyncReaderPin_ConnectSpecific(IPin * iface, IPin * pReceivePin, const AM_MEDIA_TYPE * pmt)
826 {
827     OutputPin *This = (OutputPin *)iface;
828     HRESULT hr;
829
830     TRACE("(%p, %p)\n", pReceivePin, pmt);
831     dump_AM_MEDIA_TYPE(pmt);
832
833     /* FIXME: call queryacceptproc */
834
835     This->pin.pConnectedTo = pReceivePin;
836     IPin_AddRef(pReceivePin);
837     CopyMediaType(&This->pin.mtCurrent, pmt);
838
839     hr = IPin_ReceiveConnection(pReceivePin, iface, pmt);
840
841     if (FAILED(hr))
842     {
843         IPin_Release(This->pin.pConnectedTo);
844         This->pin.pConnectedTo = NULL;
845         FreeMediaType(&This->pin.mtCurrent);
846     }
847
848     TRACE(" -- %x\n", hr);
849     return hr;
850 }
851
852 static HRESULT FileAsyncReader_Construct(HANDLE hFile, IBaseFilter * pBaseFilter, LPCRITICAL_SECTION pCritSec, IPin ** ppPin)
853 {
854     FileAsyncReader * pPinImpl;
855     PIN_INFO piOutput;
856
857     *ppPin = NULL;
858
859     pPinImpl = CoTaskMemAlloc(sizeof(*pPinImpl));
860
861     if (!pPinImpl)
862         return E_OUTOFMEMORY;
863
864     piOutput.dir = PINDIR_OUTPUT;
865     piOutput.pFilter = pBaseFilter;
866     strcpyW(piOutput.achName, wszOutputPinName);
867
868     if (SUCCEEDED(OutputPin_Init(&piOutput, NULL, pBaseFilter, AcceptProcAFR, pCritSec, &pPinImpl->pin)))
869     {
870         pPinImpl->pin.pin.lpVtbl = &FileAsyncReaderPin_Vtbl;
871         pPinImpl->lpVtblAR = &FileAsyncReader_Vtbl;
872         pPinImpl->hFile = hFile;
873         pPinImpl->hEvent = CreateEventW(NULL, 0, 0, NULL);
874         pPinImpl->bFlushing = FALSE;
875         pPinImpl->pHead = NULL;
876         pPinImpl->pin.pConnectSpecific = FileAsyncReaderPin_ConnectSpecific;
877         InitializeCriticalSection(&pPinImpl->csList);
878         pPinImpl->csList.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FileAsyncReader.csList");
879
880         *ppPin = (IPin *)(&pPinImpl->pin.pin.lpVtbl);
881         return S_OK;
882     }
883
884     CoTaskMemFree(pPinImpl);
885     return E_FAIL;
886 }
887
888 /* IAsyncReader */
889
890 static HRESULT WINAPI FileAsyncReader_QueryInterface(IAsyncReader * iface, REFIID riid, LPVOID * ppv)
891 {
892     FileAsyncReader *This = impl_from_IAsyncReader(iface);
893
894     return IPin_QueryInterface((IPin *)This, riid, ppv);
895 }
896
897 static ULONG WINAPI FileAsyncReader_AddRef(IAsyncReader * iface)
898 {
899     FileAsyncReader *This = impl_from_IAsyncReader(iface);
900
901     return IPin_AddRef((IPin *)This);
902 }
903
904 static ULONG WINAPI FileAsyncReader_Release(IAsyncReader * iface)
905 {
906     FileAsyncReader *This = impl_from_IAsyncReader(iface);
907
908     return IPin_Release((IPin *)This);
909 }
910
911 #define DEF_ALIGNMENT 1
912
913 static HRESULT WINAPI FileAsyncReader_RequestAllocator(IAsyncReader * iface, IMemAllocator * pPreferred, ALLOCATOR_PROPERTIES * pProps, IMemAllocator ** ppActual)
914 {
915     HRESULT hr = S_OK;
916
917     TRACE("(%p, %p, %p)\n", pPreferred, pProps, ppActual);
918
919     if (!pProps->cbAlign || (pProps->cbAlign % DEF_ALIGNMENT) != 0)
920         pProps->cbAlign = DEF_ALIGNMENT;
921
922     if (pPreferred)
923     {
924         ALLOCATOR_PROPERTIES PropsActual;
925         hr = IMemAllocator_SetProperties(pPreferred, pProps, &PropsActual);
926         /* FIXME: check we are still aligned */
927         if (SUCCEEDED(hr))
928         {
929             IMemAllocator_AddRef(pPreferred);
930             *ppActual = pPreferred;
931             TRACE("FileAsyncReader_RequestAllocator -- %x\n", hr);
932             return S_OK;
933         }
934     }
935
936     pPreferred = NULL;
937
938     hr = CoCreateInstance(&CLSID_MemoryAllocator, NULL, CLSCTX_INPROC, &IID_IMemAllocator, (LPVOID *)&pPreferred);
939
940     if (SUCCEEDED(hr))
941     {
942         ALLOCATOR_PROPERTIES PropsActual;
943         hr = IMemAllocator_SetProperties(pPreferred, pProps, &PropsActual);
944         /* FIXME: check we are still aligned */
945         if (SUCCEEDED(hr))
946         {
947             *ppActual = pPreferred;
948             TRACE("FileAsyncReader_RequestAllocator -- %x\n", hr);
949             return S_OK;
950         }
951     }
952
953     if (FAILED(hr))
954     {
955         *ppActual = NULL;
956         if (pPreferred)
957             IMemAllocator_Release(pPreferred);
958     }
959
960     TRACE("-- %x\n", hr);
961     return hr;
962 }
963
964 /* we could improve the Request/WaitForNext mechanism by allowing out of order samples.
965  * however, this would be quite complicated to do and may be a bit error prone */
966 static HRESULT WINAPI FileAsyncReader_Request(IAsyncReader * iface, IMediaSample * pSample, DWORD_PTR dwUser)
967 {
968     REFERENCE_TIME Start;
969     REFERENCE_TIME Stop;
970     DATAREQUEST * pDataRq;
971     BYTE * pBuffer;
972     HRESULT hr = S_OK;
973     FileAsyncReader *This = impl_from_IAsyncReader(iface);
974
975     TRACE("(%p, %lx)\n", pSample, dwUser);
976
977     /* check flushing state */
978     if (This->bFlushing)
979         return VFW_E_WRONG_STATE;
980
981     if (!(pDataRq = CoTaskMemAlloc(sizeof(*pDataRq))))
982         hr = E_OUTOFMEMORY;
983
984     /* get start and stop positions in bytes */
985     if (SUCCEEDED(hr))
986         hr = IMediaSample_GetTime(pSample, &Start, &Stop);
987
988     if (SUCCEEDED(hr))
989         hr = IMediaSample_GetPointer(pSample, &pBuffer);
990
991     if (SUCCEEDED(hr))
992     {
993         DWORD dwLength = (DWORD) BYTES_FROM_MEDIATIME(Stop - Start);
994
995         pDataRq->ovl.u.s.Offset = (DWORD) BYTES_FROM_MEDIATIME(Start);
996         pDataRq->ovl.u.s.OffsetHigh = (DWORD)(BYTES_FROM_MEDIATIME(Start) >> (sizeof(DWORD) * 8));
997         pDataRq->ovl.hEvent = This->hEvent;
998         pDataRq->dwUserData = dwUser;
999         pDataRq->pNext = NULL;
1000         /* we violate traditional COM rules here by maintaining
1001          * a reference to the sample, but not calling AddRef, but
1002          * that's what MSDN says to do */
1003         pDataRq->pSample = pSample;
1004
1005         EnterCriticalSection(&This->csList);
1006         {
1007             if (This->pHead)
1008                 /* adds data request to end of list */
1009                 queue(This->pHead, pDataRq);
1010             else
1011                 This->pHead = pDataRq;
1012         }
1013         LeaveCriticalSection(&This->csList);
1014
1015         /* this is definitely not how it is implemented on Win9x
1016          * as they do not support async reads on files, but it is
1017          * sooo much easier to use this than messing around with threads!
1018          */
1019         if (!ReadFile(This->hFile, pBuffer, dwLength, NULL, &pDataRq->ovl))
1020             hr = HRESULT_FROM_WIN32(GetLastError());
1021
1022         /* ERROR_IO_PENDING is not actually an error since this is what we want! */
1023         if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING))
1024             hr = S_OK;
1025     }
1026
1027     if (FAILED(hr) && pDataRq)
1028     {
1029         EnterCriticalSection(&This->csList);
1030         {
1031             DATAREQUEST * pCurrent;
1032             for (pCurrent = This->pHead; pCurrent && pCurrent->pNext; pCurrent = pCurrent->pNext)
1033                 if (pCurrent->pNext == pDataRq)
1034                 {
1035                     pCurrent->pNext = pDataRq->pNext;
1036                     break;
1037                 }
1038         }
1039         LeaveCriticalSection(&This->csList);
1040         CoTaskMemFree(pDataRq);
1041     }
1042
1043     TRACE("-- %x\n", hr);
1044     return hr;
1045 }
1046
1047 static HRESULT WINAPI FileAsyncReader_WaitForNext(IAsyncReader * iface, DWORD dwTimeout, IMediaSample ** ppSample, DWORD_PTR * pdwUser)
1048 {
1049     HRESULT hr = S_OK;
1050     DWORD dwBytes = 0;
1051     DATAREQUEST * pDataRq = NULL;
1052     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1053
1054     TRACE("(%u, %p, %p)\n", dwTimeout, ppSample, pdwUser);
1055
1056     /* FIXME: we could do with improving this by waiting for an array of event handles
1057      * and then determining which one finished and removing that from the list, otherwise
1058      * we will end up waiting for longer than we should do, if a later request finishes
1059      * before an earlier one */
1060
1061     *ppSample = NULL;
1062     *pdwUser = 0;
1063
1064     /* we return immediately if flushing */
1065     if (This->bFlushing)
1066         hr = VFW_E_WRONG_STATE;
1067
1068     if (SUCCEEDED(hr))
1069     {
1070         /* wait for the read to finish or timeout */
1071         if (WaitForSingleObject(This->hEvent, dwTimeout) == WAIT_TIMEOUT)
1072             hr = VFW_E_TIMEOUT;
1073     }
1074     if (SUCCEEDED(hr))
1075     {
1076         EnterCriticalSection(&This->csList);
1077         {
1078             pDataRq = This->pHead;
1079             if (pDataRq == NULL)
1080                 hr = E_FAIL;
1081             else
1082                 This->pHead = pDataRq->pNext;
1083         }
1084         LeaveCriticalSection(&This->csList);
1085     }
1086
1087     if (SUCCEEDED(hr))
1088     {
1089         /* get any errors */
1090         if (!GetOverlappedResult(This->hFile, &pDataRq->ovl, &dwBytes, FALSE))
1091             hr = HRESULT_FROM_WIN32(GetLastError());
1092     }
1093
1094     if (SUCCEEDED(hr))
1095     {
1096         IMediaSample_SetActualDataLength(pDataRq->pSample, dwBytes);
1097         *ppSample = pDataRq->pSample;
1098         *pdwUser = pDataRq->dwUserData;
1099     }
1100
1101     /* no need to close event handle since we will close it when the pin is destroyed */
1102     CoTaskMemFree(pDataRq);
1103     
1104     TRACE("-- %x\n", hr);
1105     return hr;
1106 }
1107
1108 static HRESULT WINAPI FileAsyncReader_SyncRead(IAsyncReader * iface, LONGLONG llPosition, LONG lLength, BYTE * pBuffer);
1109
1110 static HRESULT WINAPI FileAsyncReader_SyncReadAligned(IAsyncReader * iface, IMediaSample * pSample)
1111 {
1112     BYTE * pBuffer;
1113     REFERENCE_TIME tStart;
1114     REFERENCE_TIME tStop;
1115     HRESULT hr;
1116
1117     TRACE("(%p)\n", pSample);
1118
1119     hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
1120
1121     if (SUCCEEDED(hr))
1122         hr = IMediaSample_GetPointer(pSample, &pBuffer);
1123
1124     if (SUCCEEDED(hr))
1125         hr = FileAsyncReader_SyncRead(iface, 
1126             BYTES_FROM_MEDIATIME(tStart),
1127             (LONG) BYTES_FROM_MEDIATIME(tStop - tStart),
1128             pBuffer);
1129
1130     TRACE("-- %x\n", hr);
1131     return hr;
1132 }
1133
1134 static HRESULT WINAPI FileAsyncReader_SyncRead(IAsyncReader * iface, LONGLONG llPosition, LONG lLength, BYTE * pBuffer)
1135 {
1136     OVERLAPPED ovl;
1137     HRESULT hr = S_OK;
1138     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1139
1140     TRACE("(%x%08x, %d, %p)\n", (ULONG)(llPosition >> 32), (ULONG)llPosition, lLength, pBuffer);
1141
1142     ZeroMemory(&ovl, sizeof(ovl));
1143
1144     ovl.hEvent = CreateEventW(NULL, 0, 0, NULL);
1145     /* NOTE: llPosition is the actual byte position to start reading from */
1146     ovl.u.s.Offset = (DWORD) llPosition;
1147     ovl.u.s.OffsetHigh = (DWORD) (llPosition >> (sizeof(DWORD) * 8));
1148
1149     if (!ReadFile(This->hFile, pBuffer, lLength, NULL, &ovl))
1150         hr = HRESULT_FROM_WIN32(GetLastError());
1151
1152     if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING))
1153         hr = S_OK;
1154
1155     if (SUCCEEDED(hr))
1156     {
1157         DWORD dwBytesRead;
1158
1159         if (!GetOverlappedResult(This->hFile, &ovl, &dwBytesRead, TRUE))
1160             hr = HRESULT_FROM_WIN32(GetLastError());
1161     }
1162
1163     CloseHandle(ovl.hEvent);
1164
1165     TRACE("-- %x\n", hr);
1166     return hr;
1167 }
1168
1169 static HRESULT WINAPI FileAsyncReader_Length(IAsyncReader * iface, LONGLONG * pTotal, LONGLONG * pAvailable)
1170 {
1171     DWORD dwSizeLow;
1172     DWORD dwSizeHigh;
1173     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1174
1175     TRACE("(%p, %p)\n", pTotal, pAvailable);
1176
1177     if (((dwSizeLow = GetFileSize(This->hFile, &dwSizeHigh)) == -1) &&
1178         (GetLastError() != NO_ERROR))
1179         return HRESULT_FROM_WIN32(GetLastError());
1180
1181     *pTotal = (LONGLONG)dwSizeLow | (LONGLONG)dwSizeHigh << (sizeof(DWORD) * 8);
1182
1183     *pAvailable = *pTotal;
1184
1185     return S_OK;
1186 }
1187
1188 static HRESULT WINAPI FileAsyncReader_BeginFlush(IAsyncReader * iface)
1189 {
1190     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1191
1192     TRACE("()\n");
1193
1194     This->bFlushing = TRUE;
1195     CancelIo(This->hFile);
1196     SetEvent(This->hEvent);
1197     
1198     /* FIXME: free list */
1199
1200     return S_OK;
1201 }
1202
1203 static HRESULT WINAPI FileAsyncReader_EndFlush(IAsyncReader * iface)
1204 {
1205     FileAsyncReader *This = impl_from_IAsyncReader(iface);
1206
1207     TRACE("()\n");
1208
1209     This->bFlushing = FALSE;
1210
1211     return S_OK;
1212 }
1213
1214 static const IAsyncReaderVtbl FileAsyncReader_Vtbl = 
1215 {
1216     FileAsyncReader_QueryInterface,
1217     FileAsyncReader_AddRef,
1218     FileAsyncReader_Release,
1219     FileAsyncReader_RequestAllocator,
1220     FileAsyncReader_Request,
1221     FileAsyncReader_WaitForNext,
1222     FileAsyncReader_SyncReadAligned,
1223     FileAsyncReader_SyncRead,
1224     FileAsyncReader_Length,
1225     FileAsyncReader_BeginFlush,
1226     FileAsyncReader_EndFlush,
1227 };