home *** CD-ROM | disk | FTP | other *** search
/ Visual Basic Game Programming for Teens / VBGPFT.cdr / DirectX8 / dx8a_sdk.exe / samples / multimedia / directshow / baseclasses / refclock.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-11-04  |  10.5 KB  |  336 lines

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