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