refclock.cpp 12 KB

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