Line | Count | Source |
1 | | /* |
2 | | * This file is part of mpv. |
3 | | * |
4 | | * mpv is free software; you can redistribute it and/or |
5 | | * modify it under the terms of the GNU Lesser General Public |
6 | | * License as published by the Free Software Foundation; either |
7 | | * version 2.1 of the License, or (at your option) any later version. |
8 | | * |
9 | | * mpv is distributed in the hope that it will be useful, |
10 | | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
11 | | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
12 | | * GNU Lesser General Public License for more details. |
13 | | * |
14 | | * You should have received a copy of the GNU Lesser General Public |
15 | | * License along with mpv. If not, see <http://www.gnu.org/licenses/>. |
16 | | */ |
17 | | |
18 | | #include <stdlib.h> |
19 | | #include <time.h> |
20 | | #include <limits.h> |
21 | | #include <assert.h> |
22 | | |
23 | | #include "common/common.h" |
24 | | #include "common/msg.h" |
25 | | #include "threads.h" |
26 | | #include "timer.h" |
27 | | |
28 | | static uint64_t raw_time_offset; |
29 | | static mp_once timer_init_once = MP_STATIC_ONCE_INITIALIZER; |
30 | | |
31 | | static void do_timer_init(void) |
32 | 19 | { |
33 | 19 | mp_raw_time_init(); |
34 | 19 | raw_time_offset = mp_raw_time_ns(); |
35 | 19 | mp_assert(raw_time_offset > 0); |
36 | 19 | } |
37 | | |
38 | | void mp_time_init(void) |
39 | 159k | { |
40 | 159k | mp_exec_once(&timer_init_once, do_timer_init); |
41 | 159k | } |
42 | | |
43 | | int64_t mp_time_ns(void) |
44 | 207M | { |
45 | 207M | return mp_time_ns_from_raw_time(mp_raw_time_ns()); |
46 | 207M | } |
47 | | |
48 | | int64_t mp_time_ns_from_raw_time(uint64_t raw_time) |
49 | 207M | { |
50 | 207M | return raw_time - raw_time_offset; |
51 | 207M | } |
52 | | |
53 | | double mp_time_sec(void) |
54 | 7.68M | { |
55 | 7.68M | return mp_time_ns() / 1e9; |
56 | 7.68M | } |
57 | | |
58 | | int64_t mp_time_ns_add(int64_t time_ns, double timeout_sec) |
59 | 8.05M | { |
60 | 8.05M | mp_assert(time_ns > 0); // mp_time_ns() returns strictly positive values |
61 | 8.05M | double t = MPCLAMP(timeout_sec * 1e9, -0x1p63, 0x1p63); |
62 | 8.05M | int64_t ti = t == 0x1p63 ? INT64_MAX : (int64_t)t; |
63 | 8.05M | if (ti > INT64_MAX - time_ns) |
64 | 1.39M | return INT64_MAX; |
65 | 6.65M | if (ti <= -time_ns) |
66 | 0 | return 1; |
67 | 6.65M | return time_ns + ti; |
68 | 6.65M | } |