1 /****************************************************************************
2  *
3  *  Copyright (C) 2000-2001 RealNetworks, Inc. All rights reserved.
4  *
5  *  This program is free software.  It may be distributed under the terms
6  *  in the file LICENSE, found in the top level of the source distribution.
7  *
8  */
9 
10 #include "timer.h"
11 #include "app.h"
12 
13 #include "dbg.h"
14 
15 #define TVNORM(tv) while( tv.tv_usec > 1000*1000 ) { tv.tv_usec -= 1000*1000; tv.tv_sec++; }
16 
CTimer(CTimerResponse * pResponse)17 CTimer::CTimer( CTimerResponse* pResponse ) :
18     m_pResponse(pResponse),
19     m_mode(Disabled),
20     m_next(0),
21     m_interval(0)
22 {
23     // Empty
24 }
25 
~CTimer(void)26 CTimer::~CTimer( void )
27 {
28     Disable();
29 }
30 
SetResponse(CTimerResponse * pResponse)31 void CTimer::SetResponse( CTimerResponse* pResponse )
32 {
33     m_pResponse = pResponse;
34 }
35 
GetMode(void)36 CTimer::Mode CTimer::GetMode( void )
37 {
38     return m_mode;
39 }
40 
GetTimeout(void)41 UINT32 CTimer::GetTimeout( void )
42 {
43     return m_next;
44 }
45 
SetRelative(UINT32 msec)46 void CTimer::SetRelative( UINT32 msec )
47 {
48     Set( CurrentTime() + msec );
49     m_mode = SingleShot;
50 }
51 
SetAbsolute(UINT32 t)52 void CTimer::SetAbsolute( UINT32 t )
53 {
54     Set( t );
55     m_mode = SingleShot;
56 }
57 
SetRepeating(UINT32 msec)58 void CTimer::SetRepeating( UINT32 msec )
59 {
60     Set( CurrentTime() + msec );
61     m_interval = msec;
62     m_mode = Repeating;
63 }
64 
Disable(void)65 void CTimer::Disable( void )
66 {
67     if( m_mode != Disabled )
68     {
69         CEventThread* pSelf;
70         m_mode = Disabled;
71 #ifdef NO_RTTI
72         pSelf = (CEventThread*)CThread::This(); //XXX: very bad, upgrade compiler
73 #else
74         pSelf = dynamic_cast<CEventThread*>(CThread::This());
75 #endif
76         assert_or_ret( pSelf );
77         pSelf->DelTimer( this );
78     }
79 }
80 
CurrentTime(void)81 UINT32 CTimer::CurrentTime( void )
82 {
83 #ifdef _UNIX
84     timeval tv;
85     gettimeofday( &tv, NULL );
86     return (tv.tv_sec*1000 + tv.tv_usec/1000);
87 #endif
88 #ifdef _WIN32
89     return ::GetTickCount();
90 #endif
91 }
92 
Set(UINT32 t)93 void CTimer::Set( UINT32 t )
94 {
95     m_next = t;
96 
97     CEventThread* pSelf;
98 #ifdef NO_RTTI
99         pSelf = (CEventThread*)CThread::This(); //XXX: very bad, upgrade compiler
100 #else
101         pSelf = dynamic_cast<CEventThread*>(CThread::This());
102 #endif
103     assert_or_ret( pSelf );
104 
105     if( m_mode != Disabled ) pSelf->DelTimer( this );
106     pSelf->AddTimer( this );
107 }
108 
GetResponse(void)109 CTimerResponse* CTimer::GetResponse( void )
110 {
111     assert( m_pResponse );
112     return m_pResponse;
113 }
114