| 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 "system_wrappers/include/clock.h" |
| 12 |
| 13 | #include "system_wrappers/include/field_trial.h" |
| 14 |
| 15 | #if defined(WEBRTC_WIN) |
| 16 |
| 17 | // Windows needs to be included before mmsystem.h |
| 18 | #include "rtc_base/win32.h" |
| 19 |
| 20 | #include <mmsystem.h> |
| 21 |
| 22 |
| 23 | #elif defined(WEBRTC_POSIX) |
| 24 |
| 25 | #include <sys/time.h> |
| 26 | #include <time.h> |
| 27 |
| 28 | #endif // defined(WEBRTC_POSIX) |
| 29 |
| 30 | #include "rtc_base/synchronization/mutex.h" |
| 31 | #include "rtc_base/time_utils.h" |
| 32 |
| 33 | namespace webrtc { |
| 34 | namespace { |
| 35 |
| 36 | int64_t NtpOffsetUsCalledOnce() { |
| 37 | constexpr int64_t kNtpJan1970Sec = 2208988800; |
| 38 | int64_t clock_time = rtc::TimeMicros(); |
| 39 | int64_t utc_time = rtc::TimeUTCMicros(); |
| 40 | return utc_time - clock_time + kNtpJan1970Sec * rtc::kNumMicrosecsPerSec; |
| 41 | } |
| 42 |
| 43 | NtpTime TimeMicrosToNtp(int64_t time_us) { |
| 44 | static int64_t ntp_offset_us = NtpOffsetUsCalledOnce(); |
| 45 |
| 46 | int64_t time_ntp_us = time_us + ntp_offset_us; |
| 47 | RTC_DCHECK_GE(time_ntp_us, 0); // Time before year 1900 is unsupported. |
| 48 |
| 49 | // Convert seconds to uint32 through uint64 for a well-defined cast. |
| 50 | // A wrap around, which will happen in 2036, is expected for NTP time. |
| 51 | uint32_t ntp_seconds = |
| 52 | static_cast<uint64_t>(time_ntp_us / rtc::kNumMicrosecsPerSec); |
| 53 |
| 54 | // Scale fractions of the second to NTP resolution. |
| 55 | constexpr int64_t kNtpFractionsInSecond = 1LL << 32; |
| 56 | int64_t us_fractions = time_ntp_us % rtc::kNumMicrosecsPerSec; |
| 57 | uint32_t ntp_fractions = |
| 58 | us_fractions * kNtpFractionsInSecond / rtc::kNumMicrosecsPerSec; |
| 59 |
| 60 | return NtpTime(ntp_seconds, ntp_fractions); |
| 61 | } |
| 62 |
| 63 | void GetSecondsAndFraction(const timeval& time, |
| 64 | uint32_t* seconds, |
| 65 | double* fraction) { |
| 66 | *seconds = time.tv_sec + kNtpJan1970; |
| 67 | *fraction = time.tv_usec / 1e6; |
| 68 |
| 69 | while (*fraction >= 1) { |
| 70 | --*fraction; |
| 71 | ++*seconds; |
| 72 | } |
| 73 | while (*fraction < 0) { |
| 74 | ++*fraction; |
| 75 | --*seconds; |
| 76 | } |
| 77 | } |
| 78 |
| 79 | } // namespace |
| 80 |
| 81 | class RealTimeClock : public Clock { |
| 82 | public: |
| 83 | RealTimeClock() |
| 84 | : use_system_independent_ntp_time_(!field_trial::IsEnabled( |
| 85 | "WebRTC-SystemIndependentNtpTimeKillSwitch")) {} |
| 86 |
| 87 | Timestamp CurrentTime() override { |
| 88 | return Timestamp::Micros(rtc::TimeMicros()); |
| 89 | } |
| 90 |
| 91 | NtpTime CurrentNtpTime() override { |
| 92 | return use_system_independent_ntp_time_ ? TimeMicrosToNtp(rtc::TimeMicros()) |
| 93 | : SystemDependentNtpTime(); |
| 94 | } |
| 95 |
| 96 | NtpTime ConvertTimestampToNtpTime(Timestamp timestamp) override { |
| 97 | // This method does not check `use_system_independent_ntp_time_` because |
| 98 | // all callers never used the old behavior of `CurrentNtpTime`. |
| 99 | return TimeMicrosToNtp(timestamp.us()); |
| 100 | } |
| 101 |
| 102 | protected: |
| 103 | virtual timeval CurrentTimeVal() = 0; |
| 104 |
| 105 | private: |
| 106 | NtpTime SystemDependentNtpTime() { |
| 107 | uint32_t seconds; |
| 108 | double fraction; |
| 109 | GetSecondsAndFraction(CurrentTimeVal(), &seconds, &fraction); |
| 110 |
| 111 | return NtpTime(seconds, static_cast<uint32_t>( |
| 112 | fraction * kMagicNtpFractionalUnit + 0.5)); |
| 113 | } |
| 114 |
| 115 | bool use_system_independent_ntp_time_; |
| 116 | }; |
| 117 |
| 118 | #if defined(WINUWP) |
| 119 | class WinUwpRealTimeClock final : public RealTimeClock { |
| 120 | public: |
| 121 | WinUwpRealTimeClock() = default; |
| 122 | ~WinUwpRealTimeClock() override {} |
| 123 |
| 124 | protected: |
| 125 | timeval CurrentTimeVal() override { |
| 126 | // The rtc::WinUwpSystemTimeNanos() method is already time offset from a |
| 127 | // base epoch value and might as be synchronized against an NTP time server |
| 128 | // as an added bonus. |
| 129 | auto nanos = rtc::WinUwpSystemTimeNanos(); |
| 130 |
| 131 | struct timeval tv; |
| 132 |
| 133 | tv.tv_sec = rtc::dchecked_cast<long>(nanos / 1000000000); |
| 134 | tv.tv_usec = rtc::dchecked_cast<long>(nanos / 1000); |
| 135 |
| 136 | return tv; |
| 137 | } |
| 138 | }; |
| 139 |
| 140 | #elif defined(WEBRTC_WIN) |
| 141 | // TODO(pbos): Consider modifying the implementation to synchronize itself |
| 142 | // against system time (update ref_point_) periodically to |
| 143 | // prevent clock drift. |
| 144 | class WindowsRealTimeClock : public RealTimeClock { |
| 145 | public: |
| 146 | WindowsRealTimeClock() |
| 147 | : last_time_ms_(0), |
| 148 | num_timer_wraps_(0), |
| 149 | ref_point_(GetSystemReferencePoint()) {} |
| 150 |
| 151 | ~WindowsRealTimeClock() override {} |
| 152 |
| 153 | protected: |
| 154 | struct ReferencePoint { |
| 155 | FILETIME file_time; |
| 156 | LARGE_INTEGER counter_ms; |
| 157 | }; |
| 158 |
| 159 | timeval CurrentTimeVal() override { |
| 160 | const uint64_t FILETIME_1970 = 0x019db1ded53e8000; |
| 161 |
| 162 | FILETIME StartTime; |
| 163 | uint64_t Time; |
| 164 | struct timeval tv; |
| 165 |
| 166 | // We can't use query performance counter since they can change depending on |
| 167 | // speed stepping. |
| 168 | GetTime(&StartTime); |
| 169 |
| 170 | Time = (((uint64_t)StartTime.dwHighDateTime) << 32) + |
| 171 | (uint64_t)StartTime.dwLowDateTime; |
| 172 |
| 173 | // Convert the hecto-nano second time to tv format. |
| 174 | Time -= FILETIME_1970; |
| 175 |
| 176 | tv.tv_sec = (uint32_t)(Time / (uint64_t)10000000); |
| 177 | tv.tv_usec = (uint32_t)((Time % (uint64_t)10000000) / 10); |
| 178 | return tv; |
| 179 | } |
| 180 |
| 181 | void GetTime(FILETIME* current_time) { |
| 182 | DWORD t; |
| 183 | LARGE_INTEGER elapsed_ms; |
| 184 | { |
| 185 | MutexLock lock(&mutex_); |
| 186 | // time MUST be fetched inside the critical section to avoid non-monotonic |
| 187 | // last_time_ms_ values that'll register as incorrect wraparounds due to |
| 188 | // concurrent calls to GetTime. |
| 189 | t = timeGetTime(); |
| 190 | if (t < last_time_ms_) |
| 191 | num_timer_wraps_++; |
| 192 | last_time_ms_ = t; |
| 193 | elapsed_ms.HighPart = num_timer_wraps_; |
| 194 | } |
| 195 | elapsed_ms.LowPart = t; |
| 196 | elapsed_ms.QuadPart = elapsed_ms.QuadPart - ref_point_.counter_ms.QuadPart; |
| 197 |
| 198 | // Translate to 100-nanoseconds intervals (FILETIME resolution) |
| 199 | // and add to reference FILETIME to get current FILETIME. |
| 200 | ULARGE_INTEGER filetime_ref_as_ul; |
| 201 | filetime_ref_as_ul.HighPart = ref_point_.file_time.dwHighDateTime; |
| 202 | filetime_ref_as_ul.LowPart = ref_point_.file_time.dwLowDateTime; |
| 203 | filetime_ref_as_ul.QuadPart += |
| 204 | static_cast<ULONGLONG>((elapsed_ms.QuadPart) * 1000 * 10); |
| 205 |
| 206 | // Copy to result |
| 207 | current_time->dwHighDateTime = filetime_ref_as_ul.HighPart; |
| 208 | current_time->dwLowDateTime = filetime_ref_as_ul.LowPart; |
| 209 | } |
| 210 |
| 211 | static ReferencePoint GetSystemReferencePoint() { |
| 212 | ReferencePoint ref = {}; |
| 213 | FILETIME ft0 = {}; |
| 214 | FILETIME ft1 = {}; |
| 215 | // Spin waiting for a change in system time. As soon as this change happens, |
| 216 | // get the matching call for timeGetTime() as soon as possible. This is |
| 217 | // assumed to be the most accurate offset that we can get between |
| 218 | // timeGetTime() and system time. |
| 219 |
| 220 | // Set timer accuracy to 1 ms. |
| 221 | timeBeginPeriod(1); |
| 222 | GetSystemTimeAsFileTime(&ft0); |
| 223 | do { |
| 224 | GetSystemTimeAsFileTime(&ft1); |
| 225 |
| 226 | ref.counter_ms.QuadPart = timeGetTime(); |
| 227 | Sleep(0); |
| 228 | } while ((ft0.dwHighDateTime == ft1.dwHighDateTime) && |
| 229 | (ft0.dwLowDateTime == ft1.dwLowDateTime)); |
| 230 | ref.file_time = ft1; |
| 231 | timeEndPeriod(1); |
| 232 | return ref; |
| 233 | } |
| 234 |
| 235 | Mutex mutex_; |
| 236 | DWORD last_time_ms_; |
| 237 | LONG num_timer_wraps_; |
| 238 | const ReferencePoint ref_point_; |
| 239 | }; |
| 240 |
| 241 | #elif defined(WEBRTC_POSIX) |
| 242 | class UnixRealTimeClock : public RealTimeClock { |
| 243 | public: |
| 244 | UnixRealTimeClock() {} |
| 245 |
| 246 | ~UnixRealTimeClock() override {} |
| 247 |
| 248 | protected: |
| 249 | timeval CurrentTimeVal() override { |
| 250 | struct timeval tv; |
| 251 | gettimeofday(&tv, nullptr); |
| 252 | return tv; |
| 253 | } |
| 254 | }; |
| 255 | #endif // defined(WEBRTC_POSIX) |
| 256 |
| 257 | Clock* Clock::GetRealTimeClock() { |
| 258 | #if defined(WINUWP) |
| 259 | static Clock* const clock = new WinUwpRealTimeClock(); |
| 260 | #elif defined(WEBRTC_WIN) |
| 261 | static Clock* const clock = new WindowsRealTimeClock(); |
| 262 | #elif defined(WEBRTC_POSIX) |
| 263 | static Clock* const clock = new UnixRealTimeClock(); |
| 264 | #else |
| 265 | static Clock* const clock = nullptr; |
| 266 | #endif |
| 267 | return clock; |
| 268 | } |
| 269 |
| 270 | SimulatedClock::SimulatedClock(int64_t initial_time_us) |
| 271 | : time_us_(initial_time_us) {} |
| 272 |
| 273 | SimulatedClock::SimulatedClock(Timestamp initial_time) |
| 274 | : SimulatedClock(initial_time.us()) {} |
| 275 |
| 276 | SimulatedClock::~SimulatedClock() {} |
| 277 |
| 278 | Timestamp SimulatedClock::CurrentTime() { |
| 279 | return Timestamp::Micros(time_us_.load(std::memory_order_relaxed)); |
| 280 | } |
| 281 |
| 282 | NtpTime SimulatedClock::ConvertTimestampToNtpTime(Timestamp timestamp) { |
| 283 | int64_t now_us = timestamp.us(); |
| 284 | uint32_t seconds = (now_us / 1'000'000) + kNtpJan1970; |
| 285 | uint32_t fractions = static_cast<uint32_t>( |
| 286 | (now_us % 1'000'000) * kMagicNtpFractionalUnit / 1'000'000); |
| 287 | return NtpTime(seconds, fractions); |
| 288 | } |
| 289 |
| 290 | void SimulatedClock::AdvanceTimeMilliseconds(int64_t milliseconds) { |
| 291 | AdvanceTime(TimeDelta::Millis(milliseconds)); |
| 292 | } |
| 293 |
| 294 | void SimulatedClock::AdvanceTimeMicroseconds(int64_t microseconds) { |
| 295 | AdvanceTime(TimeDelta::Micros(microseconds)); |
| 296 | } |
| 297 |
| 298 | // TODO(bugs.webrtc.org(12102): It's desirable to let a single thread own |
| 299 | // advancement of the clock. We could then replace this read-modify-write |
| 300 | // operation with just a thread checker. But currently, that breaks a couple of |
| 301 | // tests, in particular, RepeatingTaskTest.ClockIntegration and |
| 302 | // CallStatsTest.LastProcessedRtt. |
| 303 | void SimulatedClock::AdvanceTime(TimeDelta delta) { |
| 304 | time_us_.fetch_add(delta.us(), std::memory_order_relaxed); |
| 305 | } |
| 306 |
| 307 | } // namespace webrtc |
| 308 |