Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

355 lines
11 KiB

  1. //------------------------------------------------------------------------------
  2. // File: RefClock.cpp
  3. //
  4. // Desc: DirectShow base classes - implements the IReferenceClock interface.
  5. //
  6. // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved.
  7. //------------------------------------------------------------------------------
  8. #include <streams.h>
  9. #include <limits.h>
  10. //@@BEGIN_MSINTERNAL
  11. #ifdef DXMPERF
  12. #include "dxmperf.h"
  13. #endif // DXMPERF
  14. //@@END_MSINTERNAL
  15. // 'this' used in constructor list
  16. #pragma warning(disable:4355)
  17. STDMETHODIMP CBaseReferenceClock::NonDelegatingQueryInterface(
  18. REFIID riid,
  19. void ** ppv)
  20. {
  21. HRESULT hr;
  22. if (riid == IID_IReferenceClock)
  23. {
  24. hr = GetInterface((IReferenceClock *) this, ppv);
  25. }
  26. else
  27. {
  28. hr = CUnknown::NonDelegatingQueryInterface(riid, ppv);
  29. }
  30. return hr;
  31. }
  32. CBaseReferenceClock::~CBaseReferenceClock()
  33. {
  34. //@@BEGIN_MSINTERNAL
  35. #ifdef DXMPERF
  36. PERFLOG_DTOR( L"CBaseReferenceClock", (IReferenceClock *) this );
  37. #endif // DXMPERF
  38. //@@END_MSINTERNAL
  39. if (m_TimerResolution) timeEndPeriod(m_TimerResolution);
  40. m_pSchedule->DumpLinkedList();
  41. if (m_hThread)
  42. {
  43. m_bAbort = TRUE;
  44. TriggerThread();
  45. WaitForSingleObject( m_hThread, INFINITE );
  46. EXECUTE_ASSERT( CloseHandle(m_hThread) );
  47. m_hThread = 0;
  48. EXECUTE_ASSERT( CloseHandle(m_pSchedule->GetEvent()) );
  49. delete m_pSchedule;
  50. }
  51. }
  52. // A derived class may supply a hThreadEvent if it has its own thread that will take care
  53. // of calling the schedulers Advise method. (Refere to CBaseReferenceClock::AdviseThread()
  54. // to see what such a thread has to do.)
  55. CBaseReferenceClock::CBaseReferenceClock( TCHAR *pName, LPUNKNOWN pUnk, HRESULT *phr, CAMSchedule * pShed )
  56. : CUnknown( pName, pUnk )
  57. , m_rtLastGotTime(0)
  58. , m_TimerResolution(0)
  59. , m_bAbort( FALSE )
  60. , m_pSchedule( pShed ? pShed : new CAMSchedule(CreateEvent(NULL, FALSE, FALSE, NULL)) )
  61. , m_hThread(0)
  62. {
  63. //@@BEGIN_MSINTERNAL
  64. #ifdef DXMPERF
  65. PERFLOG_CTOR( pName ? pName : L"CBaseReferenceClock", (IReferenceClock *) this );
  66. #endif // DXMPERF
  67. //@@END_MSINTERNAL
  68. ASSERT(m_pSchedule);
  69. if (!m_pSchedule)
  70. {
  71. *phr = E_OUTOFMEMORY;
  72. }
  73. else
  74. {
  75. // Set up the highest resolution timer we can manage
  76. TIMECAPS tc;
  77. m_TimerResolution = (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(tc)))
  78. ? tc.wPeriodMin
  79. : 1;
  80. timeBeginPeriod(m_TimerResolution);
  81. /* Initialise our system times - the derived clock should set the right values */
  82. m_dwPrevSystemTime = timeGetTime();
  83. m_rtPrivateTime = (UNITS / MILLISECONDS) * m_dwPrevSystemTime;
  84. #ifdef PERF
  85. m_idGetSystemTime = MSR_REGISTER(TEXT("CBaseReferenceClock::GetTime"));
  86. #endif
  87. if ( !pShed )
  88. {
  89. DWORD ThreadID;
  90. m_hThread = ::CreateThread(NULL, // Security attributes
  91. (DWORD) 0, // Initial stack size
  92. AdviseThreadFunction, // Thread start address
  93. (LPVOID) this, // Thread parameter
  94. (DWORD) 0, // Creation flags
  95. &ThreadID); // Thread identifier
  96. if (m_hThread)
  97. {
  98. SetThreadPriority( m_hThread, THREAD_PRIORITY_TIME_CRITICAL );
  99. }
  100. else
  101. {
  102. *phr = E_FAIL;
  103. EXECUTE_ASSERT( CloseHandle(m_pSchedule->GetEvent()) );
  104. delete m_pSchedule;
  105. }
  106. }
  107. }
  108. }
  109. STDMETHODIMP CBaseReferenceClock::GetTime(REFERENCE_TIME *pTime)
  110. {
  111. HRESULT hr;
  112. if (pTime)
  113. {
  114. REFERENCE_TIME rtNow;
  115. Lock();
  116. rtNow = GetPrivateTime();
  117. if (rtNow > m_rtLastGotTime)
  118. {
  119. m_rtLastGotTime = rtNow;
  120. hr = S_OK;
  121. }
  122. else
  123. {
  124. hr = S_FALSE;
  125. }
  126. *pTime = m_rtLastGotTime;
  127. Unlock();
  128. MSR_INTEGER(m_idGetSystemTime, LONG((*pTime) / (UNITS/MILLISECONDS)) );
  129. //@@BEGIN_MSINTERNAL
  130. #ifdef DXMPERF
  131. PERFLOG_GETTIME( (IReferenceClock *) this, *pTime );
  132. #endif // DXMPERF
  133. //@@END_MSINTERNAL
  134. }
  135. else hr = E_POINTER;
  136. return hr;
  137. }
  138. /* Ask for an async notification that a time has elapsed */
  139. STDMETHODIMP CBaseReferenceClock::AdviseTime(
  140. REFERENCE_TIME baseTime, // base reference time
  141. REFERENCE_TIME streamTime, // stream offset time
  142. HEVENT hEvent, // advise via this event
  143. DWORD_PTR *pdwAdviseCookie) // where your cookie goes
  144. {
  145. CheckPointer(pdwAdviseCookie, E_POINTER);
  146. *pdwAdviseCookie = 0;
  147. // Check that the event is not already set
  148. ASSERT(WAIT_TIMEOUT == WaitForSingleObject(HANDLE(hEvent),0));
  149. HRESULT hr;
  150. const REFERENCE_TIME lRefTime = baseTime + streamTime;
  151. if ( lRefTime <= 0 || lRefTime == MAX_TIME )
  152. {
  153. hr = E_INVALIDARG;
  154. }
  155. else
  156. {
  157. *pdwAdviseCookie = m_pSchedule->AddAdvisePacket( lRefTime, 0, HANDLE(hEvent), FALSE );
  158. hr = *pdwAdviseCookie ? NOERROR : E_OUTOFMEMORY;
  159. }
  160. return hr;
  161. }
  162. /* Ask for an asynchronous periodic notification that a time has elapsed */
  163. STDMETHODIMP CBaseReferenceClock::AdvisePeriodic(
  164. REFERENCE_TIME StartTime, // starting at this time
  165. REFERENCE_TIME PeriodTime, // time between notifications
  166. HSEMAPHORE hSemaphore, // advise via a semaphore
  167. DWORD_PTR *pdwAdviseCookie) // where your cookie goes
  168. {
  169. CheckPointer(pdwAdviseCookie, E_POINTER);
  170. *pdwAdviseCookie = 0;
  171. HRESULT hr;
  172. if (StartTime > 0 && PeriodTime > 0 && StartTime != MAX_TIME )
  173. {
  174. *pdwAdviseCookie = m_pSchedule->AddAdvisePacket( StartTime, PeriodTime, HANDLE(hSemaphore), TRUE );
  175. hr = *pdwAdviseCookie ? NOERROR : E_OUTOFMEMORY;
  176. }
  177. else hr = E_INVALIDARG;
  178. return hr;
  179. }
  180. STDMETHODIMP CBaseReferenceClock::Unadvise(DWORD_PTR dwAdviseCookie)
  181. {
  182. return m_pSchedule->Unadvise(dwAdviseCookie);
  183. }
  184. REFERENCE_TIME CBaseReferenceClock::GetPrivateTime()
  185. {
  186. CAutoLock cObjectLock(this);
  187. /* If the clock has wrapped then the current time will be less than
  188. * the last time we were notified so add on the extra milliseconds
  189. *
  190. * The time period is long enough so that the likelihood of
  191. * successive calls spanning the clock cycle is not considered.
  192. */
  193. DWORD dwTime = timeGetTime();
  194. {
  195. m_rtPrivateTime += Int32x32To64(UNITS / MILLISECONDS, (DWORD)(dwTime - m_dwPrevSystemTime));
  196. m_dwPrevSystemTime = dwTime;
  197. }
  198. return m_rtPrivateTime;
  199. }
  200. /* Adjust the current time by the input value. This allows an
  201. external time source to work out some of the latency of the clock
  202. system and adjust the "current" time accordingly. The intent is
  203. that the time returned to the user is synchronised to a clock
  204. source and allows drift to be catered for.
  205. For example: if the clock source detects a drift it can pass a delta
  206. to the current time rather than having to set an explicit time.
  207. */
  208. STDMETHODIMP CBaseReferenceClock::SetTimeDelta(const REFERENCE_TIME & TimeDelta)
  209. {
  210. #ifdef DEBUG
  211. // Just break if passed an improper time delta value
  212. LONGLONG llDelta = TimeDelta > 0 ? TimeDelta : -TimeDelta;
  213. if (llDelta > UNITS * 1000) {
  214. DbgLog((LOG_TRACE, 0, TEXT("Bad Time Delta")));
  215. //DebugBreak();
  216. }
  217. // We're going to calculate a "severity" for the time change. Max -1
  218. // min 8. We'll then use this as the debug logging level for a
  219. // debug log message.
  220. const LONG usDelta = LONG(TimeDelta/10); // Delta in micro-secs
  221. DWORD delta = abs(usDelta); // varying delta
  222. // Severity == 8 - ceil(log<base 8>(abs( micro-secs delta)))
  223. int Severity = 8;
  224. while ( delta > 0 )
  225. {
  226. delta >>= 3; // div 8
  227. Severity--;
  228. }
  229. // Sev == 0 => > 2 second delta!
  230. DbgLog((LOG_TIMING, Severity < 0 ? 0 : Severity,
  231. TEXT("Sev %2i: CSystemClock::SetTimeDelta(%8ld us) %lu -> %lu ms."),
  232. Severity, usDelta, DWORD(ConvertToMilliseconds(m_rtPrivateTime)),
  233. DWORD(ConvertToMilliseconds(TimeDelta+m_rtPrivateTime)) ));
  234. // Don't want the DbgBreak to fire when running stress on debug-builds.
  235. #ifdef BREAK_ON_SEVERE_TIME_DELTA
  236. if (Severity < 0)
  237. DbgBreakPoint(TEXT("SetTimeDelta > 16 seconds!"),
  238. TEXT(__FILE__),__LINE__);
  239. #endif
  240. #endif
  241. CAutoLock cObjectLock(this);
  242. m_rtPrivateTime += TimeDelta;
  243. // If time goes forwards, and we have advises, then we need to
  244. // trigger the thread so that it can re-evaluate its wait time.
  245. // Since we don't want the cost of the thread switches if the change
  246. // is really small, only do it if clock goes forward by more than
  247. // 0.5 millisecond. If the time goes backwards, the thread will
  248. // wake up "early" (relativly speaking) and will re-evaluate at
  249. // that time.
  250. if ( TimeDelta > 5000 && m_pSchedule->GetAdviseCount() > 0 ) TriggerThread();
  251. return NOERROR;
  252. }
  253. // Thread stuff
  254. DWORD __stdcall CBaseReferenceClock::AdviseThreadFunction(LPVOID p)
  255. {
  256. return DWORD(reinterpret_cast<CBaseReferenceClock*>(p)->AdviseThread());
  257. }
  258. HRESULT CBaseReferenceClock::AdviseThread()
  259. {
  260. DWORD dwWait = INFINITE;
  261. // The first thing we do is wait until something interesting happens
  262. // (meaning a first advise or shutdown). This prevents us calling
  263. // GetPrivateTime immediately which is goodness as that is a virtual
  264. // routine and the derived class may not yet be constructed. (This
  265. // thread is created in the base class constructor.)
  266. while ( !m_bAbort )
  267. {
  268. // Wait for an interesting event to happen
  269. DbgLog((LOG_TIMING, 3, TEXT("CBaseRefClock::AdviseThread() Delay: %lu ms"), dwWait ));
  270. WaitForSingleObject(m_pSchedule->GetEvent(), dwWait);
  271. if (m_bAbort) break;
  272. // There are several reasons why we need to work from the internal
  273. // time, mainly to do with what happens when time goes backwards.
  274. // Mainly, it stop us looping madly if an event is just about to
  275. // expire when the clock goes backward (i.e. GetTime stop for a
  276. // while).
  277. const REFERENCE_TIME rtNow = GetPrivateTime();
  278. DbgLog((LOG_TIMING, 3,
  279. TEXT("CBaseRefClock::AdviseThread() Woke at = %lu ms"),
  280. ConvertToMilliseconds(rtNow) ));
  281. // We must add in a millisecond, since this is the resolution of our
  282. // WaitForSingleObject timer. Failure to do so will cause us to loop
  283. // franticly for (approx) 1 a millisecond.
  284. m_rtNextAdvise = m_pSchedule->Advise( 10000 + rtNow );
  285. LONGLONG llWait = m_rtNextAdvise - rtNow;
  286. ASSERT( llWait > 0 );
  287. llWait = ConvertToMilliseconds(llWait);
  288. // DON'T replace this with a max!! (The type's of these things is VERY important)
  289. dwWait = (llWait > REFERENCE_TIME(UINT_MAX)) ? UINT_MAX : DWORD(llWait);
  290. };
  291. return NOERROR;
  292. }