• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef OBOE_AUDIO_CLOCK_H
18 #define OBOE_AUDIO_CLOCK_H
19 
20 #include <sys/types.h>
21 #include <ctime>
22 #include "oboe/Definitions.h"
23 
24 namespace oboe {
25 
26 // TODO: Move this class into the public headers because it is useful when calculating stream latency
27 class AudioClock {
28 public:
29     static int64_t getNanoseconds(clockid_t clockId = CLOCK_MONOTONIC) {
30         struct timespec time;
31         int result = clock_gettime(clockId, &time);
32         if (result < 0) {
33             return result;
34         }
35         return (time.tv_sec * kNanosPerSecond) + time.tv_nsec;
36     }
37 
38     /**
39      * Sleep until the specified time.
40      *
41      * @param nanoTime time to wake up
42      * @param clockId CLOCK_MONOTONIC is default
43      * @return 0 or a negative error, eg. -EINTR
44      */
45 
46     static int sleepUntilNanoTime(int64_t nanoTime, clockid_t clockId = CLOCK_MONOTONIC) {
47         struct timespec time;
48         time.tv_sec = nanoTime / kNanosPerSecond;
49         time.tv_nsec = nanoTime - (time.tv_sec * kNanosPerSecond);
50         return 0 - clock_nanosleep(clockId, TIMER_ABSTIME, &time, NULL);
51     }
52 
53     /**
54      * Sleep for the specified number of nanoseconds in real-time.
55      * Return immediately with 0 if a negative nanoseconds is specified.
56      *
57      * @param nanoseconds time to sleep
58      * @param clockId CLOCK_REALTIME is default
59      * @return 0 or a negative error, eg. -EINTR
60      */
61 
62     static int sleepForNanos(int64_t nanoseconds, clockid_t clockId = CLOCK_REALTIME) {
63         if (nanoseconds > 0) {
64             struct timespec time;
65             time.tv_sec = nanoseconds / kNanosPerSecond;
66             time.tv_nsec = nanoseconds - (time.tv_sec * kNanosPerSecond);
67             return 0 - clock_nanosleep(clockId, 0, &time, NULL);
68         }
69         return 0;
70     }
71 };
72 
73 } // namespace oboe
74 
75 #endif //OBOE_AUDIO_CLOCK_H
76