blob: 8e69652a856bd8e0539f606b1350ceba41a406ad [file] [log] [blame]
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +00001/*
2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/system_wrappers/interface/clock.h"
12
13#if defined(_WIN32)
pbos@webrtc.orgacaf3a12013-05-27 15:07:45 +000014// Windows needs to be included before mmsystem.h
pbos@webrtc.orgf9389222015-01-21 12:51:13 +000015#include "webrtc/base/win32.h"
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +000016#include <MMSystem.h>
17#elif ((defined WEBRTC_LINUX) || (defined WEBRTC_MAC))
18#include <sys/time.h>
19#include <time.h>
20#endif
21
pbos@webrtc.orgf9389222015-01-21 12:51:13 +000022#include "webrtc/base/criticalsection.h"
henrik.lundin@webrtc.org59336e82014-05-27 09:34:58 +000023#include "webrtc/system_wrappers/interface/rw_lock_wrapper.h"
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +000024#include "webrtc/system_wrappers/interface/tick_util.h"
25
26namespace webrtc {
27
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +000028const double kNtpFracPerMs = 4.294967296E6;
29
30int64_t Clock::NtpToMs(uint32_t ntp_secs, uint32_t ntp_frac) {
31 const double ntp_frac_ms = static_cast<double>(ntp_frac) / kNtpFracPerMs;
32 return 1000 * static_cast<int64_t>(ntp_secs) +
33 static_cast<int64_t>(ntp_frac_ms + 0.5);
34}
35
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +000036class RealTimeClock : public Clock {
37 // Return a timestamp in milliseconds relative to some arbitrary source; the
38 // source is fixed for this clock.
henrik.lundin@webrtc.org190a32f2014-06-09 17:40:49 +000039 virtual int64_t TimeInMilliseconds() const OVERRIDE {
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +000040 return TickTime::MillisecondTimestamp();
41 }
42
43 // Return a timestamp in microseconds relative to some arbitrary source; the
44 // source is fixed for this clock.
henrik.lundin@webrtc.org190a32f2014-06-09 17:40:49 +000045 virtual int64_t TimeInMicroseconds() const OVERRIDE {
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +000046 return TickTime::MicrosecondTimestamp();
47 }
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +000048
49 // Retrieve an NTP absolute timestamp in seconds and fractions of a second.
henrik.lundin@webrtc.org190a32f2014-06-09 17:40:49 +000050 virtual void CurrentNtp(uint32_t& seconds,
51 uint32_t& fractions) const OVERRIDE {
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +000052 timeval tv = CurrentTimeVal();
53 double microseconds_in_seconds;
54 Adjust(tv, &seconds, &microseconds_in_seconds);
55 fractions = static_cast<uint32_t>(
56 microseconds_in_seconds * kMagicNtpFractionalUnit + 0.5);
57 }
58
59 // Retrieve an NTP absolute timestamp in milliseconds.
henrik.lundin@webrtc.org190a32f2014-06-09 17:40:49 +000060 virtual int64_t CurrentNtpInMilliseconds() const OVERRIDE {
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +000061 timeval tv = CurrentTimeVal();
62 uint32_t seconds;
63 double microseconds_in_seconds;
64 Adjust(tv, &seconds, &microseconds_in_seconds);
65 return 1000 * static_cast<int64_t>(seconds) +
66 static_cast<int64_t>(1000.0 * microseconds_in_seconds + 0.5);
67 }
68
69 protected:
70 virtual timeval CurrentTimeVal() const = 0;
71
72 static void Adjust(const timeval& tv, uint32_t* adjusted_s,
73 double* adjusted_us_in_s) {
74 *adjusted_s = tv.tv_sec + kNtpJan1970;
75 *adjusted_us_in_s = tv.tv_usec / 1e6;
76
77 if (*adjusted_us_in_s >= 1) {
78 *adjusted_us_in_s -= 1;
79 ++*adjusted_s;
80 } else if (*adjusted_us_in_s < -1) {
81 *adjusted_us_in_s += 1;
82 --*adjusted_s;
83 }
84 }
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +000085};
86
87#if defined(_WIN32)
pbos@webrtc.orgf9389222015-01-21 12:51:13 +000088// TODO(pbos): Consider modifying the implementation to synchronize itself
89// against system time (update ref_point_, make it non-const) periodically to
90// prevent clock drift.
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +000091class WindowsRealTimeClock : public RealTimeClock {
92 public:
pbos@webrtc.orgf9389222015-01-21 12:51:13 +000093 WindowsRealTimeClock()
94 : last_time_ms_(0),
95 num_timer_wraps_(0),
96 ref_point_(GetSystemReferencePoint()) {}
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +000097
98 virtual ~WindowsRealTimeClock() {}
99
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +0000100 protected:
pbos@webrtc.orgf9389222015-01-21 12:51:13 +0000101 struct ReferencePoint {
102 FILETIME file_time;
103 LARGE_INTEGER counter_ms;
104 };
105
pbos@webrtc.orga2a27182013-08-01 17:26:15 +0000106 virtual timeval CurrentTimeVal() const OVERRIDE {
pbos@webrtc.org046deb92013-04-09 09:06:11 +0000107 const uint64_t FILETIME_1970 = 0x019db1ded53e8000;
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000108
109 FILETIME StartTime;
pbos@webrtc.org046deb92013-04-09 09:06:11 +0000110 uint64_t Time;
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000111 struct timeval tv;
112
wu@webrtc.org7a9a3b72014-05-29 19:40:28 +0000113 // We can't use query performance counter since they can change depending on
114 // speed stepping.
pbos@webrtc.orgf9389222015-01-21 12:51:13 +0000115 GetTime(&StartTime);
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000116
pbos@webrtc.org046deb92013-04-09 09:06:11 +0000117 Time = (((uint64_t) StartTime.dwHighDateTime) << 32) +
118 (uint64_t) StartTime.dwLowDateTime;
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000119
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +0000120 // Convert the hecto-nano second time to tv format.
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000121 Time -= FILETIME_1970;
122
pbos@webrtc.org046deb92013-04-09 09:06:11 +0000123 tv.tv_sec = (uint32_t)(Time / (uint64_t)10000000);
124 tv.tv_usec = (uint32_t)((Time % (uint64_t)10000000) / 10);
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +0000125 return tv;
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000126 }
wu@webrtc.org7a9a3b72014-05-29 19:40:28 +0000127
pbos@webrtc.orgf9389222015-01-21 12:51:13 +0000128 void GetTime(FILETIME* current_time) const {
129 DWORD t;
130 LARGE_INTEGER elapsed_ms;
131 {
132 rtc::CritScope lock(&crit_);
133 // time MUST be fetched inside the critical section to avoid non-monotonic
134 // last_time_ms_ values that'll register as incorrect wraparounds due to
135 // concurrent calls to GetTime.
136 t = timeGetTime();
137 if (t < last_time_ms_)
138 num_timer_wraps_++;
139 last_time_ms_ = t;
140 elapsed_ms.HighPart = num_timer_wraps_;
141 }
142 elapsed_ms.LowPart = t;
143 elapsed_ms.QuadPart = elapsed_ms.QuadPart - ref_point_.counter_ms.QuadPart;
144
145 // Translate to 100-nanoseconds intervals (FILETIME resolution)
146 // and add to reference FILETIME to get current FILETIME.
147 ULARGE_INTEGER filetime_ref_as_ul;
148 filetime_ref_as_ul.HighPart = ref_point_.file_time.dwHighDateTime;
149 filetime_ref_as_ul.LowPart = ref_point_.file_time.dwLowDateTime;
150 filetime_ref_as_ul.QuadPart +=
151 static_cast<ULONGLONG>((elapsed_ms.QuadPart) * 1000 * 10);
152
153 // Copy to result
154 current_time->dwHighDateTime = filetime_ref_as_ul.HighPart;
155 current_time->dwLowDateTime = filetime_ref_as_ul.LowPart;
156 }
157
158 static ReferencePoint GetSystemReferencePoint() {
159 ReferencePoint ref = {0};
160 FILETIME ft0 = {0};
161 FILETIME ft1 = {0};
162 // Spin waiting for a change in system time. As soon as this change happens,
163 // get the matching call for timeGetTime() as soon as possible. This is
164 // assumed to be the most accurate offset that we can get between
165 // timeGetTime() and system time.
166
167 // Set timer accuracy to 1 ms.
168 timeBeginPeriod(1);
169 GetSystemTimeAsFileTime(&ft0);
170 do {
171 GetSystemTimeAsFileTime(&ft1);
172
173 ref.counter_ms.QuadPart = timeGetTime();
174 Sleep(0);
175 } while ((ft0.dwHighDateTime == ft1.dwHighDateTime) &&
176 (ft0.dwLowDateTime == ft1.dwLowDateTime));
177 ref.file_time = ft1;
178 timeEndPeriod(1);
179 return ref;
180 }
181
182 // mutable as time-accessing functions are const.
183 mutable rtc::CriticalSection crit_;
184 mutable DWORD last_time_ms_;
185 mutable LONG num_timer_wraps_;
186 const ReferencePoint ref_point_;
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000187};
188
189#elif ((defined WEBRTC_LINUX) || (defined WEBRTC_MAC))
190class UnixRealTimeClock : public RealTimeClock {
191 public:
192 UnixRealTimeClock() {}
193
194 virtual ~UnixRealTimeClock() {}
195
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +0000196 protected:
pbos@webrtc.orga2a27182013-08-01 17:26:15 +0000197 virtual timeval CurrentTimeVal() const OVERRIDE {
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000198 struct timeval tv;
199 struct timezone tz;
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +0000200 tz.tz_minuteswest = 0;
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000201 tz.tz_dsttime = 0;
202 gettimeofday(&tv, &tz);
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +0000203 return tv;
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000204 }
205};
206#endif
207
wu@webrtc.org7a9a3b72014-05-29 19:40:28 +0000208#if defined(_WIN32)
pbos@webrtc.orgf9389222015-01-21 12:51:13 +0000209static WindowsRealTimeClock* volatile g_shared_clock = nullptr;
wu@webrtc.org7a9a3b72014-05-29 19:40:28 +0000210#endif
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000211Clock* Clock::GetRealTimeClock() {
212#if defined(_WIN32)
pbos@webrtc.orgf9389222015-01-21 12:51:13 +0000213 // This read relies on volatile read being atomic-load-acquire. This is
214 // true in MSVC since at least 2005:
215 // "A read of a volatile object (volatile read) has Acquire semantics"
216 if (g_shared_clock != nullptr)
217 return g_shared_clock;
218 WindowsRealTimeClock* clock = new WindowsRealTimeClock;
219 if (InterlockedCompareExchangePointer(
220 reinterpret_cast<void* volatile*>(&g_shared_clock), clock, nullptr) !=
221 nullptr) {
222 // g_shared_clock was assigned while we constructed/tried to assign our
223 // instance, delete our instance and use the existing one.
224 delete clock;
225 }
226 return g_shared_clock;
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000227#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC)
stefan@webrtc.orga678a3b2013-01-21 07:42:11 +0000228 static UnixRealTimeClock clock;
229 return &clock;
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000230#else
231 return NULL;
232#endif
233}
234
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000235SimulatedClock::SimulatedClock(int64_t initial_time_us)
henrik.lundin@webrtc.org59336e82014-05-27 09:34:58 +0000236 : time_us_(initial_time_us), lock_(RWLockWrapper::CreateRWLock()) {
237}
238
239SimulatedClock::~SimulatedClock() {
240}
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000241
henrik.lundin@webrtc.org190a32f2014-06-09 17:40:49 +0000242int64_t SimulatedClock::TimeInMilliseconds() const {
henrik.lundin@webrtc.org59336e82014-05-27 09:34:58 +0000243 ReadLockScoped synchronize(*lock_);
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000244 return (time_us_ + 500) / 1000;
245}
246
henrik.lundin@webrtc.org190a32f2014-06-09 17:40:49 +0000247int64_t SimulatedClock::TimeInMicroseconds() const {
henrik.lundin@webrtc.org59336e82014-05-27 09:34:58 +0000248 ReadLockScoped synchronize(*lock_);
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000249 return time_us_;
250}
251
henrik.lundin@webrtc.org190a32f2014-06-09 17:40:49 +0000252void SimulatedClock::CurrentNtp(uint32_t& seconds, uint32_t& fractions) const {
henrik.lundin@webrtc.org59336e82014-05-27 09:34:58 +0000253 int64_t now_ms = TimeInMilliseconds();
254 seconds = (now_ms / 1000) + kNtpJan1970;
255 fractions =
256 static_cast<uint32_t>((now_ms % 1000) * kMagicNtpFractionalUnit / 1000);
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000257}
258
henrik.lundin@webrtc.org190a32f2014-06-09 17:40:49 +0000259int64_t SimulatedClock::CurrentNtpInMilliseconds() const {
stefan@webrtc.orgb8e7f4c2013-04-12 11:56:23 +0000260 return TimeInMilliseconds() + 1000 * static_cast<int64_t>(kNtpJan1970);
261}
262
stefan@webrtc.orga678a3b2013-01-21 07:42:11 +0000263void SimulatedClock::AdvanceTimeMilliseconds(int64_t milliseconds) {
264 AdvanceTimeMicroseconds(1000 * milliseconds);
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000265}
266
stefan@webrtc.orga678a3b2013-01-21 07:42:11 +0000267void SimulatedClock::AdvanceTimeMicroseconds(int64_t microseconds) {
henrik.lundin@webrtc.org59336e82014-05-27 09:34:58 +0000268 WriteLockScoped synchronize(*lock_);
stefan@webrtc.org20ed36d2013-01-17 14:01:20 +0000269 time_us_ += microseconds;
270}
271
272}; // namespace webrtc