blob: 7a72173db766726a673581b2ecc7000d817f730a [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 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 <stdint.h>
12
13#if defined(WEBRTC_POSIX)
14#include <sys/time.h>
15#if defined(WEBRTC_MAC)
16#include <mach/mach_time.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020017
Yves Gerey988cc082018-10-23 12:03:01 +020018#include "rtc_base/numerics/safe_conversions.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#endif
20#endif
21
22#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +020023// clang-format off
24// clang formatting would put <windows.h> last,
25// which leads to compilation failure.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026#include <windows.h>
27#include <mmsystem.h>
nissecdf37a92016-09-13 23:41:47 -070028#include <sys/timeb.h>
Yves Gerey665174f2018-06-19 15:03:05 +020029// clang-format on
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030#endif
31
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "rtc_base/time_utils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000034
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035namespace rtc {
36
Taylor Brandstetterb3c68102016-05-27 14:15:43 -070037ClockInterface* g_clock = nullptr;
38
deadbeeff5f03e82016-06-06 11:16:06 -070039ClockInterface* SetClockForTesting(ClockInterface* clock) {
40 ClockInterface* prev = g_clock;
Taylor Brandstetterb3c68102016-05-27 14:15:43 -070041 g_clock = clock;
deadbeeff5f03e82016-06-06 11:16:06 -070042 return prev;
Taylor Brandstetterb3c68102016-05-27 14:15:43 -070043}
44
deadbeef22e08142017-06-12 14:30:28 -070045ClockInterface* GetClockForTesting() {
46 return g_clock;
47}
48
Robin Raymondce1b1402018-11-22 20:10:11 -050049#if defined(WINUWP)
50
51namespace {
52
53class TimeHelper final {
54 public:
55 TimeHelper(const TimeHelper&) = delete;
56
57 // Resets the clock based upon an NTP server. This routine must be called
58 // prior to the main system start-up to ensure all clocks are based upon
59 // an NTP server time if NTP synchronization is required. No critical
60 // section is used thus this method must be called prior to any clock
61 // routines being used.
62 static void SyncWithNtp(int64_t ntp_server_time_ms) {
63 auto& singleton = Singleton();
64 TIME_ZONE_INFORMATION time_zone;
65 GetTimeZoneInformation(&time_zone);
66 int64_t time_zone_bias_ns =
67 rtc::dchecked_cast<int64_t>(time_zone.Bias) * 60 * 1000 * 1000 * 1000;
68 singleton.app_start_time_ns_ =
69 (ntp_server_time_ms - kNTPTimeToUnixTimeEpochOffset) * 1000000 -
70 time_zone_bias_ns;
71 singleton.UpdateReferenceTime();
72 }
73
74 // Returns the number of nanoseconds that have passed since unix epoch.
75 static int64_t TicksNs() {
76 auto& singleton = Singleton();
77 int64_t result = 0;
78 LARGE_INTEGER qpcnt;
79 QueryPerformanceCounter(&qpcnt);
80 result = rtc::dchecked_cast<int64_t>(
81 (rtc::dchecked_cast<uint64_t>(qpcnt.QuadPart) * 100000 /
82 rtc::dchecked_cast<uint64_t>(singleton.os_ticks_per_second_)) *
83 10000);
84 result = singleton.app_start_time_ns_ + result -
85 singleton.time_since_os_start_ns_;
86 return result;
87 }
88
89 private:
90 TimeHelper() {
91 TIME_ZONE_INFORMATION time_zone;
92 GetTimeZoneInformation(&time_zone);
93 int64_t time_zone_bias_ns =
94 rtc::dchecked_cast<int64_t>(time_zone.Bias) * 60 * 1000 * 1000 * 1000;
95 FILETIME ft;
96 // This will give us system file in UTC format.
97 GetSystemTimeAsFileTime(&ft);
98 LARGE_INTEGER li;
99 li.HighPart = ft.dwHighDateTime;
100 li.LowPart = ft.dwLowDateTime;
101
102 app_start_time_ns_ = (li.QuadPart - kFileTimeToUnixTimeEpochOffset) * 100 -
103 time_zone_bias_ns;
104
105 UpdateReferenceTime();
106 }
107
108 static TimeHelper& Singleton() {
109 static TimeHelper singleton;
110 return singleton;
111 }
112
113 void UpdateReferenceTime() {
114 LARGE_INTEGER qpfreq;
115 QueryPerformanceFrequency(&qpfreq);
116 os_ticks_per_second_ = rtc::dchecked_cast<int64_t>(qpfreq.QuadPart);
117
118 LARGE_INTEGER qpcnt;
119 QueryPerformanceCounter(&qpcnt);
120 time_since_os_start_ns_ = rtc::dchecked_cast<int64_t>(
121 (rtc::dchecked_cast<uint64_t>(qpcnt.QuadPart) * 100000 /
122 rtc::dchecked_cast<uint64_t>(os_ticks_per_second_)) *
123 10000);
124 }
125
126 private:
127 static constexpr uint64_t kFileTimeToUnixTimeEpochOffset =
128 116444736000000000ULL;
129 static constexpr uint64_t kNTPTimeToUnixTimeEpochOffset = 2208988800000L;
130
131 // The number of nanoseconds since unix system epoch
132 int64_t app_start_time_ns_;
133 // The number of nanoseconds since the OS started
134 int64_t time_since_os_start_ns_;
135 // The OS calculated ticks per second
136 int64_t os_ticks_per_second_;
137};
138
139} // namespace
140
141void SyncWithNtp(int64_t time_from_ntp_server_ms) {
142 TimeHelper::SyncWithNtp(time_from_ntp_server_ms);
143}
144
145#endif // defined(WINUWP)
146
nissedeb95f32016-11-28 01:54:54 -0800147int64_t SystemTimeNanos() {
Taylor Brandstetterb3c68102016-05-27 14:15:43 -0700148 int64_t ticks;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000149#if defined(WEBRTC_MAC)
150 static mach_timebase_info_data_t timebase;
151 if (timebase.denom == 0) {
152 // Get the timebase if this is the first time we run.
153 // Recommended by Apple's QA1398.
andrew@webrtc.org6ae5a6d2014-09-16 01:03:29 +0000154 if (mach_timebase_info(&timebase) != KERN_SUCCESS) {
nisseeb4ca4e2017-01-12 02:24:27 -0800155 RTC_NOTREACHED();
andrew@webrtc.org6ae5a6d2014-09-16 01:03:29 +0000156 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000157 }
158 // Use timebase to convert absolute time tick units into nanoseconds.
Karl Wiberge0269cd2018-02-26 23:44:19 +0100159 const auto mul = [](uint64_t a, uint32_t b) -> int64_t {
160 RTC_DCHECK_NE(b, 0);
161 RTC_DCHECK_LE(a, std::numeric_limits<int64_t>::max() / b)
162 << "The multiplication " << a << " * " << b << " overflows";
163 return rtc::dchecked_cast<int64_t>(a * b);
164 };
165 ticks = mul(mach_absolute_time(), timebase.numer) / timebase.denom;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166#elif defined(WEBRTC_POSIX)
167 struct timespec ts;
Taylor Brandstetterb3c68102016-05-27 14:15:43 -0700168 // TODO(deadbeef): Do we need to handle the case when CLOCK_MONOTONIC is not
169 // supported?
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 clock_gettime(CLOCK_MONOTONIC, &ts);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200171 ticks = kNumNanosecsPerSec * static_cast<int64_t>(ts.tv_sec) +
172 static_cast<int64_t>(ts.tv_nsec);
Robin Raymondce1b1402018-11-22 20:10:11 -0500173#elif defined(WINUWP)
174 ticks = TimeHelper::TicksNs();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175#elif defined(WEBRTC_WIN)
176 static volatile LONG last_timegettime = 0;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200177 static volatile int64_t num_wrap_timegettime = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178 volatile LONG* last_timegettime_ptr = &last_timegettime;
179 DWORD now = timeGetTime();
180 // Atomically update the last gotten time
181 DWORD old = InterlockedExchange(last_timegettime_ptr, now);
182 if (now < old) {
Taylor Brandstetterb3c68102016-05-27 14:15:43 -0700183 // If now is earlier than old, there may have been a race between threads.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184 // 0x0fffffff ~3.1 days, the code will not take that long to execute
185 // so it must have been a wrap around.
186 if (old > 0xf0000000 && now < 0x0fffffff) {
187 num_wrap_timegettime++;
188 }
189 }
190 ticks = now + (num_wrap_timegettime << 32);
Taylor Brandstetterb3c68102016-05-27 14:15:43 -0700191 // TODO(deadbeef): Calculate with nanosecond precision. Otherwise, we're
192 // just wasting a multiply and divide when doing Time() on Windows.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000193 ticks = ticks * kNumNanosecsPerMillisec;
Erik SprĂ¥ng1c390982016-01-27 12:55:33 +0100194#else
195#error Unsupported platform.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196#endif
197 return ticks;
198}
199
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -0700200int64_t SystemTimeMillis() {
201 return static_cast<int64_t>(SystemTimeNanos() / kNumNanosecsPerMillisec);
202}
203
nissedeb95f32016-11-28 01:54:54 -0800204int64_t TimeNanos() {
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -0700205 if (g_clock) {
206 return g_clock->TimeNanos();
207 }
208 return SystemTimeNanos();
209}
210
honghaiz34b11eb2016-03-16 08:55:44 -0700211uint32_t Time32() {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200212 return static_cast<uint32_t>(TimeNanos() / kNumNanosecsPerMillisec);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213}
214
nisse1bffc1d2016-05-02 08:18:55 -0700215int64_t TimeMillis() {
nissedeb95f32016-11-28 01:54:54 -0800216 return TimeNanos() / kNumNanosecsPerMillisec;
honghaiz34b11eb2016-03-16 08:55:44 -0700217}
218
nissedeb95f32016-11-28 01:54:54 -0800219int64_t TimeMicros() {
220 return TimeNanos() / kNumNanosecsPerMicrosec;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000221}
222
Honghai Zhang82d78622016-05-06 11:29:15 -0700223int64_t TimeAfter(int64_t elapsed) {
henrikg91d6ede2015-09-17 00:24:34 -0700224 RTC_DCHECK_GE(elapsed, 0);
Honghai Zhang82d78622016-05-06 11:29:15 -0700225 return TimeMillis() + elapsed;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226}
227
Honghai Zhang82d78622016-05-06 11:29:15 -0700228int32_t TimeDiff32(uint32_t later, uint32_t earlier) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229 return later - earlier;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000230}
231
Honghai Zhang82d78622016-05-06 11:29:15 -0700232int64_t TimeDiff(int64_t later, int64_t earlier) {
honghaiz34b11eb2016-03-16 08:55:44 -0700233 return later - earlier;
234}
235
henrike@webrtc.org99b41622014-05-21 20:42:17 +0000236TimestampWrapAroundHandler::TimestampWrapAroundHandler()
sprang1b3530b2016-03-10 01:32:53 -0800237 : last_ts_(0), num_wrap_(-1) {}
henrike@webrtc.org99b41622014-05-21 20:42:17 +0000238
Peter Boström0c4e06b2015-10-07 12:23:21 +0200239int64_t TimestampWrapAroundHandler::Unwrap(uint32_t ts) {
sprang1b3530b2016-03-10 01:32:53 -0800240 if (num_wrap_ == -1) {
241 last_ts_ = ts;
242 num_wrap_ = 0;
243 return ts;
henrike@webrtc.org99b41622014-05-21 20:42:17 +0000244 }
sprang1b3530b2016-03-10 01:32:53 -0800245
246 if (ts < last_ts_) {
247 if (last_ts_ >= 0xf0000000 && ts < 0x0fffffff)
248 ++num_wrap_;
249 } else if ((ts - last_ts_) > 0xf0000000) {
250 // Backwards wrap. Unwrap with last wrap count and don't update last_ts_.
251 return ts + ((num_wrap_ - 1) << 32);
252 }
253
henrike@webrtc.org99b41622014-05-21 20:42:17 +0000254 last_ts_ = ts;
sprang1b3530b2016-03-10 01:32:53 -0800255 return ts + (num_wrap_ << 32);
henrike@webrtc.org99b41622014-05-21 20:42:17 +0000256}
257
Yves Gerey988cc082018-10-23 12:03:01 +0200258int64_t TmToSeconds(const tm& tm) {
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100259 static short int mdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
260 static short int cumul_mdays[12] = {0, 31, 59, 90, 120, 151,
261 181, 212, 243, 273, 304, 334};
262 int year = tm.tm_year + 1900;
263 int month = tm.tm_mon;
264 int day = tm.tm_mday - 1; // Make 0-based like the rest.
265 int hour = tm.tm_hour;
266 int min = tm.tm_min;
267 int sec = tm.tm_sec;
268
Yves Gerey665174f2018-06-19 15:03:05 +0200269 bool expiry_in_leap_year =
270 (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100271
272 if (year < 1970)
273 return -1;
274 if (month < 0 || month > 11)
275 return -1;
276 if (day < 0 || day >= mdays[month] + (expiry_in_leap_year && month == 2 - 1))
277 return -1;
278 if (hour < 0 || hour > 23)
279 return -1;
280 if (min < 0 || min > 59)
281 return -1;
282 if (sec < 0 || sec > 59)
283 return -1;
284
285 day += cumul_mdays[month];
286
287 // Add number of leap days between 1970 and the expiration year, inclusive.
288 day += ((year / 4 - 1970 / 4) - (year / 100 - 1970 / 100) +
289 (year / 400 - 1970 / 400));
290
291 // We will have added one day too much above if expiration is during a leap
292 // year, and expiration is in January or February.
Yves Gerey665174f2018-06-19 15:03:05 +0200293 if (expiry_in_leap_year && month <= 2 - 1) // |month| is zero based.
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100294 day -= 1;
295
296 // Combine all variables into seconds from 1970-01-01 00:00 (except |month|
297 // which was accumulated into |day| above).
Yves Gerey665174f2018-06-19 15:03:05 +0200298 return (((static_cast<int64_t>(year - 1970) * 365 + day) * 24 + hour) * 60 +
299 min) *
300 60 +
301 sec;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100302}
303
nissecdf37a92016-09-13 23:41:47 -0700304int64_t TimeUTCMicros() {
Minyue Li656d6092018-08-10 15:38:52 +0200305 if (g_clock) {
306 return g_clock->TimeNanos() / kNumNanosecsPerMicrosec;
307 }
nissecdf37a92016-09-13 23:41:47 -0700308#if defined(WEBRTC_POSIX)
309 struct timeval time;
deadbeef37f5ecf2017-02-27 14:06:41 -0800310 gettimeofday(&time, nullptr);
nissecdf37a92016-09-13 23:41:47 -0700311 // Convert from second (1.0) and microsecond (1e-6).
312 return (static_cast<int64_t>(time.tv_sec) * rtc::kNumMicrosecsPerSec +
313 time.tv_usec);
314
315#elif defined(WEBRTC_WIN)
316 struct _timeb time;
317 _ftime(&time);
318 // Convert from second (1.0) and milliseconds (1e-3).
319 return (static_cast<int64_t>(time.time) * rtc::kNumMicrosecsPerSec +
320 static_cast<int64_t>(time.millitm) * rtc::kNumMicrosecsPerMillisec);
321#endif
322}
323
Minyue Li656d6092018-08-10 15:38:52 +0200324int64_t TimeUTCMillis() {
325 return TimeUTCMicros() / kNumMicrosecsPerMillisec;
326}
327
Yves Gerey665174f2018-06-19 15:03:05 +0200328} // namespace rtc