libcheck: port to latest check git
[platform/upstream/gstreamer.git] / libs / gst / check / libcheck / clock_gettime.c
1 #include "libcompat.h"
2
3 #ifdef __APPLE__
4 #include <mach/clock.h>
5 #include <mach/mach.h>
6 #include <mach/mach_time.h>
7 #include <unistd.h>
8 #endif
9
10 #define NANOSECONDS_PER_SECOND 1000000000
11
12
13
14 int
15 clock_gettime (clockid_t clk_id CK_ATTRIBUTE_UNUSED, struct timespec *ts)
16 {
17
18 #ifdef __APPLE__
19   /* OS X does not have clock_gettime, use mach_absolute_time */
20
21   static mach_timebase_info_data_t sTimebaseInfo;
22   uint64_t rawTime;
23   uint64_t nanos;
24
25   rawTime = mach_absolute_time ();
26
27   /*
28    * OS X has a function to convert abs time to nano seconds: AbsoluteToNanoseconds
29    * However, the function may not be available as we may not have
30    * access to CoreServices. Because of this, we convert the abs time
31    * to nano seconds manually.
32    */
33
34   /*
35    * First grab the time base used on the system, if this is the first
36    * time we are being called. We can check if the value is uninitialized,
37    * as the denominator will be zero. 
38    */
39   if (sTimebaseInfo.denom == 0) {
40     (void) mach_timebase_info (&sTimebaseInfo);
41   }
42
43   /* 
44    * Do the conversion. We hope that the multiplication doesn't 
45    * overflow; the price you pay for working in fixed point.
46    */
47   nanos = rawTime * sTimebaseInfo.numer / sTimebaseInfo.denom;
48
49   /* 
50    * Fill in the timespec container 
51    */
52   ts->tv_sec = nanos / NANOSECONDS_PER_SECOND;
53   ts->tv_nsec = nanos - (ts->tv_sec * NANOSECONDS_PER_SECOND);
54 #else
55   /* 
56    * As there is no function to fall back onto to get the current
57    * time, zero out the time so the caller will have a sane value. 
58    */
59   ts->tv_sec = 0;
60   ts->tv_nsec = 0;
61 #endif
62
63   return 0;
64 }