]> git.sesse.net Git - vlc/blob - src/misc/pthread.c
Missing #include <errno.h>
[vlc] / src / misc / pthread.c
1 /*****************************************************************************
2  * pthread.c : pthread back-end for LibVLC
3  *****************************************************************************
4  * Copyright (C) 1999-2009 the VideoLAN team
5  *
6  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
7  *          Samuel Hocevar <sam@zoy.org>
8  *          Gildas Bazin <gbazin@netcourrier.com>
9  *          Clément Sténac
10  *          Rémi Denis-Courmont
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 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32
33 #include "libvlc.h"
34 #include <stdarg.h>
35 #include <assert.h>
36 #include <unistd.h> /* fsync() */
37 #include <signal.h>
38 #include <errno.h>
39
40 #include <sched.h>
41 #ifdef __linux__
42 # include <sys/syscall.h> /* SYS_gettid */
43 #endif
44
45 #ifdef HAVE_EXECINFO_H
46 # include <execinfo.h>
47 #endif
48
49 #ifdef __APPLE__
50 # include <sys/time.h> /* gettimeofday in vlc_cond_timedwait */
51 #endif
52
53 /**
54  * Print a backtrace to the standard error for debugging purpose.
55  */
56 void vlc_trace (const char *fn, const char *file, unsigned line)
57 {
58      fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
59      fflush (stderr); /* needed before switch to low-level I/O */
60 #ifdef HAVE_BACKTRACE
61      void *stack[20];
62      int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
63      backtrace_symbols_fd (stack, len, 2);
64 #endif
65      fsync (2);
66 }
67
68 static inline unsigned long vlc_threadid (void)
69 {
70 #if defined (__linux__)
71      /* glibc does not provide a call for this */
72      return syscall (SYS_gettid);
73
74 #else
75      union { pthread_t th; unsigned long int i; } v = { };
76      v.th = pthread_self ();
77      return v.i;
78
79 #endif
80 }
81
82 #ifndef NDEBUG
83 /*****************************************************************************
84  * vlc_thread_fatal: Report an error from the threading layer
85  *****************************************************************************
86  * This is mostly meant for debugging.
87  *****************************************************************************/
88 static void
89 vlc_thread_fatal (const char *action, int error,
90                   const char *function, const char *file, unsigned line)
91 {
92     fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
93              action, error, vlc_threadid ());
94     vlc_trace (function, file, line);
95
96     /* Sometimes strerror_r() crashes too, so make sure we print an error
97      * message before we invoke it */
98 #ifdef __GLIBC__
99     /* Avoid the strerror_r() prototype brain damage in glibc */
100     errno = error;
101     fprintf (stderr, " Error message: %m\n");
102 #else
103     char buf[1000];
104     const char *msg;
105
106     switch (strerror_r (error, buf, sizeof (buf)))
107     {
108         case 0:
109             msg = buf;
110             break;
111         case ERANGE: /* should never happen */
112             msg = "unknwon (too big to display)";
113             break;
114         default:
115             msg = "unknown (invalid error number)";
116             break;
117     }
118     fprintf (stderr, " Error message: %s\n", msg);
119 #endif
120     fflush (stderr);
121
122     abort ();
123 }
124
125 # define VLC_THREAD_ASSERT( action ) \
126     if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
127 #else
128 # define VLC_THREAD_ASSERT( action ) ((void)val)
129 #endif
130
131 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
132 /* This is not prototyped under glibc, though it exists. */
133 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
134 #endif
135
136 /*****************************************************************************
137  * vlc_mutex_init: initialize a mutex
138  *****************************************************************************/
139 void vlc_mutex_init( vlc_mutex_t *p_mutex )
140 {
141     pthread_mutexattr_t attr;
142
143     if( pthread_mutexattr_init( &attr ) )
144         abort();
145 #ifdef NDEBUG
146     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_NORMAL );
147 #else
148     /* Create error-checking mutex to detect problems more easily. */
149 # if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
150     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
151 # else
152     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
153 # endif
154 #endif
155     if( pthread_mutex_init( p_mutex, &attr ) )
156         abort();
157     pthread_mutexattr_destroy( &attr );
158 }
159
160 /*****************************************************************************
161  * vlc_mutex_init: initialize a recursive mutex (Do not use)
162  *****************************************************************************/
163 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
164 {
165     pthread_mutexattr_t attr;
166
167     pthread_mutexattr_init( &attr );
168 #if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
169     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
170 #else
171     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
172 #endif
173     if( pthread_mutex_init( p_mutex, &attr ) )
174         abort();
175     pthread_mutexattr_destroy( &attr );
176 }
177
178
179 /**
180  * Destroys a mutex. The mutex must not be locked.
181  *
182  * @param p_mutex mutex to destroy
183  * @return always succeeds
184  */
185 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
186 {
187     int val = pthread_mutex_destroy( p_mutex );
188     VLC_THREAD_ASSERT ("destroying mutex");
189 }
190
191 #ifndef NDEBUG
192 # ifdef HAVE_VALGRIND_VALGRIND_H
193 #  include <valgrind/valgrind.h>
194 # else
195 #  define RUNNING_ON_VALGRIND (0)
196 # endif
197
198 void vlc_assert_locked (vlc_mutex_t *p_mutex)
199 {
200     if (RUNNING_ON_VALGRIND > 0)
201         return;
202     assert (pthread_mutex_lock (p_mutex) == EDEADLK);
203 }
204 #endif
205
206 /**
207  * Acquires a mutex. If needed, waits for any other thread to release it.
208  * Beware of deadlocks when locking multiple mutexes at the same time,
209  * or when using mutexes from callbacks.
210  * This function is not a cancellation-point.
211  *
212  * @param p_mutex mutex initialized with vlc_mutex_init() or
213  *                vlc_mutex_init_recursive()
214  */
215 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
216 {
217     int val = pthread_mutex_lock( p_mutex );
218     VLC_THREAD_ASSERT ("locking mutex");
219 }
220
221 /**
222  * Acquires a mutex if and only if it is not currently held by another thread.
223  * This function never sleeps and can be used in delay-critical code paths.
224  * This function is not a cancellation-point.
225  *
226  * <b>Beware</b>: If this function fails, then the mutex is held... by another
227  * thread. The calling thread must deal with the error appropriately. That
228  * typically implies postponing the operations that would have required the
229  * mutex. If the thread cannot defer those operations, then it must use
230  * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
231  *
232  * @param p_mutex mutex initialized with vlc_mutex_init() or
233  *                vlc_mutex_init_recursive()
234  * @return 0 if the mutex could be acquired, an error code otherwise.
235  */
236 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
237 {
238     int val = pthread_mutex_trylock( p_mutex );
239
240     if (val != EBUSY)
241         VLC_THREAD_ASSERT ("locking mutex");
242     return val;
243 }
244
245 /**
246  * Releases a mutex (or crashes if the mutex is not locked by the caller).
247  * @param p_mutex mutex locked with vlc_mutex_lock().
248  */
249 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
250 {
251     int val = pthread_mutex_unlock( p_mutex );
252     VLC_THREAD_ASSERT ("unlocking mutex");
253 }
254
255 /*****************************************************************************
256  * vlc_cond_init: initialize a condition variable
257  *****************************************************************************/
258 void vlc_cond_init( vlc_cond_t *p_condvar )
259 {
260     pthread_condattr_t attr;
261
262     if (pthread_condattr_init (&attr))
263         abort ();
264 #if !defined (_POSIX_CLOCK_SELECTION)
265    /* Fairly outdated POSIX support (that was defined in 2001) */
266 # define _POSIX_CLOCK_SELECTION (-1)
267 #endif
268 #if (_POSIX_CLOCK_SELECTION >= 0)
269     /* NOTE: This must be the same clock as the one in mtime.c */
270     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
271 #endif
272
273     if (pthread_cond_init (p_condvar, &attr))
274         abort ();
275     pthread_condattr_destroy (&attr);
276 }
277
278 /**
279  * Destroys a condition variable. No threads shall be waiting or signaling the
280  * condition.
281  * @param p_condvar condition variable to destroy
282  */
283 void vlc_cond_destroy (vlc_cond_t *p_condvar)
284 {
285     int val = pthread_cond_destroy( p_condvar );
286     VLC_THREAD_ASSERT ("destroying condition");
287 }
288
289 /**
290  * Wakes up one thread waiting on a condition variable, if any.
291  * @param p_condvar condition variable
292  */
293 void vlc_cond_signal (vlc_cond_t *p_condvar)
294 {
295     int val = pthread_cond_signal( p_condvar );
296     VLC_THREAD_ASSERT ("signaling condition variable");
297 }
298
299 /**
300  * Wakes up all threads (if any) waiting on a condition variable.
301  * @param p_cond condition variable
302  */
303 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
304 {
305     pthread_cond_broadcast (p_condvar);
306 }
307
308 /**
309  * Waits for a condition variable. The calling thread will be suspended until
310  * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
311  * condition variable, the thread is cancelled with vlc_cancel(), or the
312  * system causes a "spurious" unsolicited wake-up.
313  *
314  * A mutex is needed to wait on a condition variable. It must <b>not</b> be
315  * a recursive mutex. Although it is possible to use the same mutex for
316  * multiple condition, it is not valid to use different mutexes for the same
317  * condition variable at the same time from different threads.
318  *
319  * In case of thread cancellation, the mutex is always locked before
320  * cancellation proceeds.
321  *
322  * The canonical way to use a condition variable to wait for event foobar is:
323  @code
324    vlc_mutex_lock (&lock);
325    mutex_cleanup_push (&lock); // release the mutex in case of cancellation
326
327    while (!foobar)
328        vlc_cond_wait (&wait, &lock);
329
330    --- foobar is now true, do something about it here --
331
332    vlc_cleanup_run (); // release the mutex
333   @endcode
334  *
335  * @param p_condvar condition variable to wait on
336  * @param p_mutex mutex which is unlocked while waiting,
337  *                then locked again when waking up.
338  * @param deadline <b>absolute</b> timeout
339  *
340  * @return 0 if the condition was signaled, an error code in case of timeout.
341  */
342 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
343 {
344     int val = pthread_cond_wait( p_condvar, p_mutex );
345     VLC_THREAD_ASSERT ("waiting on condition");
346 }
347
348 /**
349  * Waits for a condition variable up to a certain date.
350  * This works like vlc_cond_wait(), except for the additional timeout.
351  *
352  * @param p_condvar condition variable to wait on
353  * @param p_mutex mutex which is unlocked while waiting,
354  *                then locked again when waking up.
355  * @param deadline <b>absolute</b> timeout
356  *
357  * @return 0 if the condition was signaled, an error code in case of timeout.
358  */
359 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
360                         mtime_t deadline)
361 {
362 #if defined(__APPLE__) && !defined(__powerpc__) && !defined( __ppc__ ) && !defined( __ppc64__ )
363     /* mdate() is mac_absolute_time on OSX, which we must convert to do
364      * the same base than gettimeofday() which pthread_cond_timedwait
365      * relies on. */
366     mtime_t oldbase = mdate();
367     struct timeval tv;
368     gettimeofday(&tv, NULL);
369     mtime_t newbase = (mtime_t)tv.tv_sec * 1000000 + (mtime_t) tv.tv_usec;
370     deadline = deadline - oldbase + newbase;
371 #endif
372     lldiv_t d = lldiv( deadline, CLOCK_FREQ );
373     struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
374
375     int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
376     if (val != ETIMEDOUT)
377         VLC_THREAD_ASSERT ("timed-waiting on condition");
378     return val;
379 }
380
381 /**
382  * Initializes a read/write lock.
383  */
384 void vlc_rwlock_init (vlc_rwlock_t *lock)
385 {
386     if (pthread_rwlock_init (lock, NULL))
387         abort ();
388 }
389
390 /**
391  * Destroys an initialized unused read/write lock.
392  */
393 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
394 {
395     int val = pthread_rwlock_destroy (lock);
396     VLC_THREAD_ASSERT ("destroying R/W lock");
397 }
398
399 /**
400  * Acquires a read/write lock for reading. Recursion is allowed.
401  */
402 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
403 {
404     int val = pthread_rwlock_rdlock (lock);
405     VLC_THREAD_ASSERT ("acquiring R/W lock for reading");
406 }
407
408 /**
409  * Acquires a read/write lock for writing. Recursion is not allowed.
410  */
411 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
412 {
413     int val = pthread_rwlock_wrlock (lock);
414     VLC_THREAD_ASSERT ("acquiring R/W lock for writing");
415 }
416
417 /**
418  * Releases a read/write lock.
419  */
420 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
421 {
422     int val = pthread_rwlock_unlock (lock);
423     VLC_THREAD_ASSERT ("releasing R/W lock");
424 }
425
426 /**
427  * Allocates a thread-specific variable.
428  * @param key where to store the thread-specific variable handle
429  * @param destr a destruction callback. It is called whenever a thread exits
430  * and the thread-specific variable has a non-NULL value.
431  * @return 0 on success, a system error code otherwise. This function can
432  * actually fail because there is a fixed limit on the number of
433  * thread-specific variable in a process on most systems.
434  */
435 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
436 {
437     return pthread_key_create (key, destr);
438 }
439
440 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
441 {
442     pthread_key_delete (*p_tls);
443 }
444
445 /**
446  * Sets a thread-specific variable.
447  * @param key thread-local variable key (created with vlc_threadvar_create())
448  * @param value new value for the variable for the calling thread
449  * @return 0 on success, a system error code otherwise.
450  */
451 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
452 {
453     return pthread_setspecific (key, value);
454 }
455
456 /**
457  * Gets the value of a thread-local variable for the calling thread.
458  * This function cannot fail.
459  * @return the value associated with the given variable for the calling
460  * or NULL if there is no value.
461  */
462 void *vlc_threadvar_get (vlc_threadvar_t key)
463 {
464     return pthread_getspecific (key);
465 }
466
467 static bool rt_priorities = false;
468 static int rt_offset;
469
470 void vlc_threads_setup (libvlc_int_t *p_libvlc)
471 {
472     static vlc_mutex_t lock = VLC_STATIC_MUTEX;
473     static bool initialized = false;
474
475     vlc_mutex_lock (&lock);
476     /* Initializes real-time priorities before any thread is created,
477      * just once per process. */
478     if (!initialized)
479     {
480 #ifndef __APPLE__
481         if (config_GetInt (p_libvlc, "rt-priority"))
482 #endif
483         {
484             rt_offset = config_GetInt (p_libvlc, "rt-offset");
485             rt_priorities = true;
486         }
487         initialized = true;
488     }
489     vlc_mutex_unlock (&lock);
490 }
491
492 /**
493  * Creates and starts new thread.
494  *
495  * @param p_handle [OUT] pointer to write the handle of the created thread to
496  * @param entry entry point for the thread
497  * @param data data parameter given to the entry point
498  * @param priority thread priority value
499  * @return 0 on success, a standard error code on error.
500  */
501 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
502                int priority)
503 {
504     int ret;
505
506     pthread_attr_t attr;
507     pthread_attr_init (&attr);
508
509     /* Block the signals that signals interface plugin handles.
510      * If the LibVLC caller wants to handle some signals by itself, it should
511      * block these before whenever invoking LibVLC. And it must obviously not
512      * start the VLC signals interface plugin.
513      *
514      * LibVLC will normally ignore any interruption caused by an asynchronous
515      * signal during a system call. But there may well be some buggy cases
516      * where it fails to handle EINTR (bug reports welcome). Some underlying
517      * libraries might also not handle EINTR properly.
518      */
519     sigset_t oldset;
520     {
521         sigset_t set;
522         sigemptyset (&set);
523         sigdelset (&set, SIGHUP);
524         sigaddset (&set, SIGINT);
525         sigaddset (&set, SIGQUIT);
526         sigaddset (&set, SIGTERM);
527
528         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
529         pthread_sigmask (SIG_BLOCK, &set, &oldset);
530     }
531
532 #if defined (_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING >= 0) \
533  && defined (_POSIX_THREAD_PRIORITY_SCHEDULING) \
534  && (_POSIX_THREAD_PRIORITY_SCHEDULING >= 0)
535     if (rt_priorities)
536     {
537         struct sched_param sp = { .sched_priority = priority + rt_offset, };
538         int policy;
539
540         if (sp.sched_priority <= 0)
541             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
542         else
543             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
544
545         pthread_attr_setschedpolicy (&attr, policy);
546         pthread_attr_setschedparam (&attr, &sp);
547     }
548 #else
549     (void) priority;
550 #endif
551
552     /* The thread stack size.
553      * The lower the value, the less address space per thread, the highest
554      * maximum simultaneous threads per process. Too low values will cause
555      * stack overflows and weird crashes. Set with caution. Also keep in mind
556      * that 64-bits platforms consume more stack than 32-bits one.
557      *
558      * Thanks to on-demand paging, thread stack size only affects address space
559      * consumption. In terms of memory, threads only use what they need
560      * (rounded up to the page boundary).
561      *
562      * For example, on Linux i386, the default is 2 mega-bytes, which supports
563      * about 320 threads per processes. */
564 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
565
566 #ifdef VLC_STACKSIZE
567     ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
568     assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
569 #endif
570
571     ret = pthread_create (p_handle, &attr, entry, data);
572     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
573     pthread_attr_destroy (&attr);
574     return ret;
575 }
576
577 /**
578  * Marks a thread as cancelled. Next time the target thread reaches a
579  * cancellation point (while not having disabled cancellation), it will
580  * run its cancellation cleanup handler, the thread variable destructors, and
581  * terminate. vlc_join() must be used afterward regardless of a thread being
582  * cancelled or not.
583  */
584 void vlc_cancel (vlc_thread_t thread_id)
585 {
586     pthread_cancel (thread_id);
587 }
588
589 /**
590  * Waits for a thread to complete (if needed), then destroys it.
591  * This is a cancellation point; in case of cancellation, the join does _not_
592  * occur.
593  * @warning
594  * A thread cannot join itself (normally VLC will abort if this is attempted).
595  * Also, a detached thread <b>cannot</b> be joined.
596  *
597  * @param handle thread handle
598  * @param p_result [OUT] pointer to write the thread return value or NULL
599  */
600 void vlc_join (vlc_thread_t handle, void **result)
601 {
602     int val = pthread_join (handle, result);
603     VLC_THREAD_ASSERT ("joining thread");
604 }
605
606 /**
607  * Detaches a thread. When the specified thread completes, it will be
608  * automatically destroyed (in particular, its stack will be reclaimed),
609  * instead of waiting for another thread to call vlc_join(). If the thread has
610  * already completed, it will be destroyed immediately.
611  *
612  * When a thread performs some work asynchronously and may complete much
613  * earlier than it can be joined, detaching the thread can save memory.
614  * However, care must be taken that any resources used by a detached thread
615  * remains valid until the thread completes. This will typically involve some
616  * kind of thread-safe signaling.
617  *
618  * A thread may detach itself.
619  *
620  * @param handle thread handle
621  */
622 void vlc_detach (vlc_thread_t handle)
623 {
624     int val = pthread_detach (handle);
625     VLC_THREAD_ASSERT ("detaching thread");
626 }
627
628 /**
629  * Save the current cancellation state (enabled or disabled), then disable
630  * cancellation for the calling thread.
631  * This function must be called before entering a piece of code that is not
632  * cancellation-safe, unless it can be proven that the calling thread will not
633  * be cancelled.
634  * @return Previous cancellation state (opaque value for vlc_restorecancel()).
635  */
636 int vlc_savecancel (void)
637 {
638     int state;
639     int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
640
641     VLC_THREAD_ASSERT ("saving cancellation");
642     return state;
643 }
644
645 /**
646  * Restore the cancellation state for the calling thread.
647  * @param state previous state as returned by vlc_savecancel().
648  * @return Nothing, always succeeds.
649  */
650 void vlc_restorecancel (int state)
651 {
652 #ifndef NDEBUG
653     int oldstate, val;
654
655     val = pthread_setcancelstate (state, &oldstate);
656     /* This should fail if an invalid value for given for state */
657     VLC_THREAD_ASSERT ("restoring cancellation");
658
659     if (oldstate != PTHREAD_CANCEL_DISABLE)
660          vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
661                            __func__, __FILE__, __LINE__);
662 #else
663     pthread_setcancelstate (state, NULL);
664 #endif
665 }
666
667 /**
668  * Issues an explicit deferred cancellation point.
669  * This has no effect if thread cancellation is disabled.
670  * This can be called when there is a rather slow non-sleeping operation.
671  * This is also used to force a cancellation point in a function that would
672  * otherwise "not always" be a one (block_FifoGet() is an example).
673  */
674 void vlc_testcancel (void)
675 {
676     pthread_testcancel ();
677 }
678
679 void vlc_control_cancel (int cmd, ...)
680 {
681     (void) cmd;
682     assert (0);
683 }
684
685
686 struct vlc_timer
687 {
688     vlc_thread_t thread;
689     vlc_mutex_t  lock;
690     vlc_cond_t   wait;
691     void       (*func) (void *);
692     void        *data;
693     mtime_t      value, interval;
694     unsigned     users;
695     unsigned     overruns;
696 };
697
698 static void *vlc_timer_do (void *data)
699 {
700     struct vlc_timer *timer = data;
701
702     timer->func (timer->data);
703
704     vlc_mutex_lock (&timer->lock);
705     assert (timer->users > 0);
706     if (--timer->users == 0)
707         vlc_cond_signal (&timer->wait);
708     vlc_mutex_unlock (&timer->lock);
709     return NULL;
710 }
711
712 static void *vlc_timer_thread (void *data)
713 {
714     struct vlc_timer *timer = data;
715     mtime_t value, interval;
716
717     vlc_mutex_lock (&timer->lock);
718     value = timer->value;
719     interval = timer->interval;
720     vlc_mutex_unlock (&timer->lock);
721
722     for (;;)
723     {
724          vlc_thread_t th;
725
726          mwait (value);
727
728          vlc_mutex_lock (&timer->lock);
729          if (vlc_clone (&th, vlc_timer_do, timer, VLC_THREAD_PRIORITY_INPUT))
730              timer->overruns++;
731          else
732          {
733              vlc_detach (th);
734              timer->users++;
735          }
736          vlc_mutex_unlock (&timer->lock);
737
738          if (interval == 0)
739              return NULL;
740
741          value += interval;
742     }
743 }
744
745 /**
746  * Initializes an asynchronous timer.
747  * @warning Asynchronous timers are processed from an unspecified thread.
748  * Also, multiple occurences of an interval timer can run concurrently.
749  *
750  * @param id pointer to timer to be initialized
751  * @param func function that the timer will call
752  * @param data parameter for the timer function
753  * @return 0 on success, a system error code otherwise.
754  */
755 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
756 {
757     struct vlc_timer *timer = malloc (sizeof (*timer));
758
759     if (timer == NULL)
760         return ENOMEM;
761     vlc_mutex_init (&timer->lock);
762     vlc_cond_init (&timer->wait);
763     assert (func);
764     timer->func = func;
765     timer->data = data;
766     timer->value = 0;
767     timer->interval = 0;
768     timer->users = 0;
769     timer->overruns = 0;
770     *id = timer;
771     return 0;
772 }
773
774 /**
775  * Destroys an initialized timer. If needed, the timer is first disarmed.
776  * This function is undefined if the specified timer is not initialized.
777  *
778  * @warning This function <b>must</b> be called before the timer data can be
779  * freed and before the timer callback function can be unloaded.
780  *
781  * @param timer timer to destroy
782  */
783 void vlc_timer_destroy (vlc_timer_t timer)
784 {
785     vlc_timer_schedule (timer, false, 0, 0);
786     vlc_mutex_lock (&timer->lock);
787     while (timer->users != 0)
788         vlc_cond_wait (&timer->wait, &timer->lock);
789     vlc_mutex_unlock (&timer->lock);
790
791     vlc_cond_destroy (&timer->wait);
792     vlc_mutex_destroy (&timer->lock);
793     free (timer);
794 }
795
796 /**
797  * Arm or disarm an initialized timer.
798  * This functions overrides any previous call to itself.
799  *
800  * @note A timer can fire later than requested due to system scheduling
801  * limitations. An interval timer can fail to trigger sometimes, either because
802  * the system is busy or suspended, or because a previous iteration of the
803  * timer is still running. See also vlc_timer_getoverrun().
804  *
805  * @param timer initialized timer
806  * @param absolute the timer value origin is the same as mdate() if true,
807  *                 the timer value is relative to now if false.
808  * @param value zero to disarm the timer, otherwise the initial time to wait
809  *              before firing the timer.
810  * @param interval zero to fire the timer just once, otherwise the timer
811  *                 repetition interval.
812  */
813 void vlc_timer_schedule (vlc_timer_t timer, bool absolute,
814                          mtime_t value, mtime_t interval)
815 {
816     static vlc_mutex_t lock = VLC_STATIC_MUTEX;
817
818     vlc_mutex_lock (&lock);
819     vlc_mutex_lock (&timer->lock);
820     if (timer->value)
821     {
822         vlc_mutex_unlock (&timer->lock);
823         vlc_cancel (timer->thread);
824         vlc_join (timer->thread, NULL);
825         vlc_mutex_lock (&timer->lock);
826         timer->value = 0;
827     }
828     if ((value != 0)
829      && (vlc_clone (&timer->thread, vlc_timer_thread, timer,
830                     VLC_THREAD_PRIORITY_INPUT) == 0))
831     {
832         timer->value = (absolute ? 0 : mdate ()) + value;
833         timer->interval = interval;
834     }
835     vlc_mutex_unlock (&timer->lock);
836     vlc_mutex_unlock (&lock);
837 }
838
839 /**
840  * Fetch and reset the overrun counter for a timer.
841  * @param timer initialized timer
842  * @return the timer overrun counter, i.e. the number of times that the timer
843  * should have run but did not since the last actual run. If all is well, this
844  * is zero.
845  */
846 unsigned vlc_timer_getoverrun (vlc_timer_t timer)
847 {
848     unsigned ret;
849
850     vlc_mutex_lock (&timer->lock);
851     ret = timer->overruns;
852     timer->overruns = 0;
853     vlc_mutex_unlock (&timer->lock);
854     return ret;
855 }