qml: Create MediaGroupDisplay
[vlc.git] / compat / clock_nanosleep.c
blob494540b8b95776cd12fd66f2e725020b2d26e954
1 /*****************************************************************************
2 * clock_nanosleep.c: POSIX clock_nanosleep() replacement
3 *****************************************************************************
4 * Copyright © 2020 VLC authors and VideoLAN
6 * Author: Marvin Scholz <epirat07 at gmail dot com>
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU Lesser General Public License as published by
10 * the Free Software Foundation; either version 2.1 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21 *****************************************************************************/
23 #ifdef __APPLE__
25 #ifdef HAVE_CONFIG_H
26 # include <config.h>
27 #endif
29 #include <assert.h>
30 #include <pthread.h>
31 #include <sys/errno.h>
32 #include <sys/types.h>
33 #include <sys/time.h>
34 #include <sys/sysctl.h>
35 #include <mach/clock_types.h>
37 int clock_nanosleep(clockid_t clock_id, int flags,
38 const struct timespec *rqtp, struct timespec *rmtp)
40 // Validate timespec
41 if (rqtp == NULL || rqtp->tv_sec < 0 ||
42 rqtp->tv_nsec < 0 || (unsigned long)rqtp->tv_nsec >= NSEC_PER_SEC) {
43 errno = EINVAL;
44 return -1;
47 // Validate clock
48 switch (clock_id) {
49 case CLOCK_MONOTONIC:
50 case CLOCK_REALTIME:
51 break;
52 default:
53 errno = EINVAL;
54 return -1;
57 if (flags == TIMER_ABSTIME) {
58 struct timespec ts_rel;
59 struct timespec ts_now;
61 do {
62 // Get current time with requested clock
63 if (clock_gettime(clock_id, &ts_now) != 0)
64 return -1;
66 // Calculate relative timespec
67 ts_rel.tv_sec = rqtp->tv_sec - ts_now.tv_sec;
68 ts_rel.tv_nsec = rqtp->tv_nsec - ts_now.tv_nsec;
69 if (ts_rel.tv_nsec < 0) {
70 ts_rel.tv_sec -= 1;
71 ts_rel.tv_nsec += NSEC_PER_SEC;
74 // Check if time already elapsed
75 if (ts_rel.tv_sec < 0 || (ts_rel.tv_sec == 0 && ts_rel.tv_nsec == 0)) {
76 pthread_testcancel();
77 return 0;
80 // "The absolute clock_nanosleep() function has no effect on the
81 // structure referenced by rmtp", so do not pass rmtp here
82 } while (nanosleep(&ts_rel, NULL) == 0);
84 // If nanosleep failed or was interrupted by a signal,
85 // return so the caller can handle it appropriately
86 return -1;
87 } else if (flags == 0) {
88 return nanosleep(rqtp, rmtp);
89 } else {
90 // Invalid flags
91 errno = EINVAL;
92 return -1;
96 #endif