]> git.sesse.net Git - vlc/blob - src/misc/mtime.c
NTPtime64() returns an NTP timestamp
[vlc] / src / misc / mtime.c
1 /*****************************************************************************
2  * mtime.c: high resolution time management functions
3  * Functions are prototyped in vlc_mtime.h.
4  *****************************************************************************
5  * Copyright (C) 1998-2004 the VideoLAN team
6  * Copyright © 2006-2007 Rémi Denis-Courmont
7  * $Id$
8  *
9  * Authors: Vincent Seguin <seguin@via.ecp.fr>
10  *          Rémi Denis-Courmont <rem$videolan,org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #include <vlc/vlc.h>
32
33 #include <stdio.h>                                              /* sprintf() */
34 #include <time.h>                      /* clock_gettime(), clock_nanosleep() */
35 #include <stdlib.h>                                               /* lldiv() */
36 #include <assert.h>
37
38
39 #if defined( PTH_INIT_IN_PTH_H )                                  /* GNU Pth */
40 #   include <pth.h>
41 #endif
42
43 #ifdef HAVE_UNISTD_H
44 #   include <unistd.h>                                           /* select() */
45 #endif
46
47 #ifdef HAVE_KERNEL_OS_H
48 #   include <kernel/OS.h>
49 #endif
50
51 #if defined( WIN32 ) || defined( UNDER_CE )
52 #   include <windows.h>
53 #else
54 #   include <sys/time.h>
55 #endif
56
57 #if defined(HAVE_NANOSLEEP) && !defined(HAVE_STRUCT_TIMESPEC)
58 struct timespec
59 {
60     time_t  tv_sec;
61     int32_t tv_nsec;
62 };
63 #endif
64
65 #if defined(HAVE_NANOSLEEP) && !defined(HAVE_DECL_NANOSLEEP)
66 int nanosleep(struct timespec *, struct timespec *);
67 #endif
68
69 /**
70  * Return a date in a readable format
71  *
72  * This function converts a mtime date into a string.
73  * psz_buffer should be a buffer long enough to store the formatted
74  * date.
75  * \param date to be converted
76  * \param psz_buffer should be a buffer at least MSTRTIME_MAX_SIZE characters
77  * \return psz_buffer is returned so this can be used as printf parameter.
78  */
79 char *mstrtime( char *psz_buffer, mtime_t date )
80 {
81     static mtime_t ll1000 = 1000, ll60 = 60, ll24 = 24;
82
83     snprintf( psz_buffer, MSTRTIME_MAX_SIZE, "%02d:%02d:%02d-%03d.%03d",
84              (int) (date / (ll1000 * ll1000 * ll60 * ll60) % ll24),
85              (int) (date / (ll1000 * ll1000 * ll60) % ll60),
86              (int) (date / (ll1000 * ll1000) % ll60),
87              (int) (date / ll1000 % ll1000),
88              (int) (date % ll1000) );
89     return( psz_buffer );
90 }
91
92 /**
93  * Convert seconds to a time in the format h:mm:ss.
94  *
95  * This function is provided for any interface function which need to print a
96  * time string in the format h:mm:ss
97  * date.
98  * \param secs  the date to be converted
99  * \param psz_buffer should be a buffer at least MSTRTIME_MAX_SIZE characters
100  * \return psz_buffer is returned so this can be used as printf parameter.
101  */
102 char *secstotimestr( char *psz_buffer, int i_seconds )
103 {
104     snprintf( psz_buffer, MSTRTIME_MAX_SIZE, "%d:%2.2d:%2.2d",
105               (int) (i_seconds / (60 *60)),
106               (int) ((i_seconds / 60) % 60),
107               (int) (i_seconds % 60) );
108     return( psz_buffer );
109 }
110
111
112 /**
113  * Return high precision date
114  *
115  * Uses the gettimeofday() function when possible (1 MHz resolution) or the
116  * ftime() function (1 kHz resolution).
117  */
118 mtime_t mdate( void )
119 {
120 #if defined (HAVE_CLOCK_NANOSLEEP)
121     struct timespec ts;
122
123 # if (_POSIX_MONOTONIC_CLOCK - 0 >= 0)
124     /* Try to use POSIX monotonic clock if available */
125     if( clock_gettime( CLOCK_MONOTONIC, &ts ) )
126 # endif
127         /* Run-time fallback to real-time clock (always available) */
128         (void)clock_gettime( CLOCK_REALTIME, &ts );
129
130     return ((mtime_t)ts.tv_sec * (mtime_t)1000000)
131            + (mtime_t)(ts.tv_nsec / 1000);
132
133 #elif defined( HAVE_KERNEL_OS_H )
134     return( real_time_clock_usecs() );
135
136 #elif defined( WIN32 ) || defined( UNDER_CE )
137     /* We don't need the real date, just the value of a high precision timer */
138     static mtime_t freq = I64C(-1);
139
140     if( freq == I64C(-1) )
141     {
142         /* Extract from the Tcl source code:
143          * (http://www.cs.man.ac.uk/fellowsd-bin/TIP/7.html)
144          *
145          * Some hardware abstraction layers use the CPU clock
146          * in place of the real-time clock as a performance counter
147          * reference.  This results in:
148          *    - inconsistent results among the processors on
149          *      multi-processor systems.
150          *    - unpredictable changes in performance counter frequency
151          *      on "gearshift" processors such as Transmeta and
152          *      SpeedStep.
153          * There seems to be no way to test whether the performance
154          * counter is reliable, but a useful heuristic is that
155          * if its frequency is 1.193182 MHz or 3.579545 MHz, it's
156          * derived from a colorburst crystal and is therefore
157          * the RTC rather than the TSC.  If it's anything else, we
158          * presume that the performance counter is unreliable.
159          */
160         LARGE_INTEGER buf;
161
162         freq = ( QueryPerformanceFrequency( &buf ) &&
163                  (buf.QuadPart == I64C(1193182) || buf.QuadPart == I64C(3579545) ) )
164                ? buf.QuadPart : 0;
165     }
166
167     if( freq != 0 )
168     {
169         LARGE_INTEGER counter;
170         QueryPerformanceCounter (&counter);
171
172         /* Convert to from (1/freq) to microsecond resolution */
173         /* We need to split the division to avoid 63-bits overflow */
174         lldiv_t d = lldiv (counter.QuadPart, freq);
175
176         return (d.quot * 1000000)
177              + ((d.rem * 1000000) / freq);
178     }
179     else
180     {
181         /* Fallback on GetTickCount() which has a milisecond resolution
182          * (actually, best case is about 10 ms resolution)
183          * GetTickCount() only returns a DWORD thus will wrap after
184          * about 49.7 days so we try to detect the wrapping. */
185
186         static CRITICAL_SECTION date_lock;
187         static mtime_t i_previous_time = I64C(-1);
188         static int i_wrap_counts = -1;
189         mtime_t usec_time;
190
191         if( i_wrap_counts == -1 )
192         {
193             /* Initialization */
194             i_previous_time = I64C(1000) * GetTickCount();
195             InitializeCriticalSection( &date_lock );
196             i_wrap_counts = 0;
197         }
198
199         EnterCriticalSection( &date_lock );
200         usec_time = I64C(1000) *
201             (i_wrap_counts * I64C(0x100000000) + GetTickCount());
202         if( i_previous_time > usec_time )
203         {
204             /* Counter wrapped */
205             i_wrap_counts++;
206             usec_time += I64C(0x100000000) * 1000;
207         }
208         i_previous_time = usec_time;
209         LeaveCriticalSection( &date_lock );
210
211         return usec_time;
212     }
213 #else
214     struct timeval tv_date;
215
216     /* gettimeofday() cannot fail given &tv_date is a valid address */
217     (void)gettimeofday( &tv_date, NULL );
218     return( (mtime_t) tv_date.tv_sec * 1000000 + (mtime_t) tv_date.tv_usec );
219 #endif
220 }
221
222 /**
223  * Wait for a date
224  *
225  * This function uses select() and an system date function to wake up at a
226  * precise date. It should be used for process synchronization. If current date
227  * is posterior to wished date, the function returns immediately.
228  * \param date The date to wake up at
229  */
230 void mwait( mtime_t date )
231 {
232 #if defined (HAVE_CLOCK_NANOSLEEP)
233     lldiv_t d = lldiv( date, 1000000 );
234     struct timespec ts = { d.quot, d.rem * 1000 };
235
236 # if (_POSIX_MONOTONIC_CLOCK - 0 >= 0)
237     if( clock_nanosleep( CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL ) )
238 # endif
239         clock_nanosleep( CLOCK_REALTIME, TIMER_ABSTIME, &ts, NULL );
240 #else
241
242     mtime_t delay = date - mdate();
243     if( delay > 0 )
244         msleep( delay );
245
246 #endif
247 }
248
249 /**
250  * More precise sleep()
251  *
252  * Portable usleep() function.
253  * \param delay the amount of time to sleep
254  */
255 void msleep( mtime_t delay )
256 {
257 #if defined( HAVE_CLOCK_NANOSLEEP ) 
258     lldiv_t d = lldiv( delay, 1000000 );
259     struct timespec ts = { d.quot, d.rem * 1000 };
260
261 # if (_POSIX_MONOTONIC_CLOCK - 0 >= 0)
262     if( clock_nanosleep( CLOCK_MONOTONIC, 0, &ts, NULL ) )
263 # endif
264         clock_nanosleep( CLOCK_REALTIME, 0, &ts, NULL );
265
266 #elif defined( HAVE_KERNEL_OS_H )
267     snooze( delay );
268
269 #elif defined( PTH_INIT_IN_PTH_H )
270     pth_usleep( delay );
271
272 #elif defined( ST_INIT_IN_ST_H )
273     st_usleep( delay );
274
275 #elif defined( WIN32 ) || defined( UNDER_CE )
276     Sleep( (int) (delay / 1000) );
277
278 #elif defined( HAVE_NANOSLEEP )
279     struct timespec ts_delay;
280
281     ts_delay.tv_sec = delay / 1000000;
282     ts_delay.tv_nsec = (delay % 1000000) * 1000;
283
284     nanosleep( &ts_delay, NULL );
285
286 #else
287     struct timeval tv_delay;
288
289     tv_delay.tv_sec = delay / 1000000;
290     tv_delay.tv_usec = delay % 1000000;
291
292     /* select() return value should be tested, since several possible errors
293      * can occur. However, they should only happen in very particular occasions
294      * (i.e. when a signal is sent to the thread, or when memory is full), and
295      * can be ignored. */
296     select( 0, NULL, NULL, NULL, &tv_delay );
297 #endif
298 }
299
300 /*
301  * Date management (internal and external)
302  */
303
304 /**
305  * Initialize a date_t.
306  *
307  * \param date to initialize
308  * \param divider (sample rate) numerator
309  * \param divider (sample rate) denominator
310  */
311
312 void date_Init( date_t *p_date, uint32_t i_divider_n, uint32_t i_divider_d )
313 {
314     p_date->date = 0;
315     p_date->i_divider_num = i_divider_n;
316     p_date->i_divider_den = i_divider_d;
317     p_date->i_remainder = 0;
318 }
319
320 /**
321  * Change a date_t.
322  *
323  * \param date to change
324  * \param divider (sample rate) numerator
325  * \param divider (sample rate) denominator
326  */
327
328 void date_Change( date_t *p_date, uint32_t i_divider_n, uint32_t i_divider_d )
329 {
330     p_date->i_divider_num = i_divider_n;
331     p_date->i_divider_den = i_divider_d;
332 }
333
334 /**
335  * Set the date value of a date_t.
336  *
337  * \param date to set
338  * \param date value
339  */
340 void date_Set( date_t *p_date, mtime_t i_new_date )
341 {
342     p_date->date = i_new_date;
343     p_date->i_remainder = 0;
344 }
345
346 /**
347  * Get the date of a date_t
348  *
349  * \param date to get
350  * \return date value
351  */
352 mtime_t date_Get( const date_t *p_date )
353 {
354     return p_date->date;
355 }
356
357 /**
358  * Move forwards or backwards the date of a date_t.
359  *
360  * \param date to move
361  * \param difference value
362  */
363 void date_Move( date_t *p_date, mtime_t i_difference )
364 {
365     p_date->date += i_difference;
366 }
367
368 /**
369  * Increment the date and return the result, taking into account
370  * rounding errors.
371  *
372  * \param date to increment
373  * \param incrementation in number of samples
374  * \return date value
375  */
376 mtime_t date_Increment( date_t *p_date, uint32_t i_nb_samples )
377 {
378     mtime_t i_dividend = (mtime_t)i_nb_samples * 1000000;
379     p_date->date += i_dividend / p_date->i_divider_num * p_date->i_divider_den;
380     p_date->i_remainder += (int)(i_dividend % p_date->i_divider_num);
381
382     if( p_date->i_remainder >= p_date->i_divider_num )
383     {
384         /* This is Bresenham algorithm. */
385         p_date->date += p_date->i_divider_den;
386         p_date->i_remainder -= p_date->i_divider_num;
387     }
388
389     return p_date->date;
390 }
391
392 /**
393  * @return NTP 64-bits timestamp in host byte order.
394  */
395 uint64_t NTPtime64 (void)
396 {
397     struct timespec ts;
398 #if defined (CLOCK_REALTIME)
399     clock_gettime (CLOCK_REALTIME, &ts);
400 #else
401     {
402         struct timeval tv;
403         gettimeofday (&tv, NULL);
404         ts.tv_sec = tv.tv_sec;
405         ts.tv_nsec = tv.tv_usec * 1000;
406     }
407 #endif
408
409     /* Convert nanoseconds to 32-bits fraction (232 picosecond units) */
410     uint64_t t = (uint64_t)(ts.tv_nsec) << 32;
411     t /= 1000000000;
412
413
414     /* There is 70 years (incl. 17 leap ones) offset to the Unix Epoch.
415      * No leap seconds during that period since they were not invented yet.
416      */
417     assert (t < 0x100000000);
418     t |= ((70LL * 365 + 17) * 24 * 60 * 60 + ts.tv_sec) << 32;
419     return t;
420 }
421