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