#ifndef WEBRTC_EXCLUDE_SYSTEM_TIME
#include <stdint.h>
#include <limits>
#if defined(WEBRTC_POSIX)
#include <sys/time.h>
#if defined(WEBRTC_MAC)
#include <mach/mach_time.h>
#endif
#endif
#if defined(WEBRTC_WIN)
#include <windows.h>
#include <mmsystem.h>
#include <sys/timeb.h>
#endif
#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_conversions.h"
#include "rtc_base/system_time.h"
#include "rtc_base/time_utils.h"
namespace rtc {
int64_t SystemTimeNanos() {
int64_t ticks;
#if defined(WEBRTC_MAC)
static mach_timebase_info_data_t timebase;
if (timebase.denom == 0) {
if (mach_timebase_info(&timebase) != KERN_SUCCESS) {
RTC_DCHECK_NOTREACHED();
}
}
const auto mul = [](uint64_t a, uint32_t b) -> int64_t {
RTC_DCHECK_NE(b, 0);
RTC_DCHECK_LE(a, std::numeric_limits<int64_t>::max() / b)
<< "The multiplication " << a << " * " << b << " overflows";
return rtc::dchecked_cast<int64_t>(a * b);
};
ticks = mul(mach_absolute_time(), timebase.numer) / timebase.denom;
#elif defined(WEBRTC_POSIX)
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
ticks = kNumNanosecsPerSec * static_cast<int64_t>(ts.tv_sec) +
static_cast<int64_t>(ts.tv_nsec);
#elif defined(WINUWP)
ticks = WinUwpSystemTimeNanos();
#elif defined(WEBRTC_WIN)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-volatile"
static volatile LONG last_timegettime = 0;
static volatile int64_t num_wrap_timegettime = 0;
volatile LONG* last_timegettime_ptr = &last_timegettime;
DWORD now = timeGetTime();
DWORD old = InterlockedExchange(last_timegettime_ptr, now);
if (now < old) {
if (old > 0xf0000000 && now < 0x0fffffff) {
num_wrap_timegettime++;
}
}
ticks = now + (num_wrap_timegettime << 32);
ticks = ticks * kNumNanosecsPerMillisec;
#pragma clang diagnostic pop
#else
#error Unsupported platform.
#endif
return ticks;
}
}
#endif