1#ifndef ANDROID_DVR_CLOCK_NS_H_
2#define ANDROID_DVR_CLOCK_NS_H_
3
4#include <stdint.h>
5#include <time.h>
6
7namespace android {
8namespace dvr {
9
10constexpr int64_t kNanosPerSecond = 1000000000ll;
11
12// Returns the standard Dream OS monotonic system time that corresponds with all
13// timestamps found in Dream OS APIs.
14static inline timespec GetSystemClock() {
15  timespec t;
16  clock_gettime(CLOCK_MONOTONIC, &t);
17  return t;
18}
19
20static inline timespec GetSystemClockRaw() {
21  timespec t;
22  clock_gettime(CLOCK_MONOTONIC_RAW, &t);
23  return t;
24}
25
26static inline int64_t GetSystemClockNs() {
27  timespec t = GetSystemClock();
28  int64_t ns = kNanosPerSecond * (int64_t)t.tv_sec + (int64_t)t.tv_nsec;
29  return ns;
30}
31
32static inline int64_t GetSystemClockRawNs() {
33  timespec t = GetSystemClockRaw();
34  int64_t ns = kNanosPerSecond * (int64_t)t.tv_sec + (int64_t)t.tv_nsec;
35  return ns;
36}
37
38static inline double NsToSec(int64_t nanoseconds) {
39  return nanoseconds / static_cast<double>(kNanosPerSecond);
40}
41
42static inline double GetSystemClockSec() { return NsToSec(GetSystemClockNs()); }
43
44static inline double GetSystemClockMs() { return GetSystemClockSec() * 1000.0; }
45
46// Converts a nanosecond timestamp to a timespec. Based on the kernel function
47// of the same name.
48static inline timespec NsToTimespec(int64_t ns) {
49  timespec t;
50  int32_t remainder;
51
52  t.tv_sec = ns / kNanosPerSecond;
53  remainder = ns % kNanosPerSecond;
54  if (remainder < 0) {
55    t.tv_nsec--;
56    remainder += kNanosPerSecond;
57  }
58  t.tv_nsec = remainder;
59
60  return t;
61}
62
63// Timestamp comparison functions that handle wrapping values correctly.
64static inline bool TimestampLT(int64_t a, int64_t b) {
65  return static_cast<int64_t>(static_cast<uint64_t>(a) -
66                              static_cast<uint64_t>(b)) < 0;
67}
68static inline bool TimestampLE(int64_t a, int64_t b) {
69  return static_cast<int64_t>(static_cast<uint64_t>(a) -
70                              static_cast<uint64_t>(b)) <= 0;
71}
72static inline bool TimestampGT(int64_t a, int64_t b) {
73  return static_cast<int64_t>(static_cast<uint64_t>(a) -
74                              static_cast<uint64_t>(b)) > 0;
75}
76static inline bool TimestampGE(int64_t a, int64_t b) {
77  return static_cast<int64_t>(static_cast<uint64_t>(a) -
78                              static_cast<uint64_t>(b)) >= 0;
79}
80
81}  // namespace dvr
82}  // namespace android
83
84#endif  // ANDROID_DVR_CLOCK_NS_H_
85