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
9 * Authors: Vincent Seguin <seguin@via.ecp.fr>
10 * Rémi Denis-Courmont <rem$videolan,org>
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.
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.
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 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
33 #include <stdio.h> /* sprintf() */
34 #include <time.h> /* clock_gettime(), clock_nanosleep() */
35 #include <stdlib.h> /* lldiv() */
39 #if defined( PTH_INIT_IN_PTH_H ) /* GNU Pth */
44 # include <unistd.h> /* select() */
47 #ifdef HAVE_KERNEL_OS_H
48 # include <kernel/OS.h>
51 #if defined( WIN32 ) || defined( UNDER_CE )
54 # include <sys/time.h>
57 #if defined(HAVE_NANOSLEEP) && !defined(HAVE_STRUCT_TIMESPEC)
65 #if defined(HAVE_NANOSLEEP) && !defined(HAVE_DECL_NANOSLEEP)
66 int nanosleep(struct timespec *, struct timespec *);
70 * Return a date in a readable format
72 * This function converts a mtime date into a string.
73 * psz_buffer should be a buffer long enough to store the formatted
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.
79 char *mstrtime( char *psz_buffer, mtime_t date )
81 static mtime_t ll1000 = 1000, ll60 = 60, ll24 = 24;
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) );
93 * Convert seconds to a time in the format h:mm:ss.
95 * This function is provided for any interface function which need to print a
96 * time string in the format h:mm:ss
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.
102 char *secstotimestr( char *psz_buffer, int i_seconds )
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 );
113 * Return high precision date
115 * Uses the gettimeofday() function when possible (1 MHz resolution) or the
116 * ftime() function (1 kHz resolution).
118 mtime_t mdate( void )
120 #if defined (HAVE_CLOCK_NANOSLEEP)
123 # if (_POSIX_MONOTONIC_CLOCK - 0 >= 0)
124 /* Try to use POSIX monotonic clock if available */
125 if( clock_gettime( CLOCK_MONOTONIC, &ts ) )
127 /* Run-time fallback to real-time clock (always available) */
128 (void)clock_gettime( CLOCK_REALTIME, &ts );
130 return ((mtime_t)ts.tv_sec * (mtime_t)1000000)
131 + (mtime_t)(ts.tv_nsec / 1000);
133 #elif defined( HAVE_KERNEL_OS_H )
134 return( real_time_clock_usecs() );
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);
140 if( freq == I64C(-1) )
142 /* Extract from the Tcl source code:
143 * (http://www.cs.man.ac.uk/fellowsd-bin/TIP/7.html)
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
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.
162 freq = ( QueryPerformanceFrequency( &buf ) &&
163 (buf.QuadPart == I64C(1193182) || buf.QuadPart == I64C(3579545) ) )
169 LARGE_INTEGER counter;
170 QueryPerformanceCounter (&counter);
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);
176 return (d.quot * 1000000)
177 + ((d.rem * 1000000) / freq);
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. */
186 static CRITICAL_SECTION date_lock;
187 static mtime_t i_previous_time = I64C(-1);
188 static int i_wrap_counts = -1;
191 if( i_wrap_counts == -1 )
194 i_previous_time = I64C(1000) * GetTickCount();
195 InitializeCriticalSection( &date_lock );
199 EnterCriticalSection( &date_lock );
200 usec_time = I64C(1000) *
201 (i_wrap_counts * I64C(0x100000000) + GetTickCount());
202 if( i_previous_time > usec_time )
204 /* Counter wrapped */
206 usec_time += I64C(0x100000000) * 1000;
208 i_previous_time = usec_time;
209 LeaveCriticalSection( &date_lock );
214 struct timeval tv_date;
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 );
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
230 void mwait( mtime_t date )
232 #if defined (HAVE_CLOCK_NANOSLEEP)
233 lldiv_t d = lldiv( date, 1000000 );
234 struct timespec ts = { d.quot, d.rem * 1000 };
236 # if (_POSIX_MONOTONIC_CLOCK - 0 >= 0)
237 if( clock_nanosleep( CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL ) )
239 clock_nanosleep( CLOCK_REALTIME, TIMER_ABSTIME, &ts, NULL );
242 mtime_t delay = date - mdate();
250 * More precise sleep()
252 * Portable usleep() function.
253 * \param delay the amount of time to sleep
255 void msleep( mtime_t delay )
257 #if defined( HAVE_CLOCK_NANOSLEEP )
258 lldiv_t d = lldiv( delay, 1000000 );
259 struct timespec ts = { d.quot, d.rem * 1000 };
261 # if (_POSIX_MONOTONIC_CLOCK - 0 >= 0)
262 if( clock_nanosleep( CLOCK_MONOTONIC, 0, &ts, NULL ) )
264 clock_nanosleep( CLOCK_REALTIME, 0, &ts, NULL );
266 #elif defined( HAVE_KERNEL_OS_H )
269 #elif defined( PTH_INIT_IN_PTH_H )
272 #elif defined( ST_INIT_IN_ST_H )
275 #elif defined( WIN32 ) || defined( UNDER_CE )
276 Sleep( (int) (delay / 1000) );
278 #elif defined( HAVE_NANOSLEEP )
279 struct timespec ts_delay;
281 ts_delay.tv_sec = delay / 1000000;
282 ts_delay.tv_nsec = (delay % 1000000) * 1000;
284 nanosleep( &ts_delay, NULL );
287 struct timeval tv_delay;
289 tv_delay.tv_sec = delay / 1000000;
290 tv_delay.tv_usec = delay % 1000000;
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
296 select( 0, NULL, NULL, NULL, &tv_delay );
301 * Date management (internal and external)
305 * Initialize a date_t.
307 * \param date to initialize
308 * \param divider (sample rate) numerator
309 * \param divider (sample rate) denominator
312 void date_Init( date_t *p_date, uint32_t i_divider_n, uint32_t i_divider_d )
315 p_date->i_divider_num = i_divider_n;
316 p_date->i_divider_den = i_divider_d;
317 p_date->i_remainder = 0;
323 * \param date to change
324 * \param divider (sample rate) numerator
325 * \param divider (sample rate) denominator
328 void date_Change( date_t *p_date, uint32_t i_divider_n, uint32_t i_divider_d )
330 p_date->i_divider_num = i_divider_n;
331 p_date->i_divider_den = i_divider_d;
335 * Set the date value of a date_t.
340 void date_Set( date_t *p_date, mtime_t i_new_date )
342 p_date->date = i_new_date;
343 p_date->i_remainder = 0;
347 * Get the date of a date_t
352 mtime_t date_Get( const date_t *p_date )
358 * Move forwards or backwards the date of a date_t.
360 * \param date to move
361 * \param difference value
363 void date_Move( date_t *p_date, mtime_t i_difference )
365 p_date->date += i_difference;
369 * Increment the date and return the result, taking into account
372 * \param date to increment
373 * \param incrementation in number of samples
376 mtime_t date_Increment( date_t *p_date, uint32_t i_nb_samples )
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);
382 if( p_date->i_remainder >= p_date->i_divider_num )
384 /* This is Bresenham algorithm. */
385 p_date->date += p_date->i_divider_den;
386 p_date->i_remainder -= p_date->i_divider_num;
393 * @return NTP 64-bits timestamp in host byte order.
395 uint64_t NTPtime64 (void)
398 #if defined (CLOCK_REALTIME)
399 clock_gettime (CLOCK_REALTIME, &ts);
403 gettimeofday (&tv, NULL);
404 ts.tv_sec = tv.tv_sec;
405 ts.tv_nsec = tv.tv_usec * 1000;
409 /* Convert nanoseconds to 32-bits fraction (232 picosecond units) */
410 uint64_t t = (uint64_t)(ts.tv_nsec) << 32;
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.
417 assert (t < 0x100000000);
418 t |= ((70LL * 365 + 17) * 24 * 60 * 60 + ts.tv_sec) << 32;