Debian Codegraph @

sys/directshow/strmbase/baseclasses/wxutil.cpp

raw
1 //------------------------------------------------------------------------------
2 // File: WXUtil.cpp
3 //
4 // Desc: DirectShow base classes - implements helper classes for building
5 // multimedia filters.
6 //
7 // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved.
8 //------------------------------------------------------------------------------
9
10
11 #include <streams.h>
12 #define STRSAFE_NO_DEPRECATE
13 #include <strsafe.h>
14
15
16 // --- CAMEvent -----------------------
17 CAMEvent::CAMEvent(BOOL fManualReset, __inout_opt HRESULT *phr)
18 {
19 m_hEvent = CreateEvent(NULL, fManualReset, FALSE, NULL);
20 if (NULL == m_hEvent) {
21 if (NULL != phr && SUCCEEDED(*phr)) {
22 *phr = E_OUTOFMEMORY;
23 }
24 }
25 }
26
27 CAMEvent::CAMEvent(__inout_opt HRESULT *phr)
28 {
29 m_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
30 if (NULL == m_hEvent) {
31 if (NULL != phr && SUCCEEDED(*phr)) {
32 *phr = E_OUTOFMEMORY;
33 }
34 }
35 }
36
37 CAMEvent::~CAMEvent()
38 {
39 if (m_hEvent) {
40 EXECUTE_ASSERT(CloseHandle(m_hEvent));
41 }
42 }
43
44
45 // --- CAMMsgEvent -----------------------
46 // One routine. The rest is handled in CAMEvent
47
48 CAMMsgEvent::CAMMsgEvent(__inout_opt HRESULT *phr) : CAMEvent(FALSE, phr)
49 {
50 }
51
52 BOOL CAMMsgEvent::WaitMsg(DWORD dwTimeout)
53 {
54 // wait for the event to be signalled, or for the
55 // timeout (in MS) to expire. allow SENT messages
56 // to be processed while we wait
57 DWORD dwWait;
58 DWORD dwStartTime;
59
60 // set the waiting period.
61 DWORD dwWaitTime = dwTimeout;
62
63 // the timeout will eventually run down as we iterate
64 // processing messages. grab the start time so that
65 // we can calculate elapsed times.
66 if (dwWaitTime != INFINITE) {
67 dwStartTime = timeGetTime();
68 }
69
70 do {
71 dwWait = MsgWaitForMultipleObjects(1,&m_hEvent,FALSE, dwWaitTime, QS_SENDMESSAGE);
72 if (dwWait == WAIT_OBJECT_0 + 1) {
73 MSG Message;
74 PeekMessage(&Message,NULL,0,0,PM_NOREMOVE);
75
76 // If we have an explicit length of time to wait calculate
77 // the next wake up point - which might be now.
78 // If dwTimeout is INFINITE, it stays INFINITE
79 if (dwWaitTime != INFINITE) {
80
81 DWORD dwElapsed = timeGetTime()-dwStartTime;
82
83 dwWaitTime =
84 (dwElapsed >= dwTimeout)
85 ? 0 // wake up with WAIT_TIMEOUT
86 : dwTimeout-dwElapsed;
87 }
88 }
89 } while (dwWait == WAIT_OBJECT_0 + 1);
90
91 // return TRUE if we woke on the event handle,
92 // FALSE if we timed out.
93 return (dwWait == WAIT_OBJECT_0);
94 }
95
96 // --- CAMThread ----------------------
97
98
99 CAMThread::CAMThread(__inout_opt HRESULT *phr)
100 : m_EventSend(TRUE, phr), // must be manual-reset for CheckRequest()
101 m_EventComplete(FALSE, phr)
102 {
103 m_hThread = NULL;
104 }
105
106 CAMThread::~CAMThread() {
107 Close();
108 }
109
110
111 // when the thread starts, it calls this function. We unwrap the 'this'
112 //pointer and call ThreadProc.
113 DWORD WINAPI
114 CAMThread::InitialThreadProc(__inout LPVOID pv)
115 {
116 HRESULT hrCoInit = CAMThread::CoInitializeHelper();
117 if(FAILED(hrCoInit)) {
118 DbgLog((LOG_ERROR, 1, TEXT("CoInitializeEx failed.")));
119 }
120
121 CAMThread * pThread = (CAMThread *) pv;
122
123 HRESULT hr = pThread->ThreadProc();
124
125 if(SUCCEEDED(hrCoInit)) {
126 CoUninitialize();
127 }
128
129 return hr;
130 }
131
132 BOOL
133 CAMThread::Create()
134 {
135 DWORD threadid;
136
137 CAutoLock lock(&m_AccessLock);
138
139 if (ThreadExists()) {
140 return FALSE;
141 }
142
143 m_hThread = CreateThread(
144 NULL,
145 0,
146 CAMThread::InitialThreadProc,
147 this,
148 0,
149 &threadid);
150
151 if (!m_hThread) {
152 return FALSE;
153 }
154
155 return TRUE;
156 }
157
158 DWORD
159 CAMThread::CallWorker(DWORD dwParam)
160 {
161 // lock access to the worker thread for scope of this object
162 CAutoLock lock(&m_AccessLock);
163
164 if (!ThreadExists()) {
165 return (DWORD) E_FAIL;
166 }
167
168 // set the parameter
169 m_dwParam = dwParam;
170
171 // signal the worker thread
172 m_EventSend.Set();
173
174 // wait for the completion to be signalled
175 m_EventComplete.Wait();
176
177 // done - this is the thread's return value
178 return m_dwReturnVal;
179 }
180
181 // Wait for a request from the client
182 DWORD
183 CAMThread::GetRequest()
184 {
185 m_EventSend.Wait();
186 return m_dwParam;
187 }
188
189 // is there a request?
190 BOOL
191 CAMThread::CheckRequest(__out_opt DWORD * pParam)
192 {
193 if (!m_EventSend.Check()) {
194 return FALSE;
195 } else {
196 if (pParam) {
197 *pParam = m_dwParam;
198 }
199 return TRUE;
200 }
201 }
202
203 // reply to the request
204 void
205 CAMThread::Reply(DWORD dw)
206 {
207 m_dwReturnVal = dw;
208
209 // The request is now complete so CheckRequest should fail from
210 // now on
211 //
212 // This event should be reset BEFORE we signal the client or
213 // the client may Set it before we reset it and we'll then
214 // reset it (!)
215
216 m_EventSend.Reset();
217
218 // Tell the client we're finished
219
220 m_EventComplete.Set();
221 }
222
223 HRESULT CAMThread::CoInitializeHelper()
224 {
225 // call CoInitializeEx and tell OLE not to create a window (this
226 // thread probably won't dispatch messages and will hang on
227 // broadcast msgs o/w).
228 //
229 // If CoInitEx is not available, threads that don't call CoCreate
230 // aren't affected. Threads that do will have to handle the
231 // failure. Perhaps we should fall back to CoInitialize and risk
232 // hanging?
233 //
234
235 // older versions of ole32.dll don't have CoInitializeEx
236
237 HRESULT hr = E_FAIL;
238 HINSTANCE hOle = GetModuleHandle(TEXT("ole32.dll"));
239 if(hOle)
240 {
241 typedef HRESULT (STDAPICALLTYPE *PCoInitializeEx)(
242 LPVOID pvReserved, DWORD dwCoInit);
243 PCoInitializeEx pCoInitializeEx =
244 (PCoInitializeEx)(GetProcAddress(hOle, "CoInitializeEx"));
245 if(pCoInitializeEx)
246 {
247 hr = (*pCoInitializeEx)(0, COINIT_DISABLE_OLE1DDE );
248 }
249 }
250 else
251 {
252 // caller must load ole32.dll
253 DbgBreak("couldn't locate ole32.dll");
254 }
255
256 return hr;
257 }
258
259
260 // destructor for CMsgThread - cleans up any messages left in the
261 // queue when the thread exited
262 CMsgThread::~CMsgThread()
263 {
264 if (m_hThread != NULL) {
265 WaitForSingleObject(m_hThread, INFINITE);
266 EXECUTE_ASSERT(CloseHandle(m_hThread));
267 }
268
269 POSITION pos = m_ThreadQueue.GetHeadPosition();
270 while (pos) {
271 CMsg * pMsg = m_ThreadQueue.GetNext(pos);
272 delete pMsg;
273 }
274 m_ThreadQueue.RemoveAll();
275
276 if (m_hSem != NULL) {
277 EXECUTE_ASSERT(CloseHandle(m_hSem));
278 }
279 }
280
281 BOOL
282 CMsgThread::CreateThread(
283 )
284 {
285 m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL);
286 if (m_hSem == NULL) {
287 return FALSE;
288 }
289
290 m_hThread = ::CreateThread(NULL, 0, DefaultThreadProc,
291 (LPVOID)this, 0, &m_ThreadId);
292 return m_hThread != NULL;
293 }
294
295
296 // This is the threads message pump. Here we get and dispatch messages to
297 // clients thread proc until the client refuses to process a message.
298 // The client returns a non-zero value to stop the message pump, this
299 // value becomes the threads exit code.
300
301 DWORD WINAPI
302 CMsgThread::DefaultThreadProc(
303 __inout LPVOID lpParam
304 )
305 {
306 CMsgThread *lpThis = (CMsgThread *)lpParam;
307 CMsg msg;
308 LRESULT lResult;
309
310 // !!!
311 CoInitialize(NULL);
312
313 // allow a derived class to handle thread startup
314 lpThis->OnThreadInit();
315
316 do {
317 lpThis->GetThreadMsg(&msg);
318 lResult = lpThis->ThreadMessageProc(msg.uMsg,msg.dwFlags,
319 msg.lpParam, msg.pEvent);
320 } while (lResult == 0L);
321
322 // !!!
323 CoUninitialize();
324
325 return (DWORD)lResult;
326 }
327
328
329 // Block until the next message is placed on the list m_ThreadQueue.
330 // copies the message to the message pointed to by *pmsg
331 void
332 CMsgThread::GetThreadMsg(__out CMsg *msg)
333 {
334 CMsg * pmsg = NULL;
335
336 // keep trying until a message appears
337 while (TRUE) {
338 {
339 CAutoLock lck(&m_Lock);
340 pmsg = m_ThreadQueue.RemoveHead();
341 if (pmsg == NULL) {
342 m_lWaiting++;
343 } else {
344 break;
345 }
346 }
347 // the semaphore will be signalled when it is non-empty
348 WaitForSingleObject(m_hSem, INFINITE);
349 }
350 // copy fields to caller's CMsg
351 *msg = *pmsg;
352
353 // this CMsg was allocated by the 'new' in PutThreadMsg
354 delete pmsg;
355
356 }
357
358 // Helper function - convert int to WSTR
359 void WINAPI IntToWstr(int i, __out_ecount(12) LPWSTR wstr)
360 {
361 #ifdef UNICODE
362 if (FAILED(StringCchPrintf(wstr, 12, L"%d", i))) {
363 wstr[0] = 0;
364 }
365 #else
366 TCHAR temp[12];
367 if (FAILED(StringCchPrintf(temp, NUMELMS(temp), "%d", i))) {
368 wstr[0] = 0;
369 } else {
370 MultiByteToWideChar(CP_ACP, 0, temp, -1, wstr, 12);
371 }
372 #endif
373 } // IntToWstr
374
375
376 #define MEMORY_ALIGNMENT 4
377 #define MEMORY_ALIGNMENT_LOG2 2
378 #define MEMORY_ALIGNMENT_MASK MEMORY_ALIGNMENT - 1
379
380 void * __stdcall memmoveInternal(void * dst, const void * src, size_t count)
381 {
382 void * ret = dst;
383
384 #ifdef _X86_
385 if (dst <= src || (char *)dst >= ((char *)src + count)) {
386
387 /*
388 * Non-Overlapping Buffers
389 * copy from lower addresses to higher addresses
390 */
391 _asm {
392 mov esi,src
393 mov edi,dst
394 mov ecx,count
395 cld
396 mov edx,ecx
397 and edx,MEMORY_ALIGNMENT_MASK
398 shr ecx,MEMORY_ALIGNMENT_LOG2
399 rep movsd
400 or ecx,edx
401 jz memmove_done
402 rep movsb
403 memmove_done:
404 }
405 }
406 else {
407
408 /*
409 * Overlapping Buffers
410 * copy from higher addresses to lower addresses
411 */
412 _asm {
413 mov esi,src
414 mov edi,dst
415 mov ecx,count
416 std
417 add esi,ecx
418 add edi,ecx
419 dec esi
420 dec edi
421 rep movsb
422 cld
423 }
424 }
425 #else
426 MoveMemory(dst, src, count);
427 #endif
428
429 return ret;
430 }
431
432 HRESULT AMSafeMemMoveOffset(
433 __in_bcount(dst_size) void * dst,
434 __in size_t dst_size,
435 __in DWORD cb_dst_offset,
436 __in_bcount(src_size) const void * src,
437 __in size_t src_size,
438 __in DWORD cb_src_offset,
439 __in size_t count)
440 {
441 // prevent read overruns
442 if( count + cb_src_offset < count || // prevent integer overflow
443 count + cb_src_offset > src_size) // prevent read overrun
444 {
445 return E_INVALIDARG;
446 }
447
448 // prevent write overruns
449 if( count + cb_dst_offset < count || // prevent integer overflow
450 count + cb_dst_offset > dst_size) // prevent write overrun
451 {
452 return E_INVALIDARG;
453 }
454
455 memmoveInternal( (BYTE *)dst+cb_dst_offset, (BYTE *)src+cb_src_offset, count);
456 return S_OK;
457 }
458
459
460 #ifdef DEBUG
461 /******************************Public*Routine******************************\
462 * Debug CCritSec helpers
463 *
464 * We provide debug versions of the Constructor, destructor, Lock and Unlock
465 * routines. The debug code tracks who owns each critical section by
466 * maintaining a depth count.
467 *
468 * History:
469 *
470 \**************************************************************************/
471
472 CCritSec::CCritSec()
473 {
474 InitializeCriticalSection(&m_CritSec);
475 m_currentOwner = m_lockCount = 0;
476 m_fTrace = FALSE;
477 }
478
479 CCritSec::~CCritSec()
480 {
481 DeleteCriticalSection(&m_CritSec);
482 }
483
484 void CCritSec::Lock()
485 {
486 UINT tracelevel=3;
487 DWORD us = GetCurrentThreadId();
488 DWORD currentOwner = m_currentOwner;
489 if (currentOwner && (currentOwner != us)) {
490 // already owned, but not by us
491 if (m_fTrace) {
492 DbgLog((LOG_LOCKING, 2, TEXT("Thread %d about to wait for lock %x owned by %d"),
493 GetCurrentThreadId(), &m_CritSec, currentOwner));
494 tracelevel=2;
495 // if we saw the message about waiting for the critical
496 // section we ensure we see the message when we get the
497 // critical section
498 }
499 }
500 EnterCriticalSection(&m_CritSec);
501 if (0 == m_lockCount++) {
502 // we now own it for the first time. Set owner information
503 m_currentOwner = us;
504
505 if (m_fTrace) {
506 DbgLog((LOG_LOCKING, tracelevel, TEXT("Thread %d now owns lock %x"), m_currentOwner, &m_CritSec));
507 }
508 }
509 }
510
511 void CCritSec::Unlock() {
512 if (0 == --m_lockCount) {
513 // about to be unowned
514 if (m_fTrace) {
515 DbgLog((LOG_LOCKING, 3, TEXT("Thread %d releasing lock %x"), m_currentOwner, &m_CritSec));
516 }
517
518 m_currentOwner = 0;
519 }
520 LeaveCriticalSection(&m_CritSec);
521 }
522
523 void WINAPI DbgLockTrace(CCritSec * pcCrit, BOOL fTrace)
524 {
525 pcCrit->m_fTrace = fTrace;
526 }
527
528 BOOL WINAPI CritCheckIn(CCritSec * pcCrit)
529 {
530 return (GetCurrentThreadId() == pcCrit->m_currentOwner);
531 }
532
533 BOOL WINAPI CritCheckIn(const CCritSec * pcCrit)
534 {
535 return (GetCurrentThreadId() == pcCrit->m_currentOwner);
536 }
537
538 BOOL WINAPI CritCheckOut(CCritSec * pcCrit)
539 {
540 return (GetCurrentThreadId() != pcCrit->m_currentOwner);
541 }
542
543 BOOL WINAPI CritCheckOut(const CCritSec * pcCrit)
544 {
545 return (GetCurrentThreadId() != pcCrit->m_currentOwner);
546 }
547 #endif
548
549
550 STDAPI WriteBSTR(__deref_out BSTR *pstrDest, LPCWSTR szSrc)
551 {
552 *pstrDest = SysAllocString( szSrc );
553 if( !(*pstrDest) ) return E_OUTOFMEMORY;
554 return NOERROR;
555 }
556
557
558 STDAPI FreeBSTR(__deref_in BSTR* pstr)
559 {
560 if( (PVOID)*pstr == NULL ) return S_FALSE;
561 SysFreeString( *pstr );
562 return NOERROR;
563 }
564
565
566 // Return a wide string - allocating memory for it
567 // Returns:
568 // S_OK - no error
569 // E_POINTER - ppszReturn == NULL
570 // E_OUTOFMEMORY - can't allocate memory for returned string
571 STDAPI AMGetWideString(LPCWSTR psz, __deref_out LPWSTR *ppszReturn)
572 {
573 CheckPointer(ppszReturn, E_POINTER);
574 ValidateReadWritePtr(ppszReturn, sizeof(LPWSTR));
575 *ppszReturn = NULL;
576 size_t nameLen;
577 HRESULT hr = StringCbLengthW(psz, 100000, &nameLen);
578 if (FAILED(hr)) {
579 return hr;
580 }
581 *ppszReturn = (LPWSTR)CoTaskMemAlloc(nameLen + sizeof(WCHAR));
582 if (*ppszReturn == NULL) {
583 return E_OUTOFMEMORY;
584 }
585 CopyMemory(*ppszReturn, psz, nameLen + sizeof(WCHAR));
586 return NOERROR;
587 }
588
589 // Waits for the HANDLE hObject. While waiting messages sent
590 // to windows on our thread by SendMessage will be processed.
591 // Using this function to do waits and mutual exclusion
592 // avoids some deadlocks in objects with windows.
593 // Return codes are the same as for WaitForSingleObject
594 DWORD WINAPI WaitDispatchingMessages(
595 HANDLE hObject,
596 DWORD dwWait,
597 HWND hwnd,
598 UINT uMsg,
599 HANDLE hEvent)
600 {
601 BOOL bPeeked = FALSE;
602 DWORD dwResult;
603 DWORD dwStart;
604 DWORD dwThreadPriority;
605
606 static UINT uMsgId = 0;
607
608 HANDLE hObjects[2] = { hObject, hEvent };
609 if (dwWait != INFINITE && dwWait != 0) {
610 dwStart = GetTickCount();
611 }
612 for (; ; ) {
613 DWORD nCount = NULL != hEvent ? 2 : 1;
614
615 // Minimize the chance of actually dispatching any messages
616 // by seeing if we can lock immediately.
617 dwResult = WaitForMultipleObjects(nCount, hObjects, FALSE, 0);
618 if (dwResult < WAIT_OBJECT_0 + nCount) {
619 break;
620 }
621
622 DWORD dwTimeOut = dwWait;
623 if (dwTimeOut > 10) {
624 dwTimeOut = 10;
625 }
626 dwResult = MsgWaitForMultipleObjects(
627 nCount,
628 hObjects,
629 FALSE,
630 dwTimeOut,
631 hwnd == NULL ? QS_SENDMESSAGE :
632 QS_SENDMESSAGE + QS_POSTMESSAGE);
633 if (dwResult == WAIT_OBJECT_0 + nCount ||
634 dwResult == WAIT_TIMEOUT && dwTimeOut != dwWait) {
635 MSG msg;
636 if (hwnd != NULL) {
637 while (PeekMessage(&msg, hwnd, uMsg, uMsg, PM_REMOVE)) {
638 DispatchMessage(&msg);
639 }
640 }
641 // Do this anyway - the previous peek doesn't flush out the
642 // messages
643 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
644
645 if (dwWait != INFINITE && dwWait != 0) {
646 DWORD dwNow = GetTickCount();
647
648 // Working with differences handles wrap-around
649 DWORD dwDiff = dwNow - dwStart;
650 if (dwDiff > dwWait) {
651 dwWait = 0;
652 } else {
653 dwWait -= dwDiff;
654 }
655 dwStart = dwNow;
656 }
657 if (!bPeeked) {
658 // Raise our priority to prevent our message queue
659 // building up
660 dwThreadPriority = GetThreadPriority(GetCurrentThread());
661 if (dwThreadPriority < THREAD_PRIORITY_HIGHEST) {
662 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
663 }
664 bPeeked = TRUE;
665 }
666 } else {
667 break;
668 }
669 }
670 if (bPeeked) {
671 SetThreadPriority(GetCurrentThread(), dwThreadPriority);
672 if (HIWORD(GetQueueStatus(QS_POSTMESSAGE)) & QS_POSTMESSAGE) {
673 if (uMsgId == 0) {
674 uMsgId = RegisterWindowMessage(TEXT("AMUnblock"));
675 }
676 if (uMsgId != 0) {
677 MSG msg;
678 // Remove old ones
679 while (PeekMessage(&msg, (HWND)-1, uMsgId, uMsgId, PM_REMOVE)) {
680 }
681 }
682 PostThreadMessage(GetCurrentThreadId(), uMsgId, 0, 0);
683 }
684 }
685 return dwResult;
686 }
687
688 HRESULT AmGetLastErrorToHResult()
689 {
690 DWORD dwLastError = GetLastError();
691 if(dwLastError != 0)
692 {
693 return HRESULT_FROM_WIN32(dwLastError);
694 }
695 else
696 {
697 return E_FAIL;
698 }
699 }
700
701 IUnknown* QzAtlComPtrAssign(__deref_inout_opt IUnknown** pp, __in_opt IUnknown* lp)
702 {
703 if (lp != NULL)
704 lp->AddRef();
705 if (*pp)
706 (*pp)->Release();
707 *pp = lp;
708 return lp;
709 }
710
711 /******************************************************************************
712
713 CompatibleTimeSetEvent
714
715 CompatibleTimeSetEvent() sets the TIME_KILL_SYNCHRONOUS flag before calling
716 timeSetEvent() if the current operating system supports it. TIME_KILL_SYNCHRONOUS
717 is supported on Windows XP and later operating systems.
718
719 Parameters:
720 - The same parameters as timeSetEvent(). See timeSetEvent()'s documentation in
721 the Platform SDK for more information.
722
723 Return Value:
724 - The same return value as timeSetEvent(). See timeSetEvent()'s documentation in
725 the Platform SDK for more information.
726
727 ******************************************************************************/
728 MMRESULT CompatibleTimeSetEvent( UINT uDelay, UINT uResolution, __in LPTIMECALLBACK lpTimeProc, DWORD_PTR dwUser, UINT fuEvent )
729 {
730 #if WINVER >= 0x0501
731 {
732 static bool fCheckedVersion = false;
733 static bool fTimeKillSynchronousFlagAvailable = false;
734
735 if( !fCheckedVersion ) {
736 fTimeKillSynchronousFlagAvailable = TimeKillSynchronousFlagAvailable();
737 fCheckedVersion = true;
738 }
739
740 if( fTimeKillSynchronousFlagAvailable ) {
741 fuEvent = fuEvent | TIME_KILL_SYNCHRONOUS;
742 }
743 }
744 #endif // WINVER >= 0x0501
745
746 return timeSetEvent( uDelay, uResolution, lpTimeProc, dwUser, fuEvent );
747 }
748
749 bool TimeKillSynchronousFlagAvailable( void )
750 {
751 OSVERSIONINFO osverinfo;
752
753 osverinfo.dwOSVersionInfoSize = sizeof(osverinfo);
754
755 if( GetVersionEx( &osverinfo ) ) {
756
757 // Windows XP's major version is 5 and its' minor version is 1.
758 // timeSetEvent() started supporting the TIME_KILL_SYNCHRONOUS flag
759 // in Windows XP.
760 if( (osverinfo.dwMajorVersion > 5) ||
761 ( (osverinfo.dwMajorVersion == 5) && (osverinfo.dwMinorVersion >= 1) ) ) {
762 return true;
763 }
764 }
765
766 return false;
767 }
768
769