You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

328 lines
9.5 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #include <stdint.h>
  11. #if defined(WEBRTC_POSIX)
  12. #include <sys/time.h>
  13. #if defined(WEBRTC_MAC)
  14. #include <mach/mach_time.h>
  15. #include "rtc_base/numerics/safe_conversions.h"
  16. #endif
  17. #endif
  18. #if defined(WEBRTC_WIN)
  19. // clang-format off
  20. // clang formatting would put <windows.h> last,
  21. // which leads to compilation failure.
  22. #include <windows.h>
  23. #include <mmsystem.h>
  24. #include <sys/timeb.h>
  25. // clang-format on
  26. #endif
  27. #include "rtc_base/checks.h"
  28. #include "rtc_base/time_utils.h"
  29. namespace rtc {
  30. ClockInterface* g_clock = nullptr;
  31. ClockInterface* SetClockForTesting(ClockInterface* clock) {
  32. ClockInterface* prev = g_clock;
  33. g_clock = clock;
  34. return prev;
  35. }
  36. ClockInterface* GetClockForTesting() {
  37. return g_clock;
  38. }
  39. #if defined(WINUWP)
  40. namespace {
  41. class TimeHelper final {
  42. public:
  43. TimeHelper(const TimeHelper&) = delete;
  44. // Resets the clock based upon an NTP server. This routine must be called
  45. // prior to the main system start-up to ensure all clocks are based upon
  46. // an NTP server time if NTP synchronization is required. No critical
  47. // section is used thus this method must be called prior to any clock
  48. // routines being used.
  49. static void SyncWithNtp(int64_t ntp_server_time_ms) {
  50. auto& singleton = Singleton();
  51. TIME_ZONE_INFORMATION time_zone;
  52. GetTimeZoneInformation(&time_zone);
  53. int64_t time_zone_bias_ns =
  54. rtc::dchecked_cast<int64_t>(time_zone.Bias) * 60 * 1000 * 1000 * 1000;
  55. singleton.app_start_time_ns_ =
  56. (ntp_server_time_ms - kNTPTimeToUnixTimeEpochOffset) * 1000000 -
  57. time_zone_bias_ns;
  58. singleton.UpdateReferenceTime();
  59. }
  60. // Returns the number of nanoseconds that have passed since unix epoch.
  61. static int64_t TicksNs() {
  62. auto& singleton = Singleton();
  63. int64_t result = 0;
  64. LARGE_INTEGER qpcnt;
  65. QueryPerformanceCounter(&qpcnt);
  66. result = rtc::dchecked_cast<int64_t>(
  67. (rtc::dchecked_cast<uint64_t>(qpcnt.QuadPart) * 100000 /
  68. rtc::dchecked_cast<uint64_t>(singleton.os_ticks_per_second_)) *
  69. 10000);
  70. result = singleton.app_start_time_ns_ + result -
  71. singleton.time_since_os_start_ns_;
  72. return result;
  73. }
  74. private:
  75. TimeHelper() {
  76. TIME_ZONE_INFORMATION time_zone;
  77. GetTimeZoneInformation(&time_zone);
  78. int64_t time_zone_bias_ns =
  79. rtc::dchecked_cast<int64_t>(time_zone.Bias) * 60 * 1000 * 1000 * 1000;
  80. FILETIME ft;
  81. // This will give us system file in UTC format.
  82. GetSystemTimeAsFileTime(&ft);
  83. LARGE_INTEGER li;
  84. li.HighPart = ft.dwHighDateTime;
  85. li.LowPart = ft.dwLowDateTime;
  86. app_start_time_ns_ = (li.QuadPart - kFileTimeToUnixTimeEpochOffset) * 100 -
  87. time_zone_bias_ns;
  88. UpdateReferenceTime();
  89. }
  90. static TimeHelper& Singleton() {
  91. static TimeHelper singleton;
  92. return singleton;
  93. }
  94. void UpdateReferenceTime() {
  95. LARGE_INTEGER qpfreq;
  96. QueryPerformanceFrequency(&qpfreq);
  97. os_ticks_per_second_ = rtc::dchecked_cast<int64_t>(qpfreq.QuadPart);
  98. LARGE_INTEGER qpcnt;
  99. QueryPerformanceCounter(&qpcnt);
  100. time_since_os_start_ns_ = rtc::dchecked_cast<int64_t>(
  101. (rtc::dchecked_cast<uint64_t>(qpcnt.QuadPart) * 100000 /
  102. rtc::dchecked_cast<uint64_t>(os_ticks_per_second_)) *
  103. 10000);
  104. }
  105. private:
  106. static constexpr uint64_t kFileTimeToUnixTimeEpochOffset =
  107. 116444736000000000ULL;
  108. static constexpr uint64_t kNTPTimeToUnixTimeEpochOffset = 2208988800000L;
  109. // The number of nanoseconds since unix system epoch
  110. int64_t app_start_time_ns_;
  111. // The number of nanoseconds since the OS started
  112. int64_t time_since_os_start_ns_;
  113. // The OS calculated ticks per second
  114. int64_t os_ticks_per_second_;
  115. };
  116. } // namespace
  117. void SyncWithNtp(int64_t time_from_ntp_server_ms) {
  118. TimeHelper::SyncWithNtp(time_from_ntp_server_ms);
  119. }
  120. #endif // defined(WINUWP)
  121. int64_t SystemTimeNanos() {
  122. int64_t ticks;
  123. #if defined(WEBRTC_MAC)
  124. static mach_timebase_info_data_t timebase;
  125. if (timebase.denom == 0) {
  126. // Get the timebase if this is the first time we run.
  127. // Recommended by Apple's QA1398.
  128. if (mach_timebase_info(&timebase) != KERN_SUCCESS) {
  129. RTC_NOTREACHED();
  130. }
  131. }
  132. // Use timebase to convert absolute time tick units into nanoseconds.
  133. const auto mul = [](uint64_t a, uint32_t b) -> int64_t {
  134. RTC_DCHECK_NE(b, 0);
  135. RTC_DCHECK_LE(a, std::numeric_limits<int64_t>::max() / b)
  136. << "The multiplication " << a << " * " << b << " overflows";
  137. return rtc::dchecked_cast<int64_t>(a * b);
  138. };
  139. ticks = mul(mach_absolute_time(), timebase.numer) / timebase.denom;
  140. #elif defined(WEBRTC_POSIX)
  141. struct timespec ts;
  142. // TODO(deadbeef): Do we need to handle the case when CLOCK_MONOTONIC is not
  143. // supported?
  144. clock_gettime(CLOCK_MONOTONIC, &ts);
  145. ticks = kNumNanosecsPerSec * static_cast<int64_t>(ts.tv_sec) +
  146. static_cast<int64_t>(ts.tv_nsec);
  147. #elif defined(WINUWP)
  148. ticks = TimeHelper::TicksNs();
  149. #elif defined(WEBRTC_WIN)
  150. static volatile LONG last_timegettime = 0;
  151. static volatile int64_t num_wrap_timegettime = 0;
  152. volatile LONG* last_timegettime_ptr = &last_timegettime;
  153. DWORD now = timeGetTime();
  154. // Atomically update the last gotten time
  155. DWORD old = InterlockedExchange(last_timegettime_ptr, now);
  156. if (now < old) {
  157. // If now is earlier than old, there may have been a race between threads.
  158. // 0x0fffffff ~3.1 days, the code will not take that long to execute
  159. // so it must have been a wrap around.
  160. if (old > 0xf0000000 && now < 0x0fffffff) {
  161. num_wrap_timegettime++;
  162. }
  163. }
  164. ticks = now + (num_wrap_timegettime << 32);
  165. // TODO(deadbeef): Calculate with nanosecond precision. Otherwise, we're
  166. // just wasting a multiply and divide when doing Time() on Windows.
  167. ticks = ticks * kNumNanosecsPerMillisec;
  168. #else
  169. #error Unsupported platform.
  170. #endif
  171. return ticks;
  172. }
  173. int64_t SystemTimeMillis() {
  174. return static_cast<int64_t>(SystemTimeNanos() / kNumNanosecsPerMillisec);
  175. }
  176. int64_t TimeNanos() {
  177. if (g_clock) {
  178. return g_clock->TimeNanos();
  179. }
  180. return SystemTimeNanos();
  181. }
  182. uint32_t Time32() {
  183. return static_cast<uint32_t>(TimeNanos() / kNumNanosecsPerMillisec);
  184. }
  185. int64_t TimeMillis() {
  186. return TimeNanos() / kNumNanosecsPerMillisec;
  187. }
  188. int64_t TimeMicros() {
  189. return TimeNanos() / kNumNanosecsPerMicrosec;
  190. }
  191. int64_t TimeAfter(int64_t elapsed) {
  192. RTC_DCHECK_GE(elapsed, 0);
  193. return TimeMillis() + elapsed;
  194. }
  195. int32_t TimeDiff32(uint32_t later, uint32_t earlier) {
  196. return later - earlier;
  197. }
  198. int64_t TimeDiff(int64_t later, int64_t earlier) {
  199. return later - earlier;
  200. }
  201. TimestampWrapAroundHandler::TimestampWrapAroundHandler()
  202. : last_ts_(0), num_wrap_(-1) {}
  203. int64_t TimestampWrapAroundHandler::Unwrap(uint32_t ts) {
  204. if (num_wrap_ == -1) {
  205. last_ts_ = ts;
  206. num_wrap_ = 0;
  207. return ts;
  208. }
  209. if (ts < last_ts_) {
  210. if (last_ts_ >= 0xf0000000 && ts < 0x0fffffff)
  211. ++num_wrap_;
  212. } else if ((ts - last_ts_) > 0xf0000000) {
  213. // Backwards wrap. Unwrap with last wrap count and don't update last_ts_.
  214. return ts + ((num_wrap_ - 1) << 32);
  215. }
  216. last_ts_ = ts;
  217. return ts + (num_wrap_ << 32);
  218. }
  219. int64_t TmToSeconds(const tm& tm) {
  220. static short int mdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  221. static short int cumul_mdays[12] = {0, 31, 59, 90, 120, 151,
  222. 181, 212, 243, 273, 304, 334};
  223. int year = tm.tm_year + 1900;
  224. int month = tm.tm_mon;
  225. int day = tm.tm_mday - 1; // Make 0-based like the rest.
  226. int hour = tm.tm_hour;
  227. int min = tm.tm_min;
  228. int sec = tm.tm_sec;
  229. bool expiry_in_leap_year =
  230. (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
  231. if (year < 1970)
  232. return -1;
  233. if (month < 0 || month > 11)
  234. return -1;
  235. if (day < 0 || day >= mdays[month] + (expiry_in_leap_year && month == 2 - 1))
  236. return -1;
  237. if (hour < 0 || hour > 23)
  238. return -1;
  239. if (min < 0 || min > 59)
  240. return -1;
  241. if (sec < 0 || sec > 59)
  242. return -1;
  243. day += cumul_mdays[month];
  244. // Add number of leap days between 1970 and the expiration year, inclusive.
  245. day += ((year / 4 - 1970 / 4) - (year / 100 - 1970 / 100) +
  246. (year / 400 - 1970 / 400));
  247. // We will have added one day too much above if expiration is during a leap
  248. // year, and expiration is in January or February.
  249. if (expiry_in_leap_year && month <= 2 - 1) // |month| is zero based.
  250. day -= 1;
  251. // Combine all variables into seconds from 1970-01-01 00:00 (except |month|
  252. // which was accumulated into |day| above).
  253. return (((static_cast<int64_t>(year - 1970) * 365 + day) * 24 + hour) * 60 +
  254. min) *
  255. 60 +
  256. sec;
  257. }
  258. int64_t TimeUTCMicros() {
  259. if (g_clock) {
  260. return g_clock->TimeNanos() / kNumNanosecsPerMicrosec;
  261. }
  262. #if defined(WEBRTC_POSIX)
  263. struct timeval time;
  264. gettimeofday(&time, nullptr);
  265. // Convert from second (1.0) and microsecond (1e-6).
  266. return (static_cast<int64_t>(time.tv_sec) * rtc::kNumMicrosecsPerSec +
  267. time.tv_usec);
  268. #elif defined(WEBRTC_WIN)
  269. struct _timeb time;
  270. _ftime(&time);
  271. // Convert from second (1.0) and milliseconds (1e-3).
  272. return (static_cast<int64_t>(time.time) * rtc::kNumMicrosecsPerSec +
  273. static_cast<int64_t>(time.millitm) * rtc::kNumMicrosecsPerMillisec);
  274. #endif
  275. }
  276. int64_t TimeUTCMillis() {
  277. return TimeUTCMicros() / kNumMicrosecsPerMillisec;
  278. }
  279. } // namespace rtc