]> git.sesse.net Git - vlc/blob - src/win32/thread.c
Win32: don't destroy variables without destroy callbacks
[vlc] / src / win32 / thread.c
1 /*****************************************************************************
2  * thread.c : Win32 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  *          Pierre Ynard
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33
34 #include "libvlc.h"
35 #include <stdarg.h>
36 #include <assert.h>
37 #include <limits.h>
38 #include <errno.h>
39 #ifdef UNDER_CE
40 # include <mmsystem.h>
41 #endif
42
43 static vlc_threadvar_t cancel_key;
44
45 /**
46  * Per-thread cancellation data
47  */
48 typedef struct vlc_cancel_t
49 {
50     vlc_cleanup_t *cleaners;
51 #ifdef UNDER_CE
52     HANDLE         cancel_event;
53 #endif
54     bool           killable;
55     bool           killed;
56 } vlc_cancel_t;
57
58 #ifndef UNDER_CE
59 # define VLC_CANCEL_INIT { NULL, true, false }
60 #else
61 # define VLC_CANCEL_INIT { NULL, NULL, true, false }
62 #endif
63
64 #ifdef UNDER_CE
65 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy);
66
67 static DWORD vlc_cancelable_wait (DWORD count, const HANDLE *handles,
68                                   DWORD delay)
69 {
70     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
71     if (nfo == NULL)
72     {
73         /* Main thread - cannot be cancelled anyway */
74         return WaitForMultipleObjects (count, handles, FALSE, delay);
75     }
76     HANDLE new_handles[count + 1];
77     memcpy(new_handles, handles, count * sizeof(HANDLE));
78     new_handles[count] = nfo->cancel_event;
79     DWORD result = WaitForMultipleObjects (count + 1, new_handles, FALSE,
80                                            delay);
81     if (result == WAIT_OBJECT_0 + count)
82     {
83         vlc_cancel_self (NULL);
84         return WAIT_IO_COMPLETION;
85     }
86     else
87     {
88         return result;
89     }
90 }
91
92 DWORD SleepEx (DWORD dwMilliseconds, BOOL bAlertable)
93 {
94     if (bAlertable)
95     {
96         DWORD result = vlc_cancelable_wait (0, NULL, dwMilliseconds);
97         return (result == WAIT_TIMEOUT) ? 0 : WAIT_IO_COMPLETION;
98     }
99     else
100     {
101         Sleep(dwMilliseconds);
102         return 0;
103     }
104 }
105
106 DWORD WaitForSingleObjectEx (HANDLE hHandle, DWORD dwMilliseconds,
107                              BOOL bAlertable)
108 {
109     if (bAlertable)
110     {
111         /* The MSDN documentation specifies different return codes,
112          * but in practice they are the same. We just check that it
113          * remains so. */
114 #if WAIT_ABANDONED != WAIT_ABANDONED_0
115 # error Windows headers changed, code needs to be rewritten!
116 #endif
117         return vlc_cancelable_wait (1, &hHandle, dwMilliseconds);
118     }
119     else
120     {
121         return WaitForSingleObject (hHandle, dwMilliseconds);
122     }
123 }
124
125 DWORD WaitForMultipleObjectsEx (DWORD nCount, const HANDLE *lpHandles,
126                                 BOOL bWaitAll, DWORD dwMilliseconds,
127                                 BOOL bAlertable)
128 {
129     if (bAlertable)
130     {
131         /* We do not support the bWaitAll case */
132         assert (! bWaitAll);
133         return vlc_cancelable_wait (nCount, lpHandles, dwMilliseconds);
134     }
135     else
136     {
137         return WaitForMultipleObjects (nCount, lpHandles, bWaitAll,
138                                        dwMilliseconds);
139     }
140 }
141 #endif
142
143 vlc_mutex_t super_mutex;
144 vlc_cond_t  super_variable;
145
146 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
147 {
148     (void) hinstDll;
149     (void) lpvReserved;
150
151     switch (fdwReason)
152     {
153         case DLL_PROCESS_ATTACH:
154             vlc_mutex_init (&super_mutex);
155             vlc_cond_init (&super_variable);
156             vlc_threadvar_create (&cancel_key, NULL);
157             break;
158
159         case DLL_PROCESS_DETACH:
160             vlc_threadvar_delete( &cancel_key );
161             vlc_cond_destroy (&super_variable);
162             vlc_mutex_destroy (&super_mutex);
163             break;
164     }
165     return TRUE;
166 }
167
168 /*** Mutexes ***/
169 void vlc_mutex_init( vlc_mutex_t *p_mutex )
170 {
171     /* This creates a recursive mutex. This is OK as fast mutexes have
172      * no defined behavior in case of recursive locking. */
173     InitializeCriticalSection (&p_mutex->mutex);
174     p_mutex->dynamic = true;
175 }
176
177 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
178 {
179     InitializeCriticalSection( &p_mutex->mutex );
180     p_mutex->dynamic = true;
181 }
182
183
184 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
185 {
186     assert (p_mutex->dynamic);
187     DeleteCriticalSection (&p_mutex->mutex);
188 }
189
190 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
191 {
192     if (!p_mutex->dynamic)
193     {   /* static mutexes */
194         int canc = vlc_savecancel ();
195         assert (p_mutex != &super_mutex); /* this one cannot be static */
196
197         vlc_mutex_lock (&super_mutex);
198         while (p_mutex->locked)
199         {
200             p_mutex->contention++;
201             vlc_cond_wait (&super_variable, &super_mutex);
202             p_mutex->contention--;
203         }
204         p_mutex->locked = true;
205         vlc_mutex_unlock (&super_mutex);
206         vlc_restorecancel (canc);
207         return;
208     }
209
210     EnterCriticalSection (&p_mutex->mutex);
211 }
212
213 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
214 {
215     if (!p_mutex->dynamic)
216     {   /* static mutexes */
217         int ret = EBUSY;
218
219         assert (p_mutex != &super_mutex); /* this one cannot be static */
220         vlc_mutex_lock (&super_mutex);
221         if (!p_mutex->locked)
222         {
223             p_mutex->locked = true;
224             ret = 0;
225         }
226         vlc_mutex_unlock (&super_mutex);
227         return ret;
228     }
229
230     return TryEnterCriticalSection (&p_mutex->mutex) ? 0 : EBUSY;
231 }
232
233 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
234 {
235     if (!p_mutex->dynamic)
236     {   /* static mutexes */
237         assert (p_mutex != &super_mutex); /* this one cannot be static */
238
239         vlc_mutex_lock (&super_mutex);
240         assert (p_mutex->locked);
241         p_mutex->locked = false;
242         if (p_mutex->contention)
243             vlc_cond_broadcast (&super_variable);
244         vlc_mutex_unlock (&super_mutex);
245         return;
246     }
247
248     LeaveCriticalSection (&p_mutex->mutex);
249 }
250
251 /*** Condition variables ***/
252 enum
253 {
254     CLOCK_MONOTONIC,
255     CLOCK_REALTIME,
256 };
257
258 static void vlc_cond_init_common (vlc_cond_t *p_condvar, unsigned clock)
259 {
260     /* Create a manual-reset event (manual reset is needed for broadcast). */
261     p_condvar->handle = CreateEvent (NULL, TRUE, FALSE, NULL);
262     if (!p_condvar->handle)
263         abort();
264     p_condvar->clock = clock;
265 }
266
267 void vlc_cond_init (vlc_cond_t *p_condvar)
268 {
269     vlc_cond_init_common (p_condvar, CLOCK_MONOTONIC);
270 }
271
272 void vlc_cond_init_daytime (vlc_cond_t *p_condvar)
273 {
274     vlc_cond_init_common (p_condvar, CLOCK_REALTIME);
275 }
276
277 void vlc_cond_destroy (vlc_cond_t *p_condvar)
278 {
279     CloseHandle (p_condvar->handle);
280 }
281
282 void vlc_cond_signal (vlc_cond_t *p_condvar)
283 {
284     /* NOTE: This will cause a broadcast, that is wrong.
285      * This will also wake up the next waiting thread if no threads are yet
286      * waiting, which is also wrong. However both of these issues are allowed
287      * by the provision for spurious wakeups. Better have too many wakeups
288      * than too few (= deadlocks). */
289     SetEvent (p_condvar->handle);
290 }
291
292 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
293 {
294     SetEvent (p_condvar->handle);
295 }
296
297 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
298 {
299     DWORD result;
300
301     assert (p_mutex->dynamic); /* TODO */
302     do
303     {
304         vlc_testcancel ();
305         LeaveCriticalSection (&p_mutex->mutex);
306         result = WaitForSingleObjectEx (p_condvar->handle, INFINITE, TRUE);
307         EnterCriticalSection (&p_mutex->mutex);
308     }
309     while (result == WAIT_IO_COMPLETION);
310
311     assert (result != WAIT_ABANDONED); /* another thread failed to cleanup! */
312     assert (result != WAIT_FAILED);
313     ResetEvent (p_condvar->handle);
314 }
315
316 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
317                         mtime_t deadline)
318 {
319     DWORD result;
320
321     assert (p_mutex->dynamic); /* TODO */
322     do
323     {
324         vlc_testcancel ();
325
326         mtime_t total;
327         switch (p_condvar->clock)
328         {
329             case CLOCK_MONOTONIC:
330                 total = mdate();
331                 break;
332             case CLOCK_REALTIME: /* FIXME? sub-second precision */
333                 total = CLOCK_FREQ * time (NULL);
334                 break;
335             default:
336                 assert (0);
337         }
338         total = (deadline - total) / 1000;
339         if( total < 0 )
340             total = 0;
341
342         DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
343         LeaveCriticalSection (&p_mutex->mutex);
344         result = WaitForSingleObjectEx (p_condvar->handle, delay, TRUE);
345         EnterCriticalSection (&p_mutex->mutex);
346     }
347     while (result == WAIT_IO_COMPLETION);
348
349     assert (result != WAIT_ABANDONED);
350     assert (result != WAIT_FAILED);
351     ResetEvent (p_condvar->handle);
352
353     return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
354 }
355
356 /*** Semaphore ***/
357 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
358 {
359     *sem = CreateSemaphore (NULL, value, 0x7fffffff, NULL);
360     if (*sem == NULL)
361         abort ();
362 }
363
364 void vlc_sem_destroy (vlc_sem_t *sem)
365 {
366     CloseHandle (*sem);
367 }
368
369 int vlc_sem_post (vlc_sem_t *sem)
370 {
371     ReleaseSemaphore (*sem, 1, NULL);
372     return 0; /* FIXME */
373 }
374
375 void vlc_sem_wait (vlc_sem_t *sem)
376 {
377     DWORD result;
378
379     do
380     {
381         vlc_testcancel ();
382         result = WaitForSingleObjectEx (*sem, INFINITE, TRUE);
383     }
384     while (result == WAIT_IO_COMPLETION);
385 }
386
387 /*** Read/write locks */
388 /* SRW (Slim Read Write) locks are available in Vista+ only */
389 void vlc_rwlock_init (vlc_rwlock_t *lock)
390 {
391     vlc_mutex_init (&lock->mutex);
392     vlc_cond_init (&lock->read_wait);
393     vlc_cond_init (&lock->write_wait);
394     lock->readers = 0; /* active readers */
395     lock->writers = 0; /* waiting or active writers */
396     lock->writer = 0; /* ID of active writer */
397 }
398
399 /**
400  * Destroys an initialized unused read/write lock.
401  */
402 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
403 {
404     vlc_cond_destroy (&lock->read_wait);
405     vlc_cond_destroy (&lock->write_wait);
406     vlc_mutex_destroy (&lock->mutex);
407 }
408
409 /**
410  * Acquires a read/write lock for reading. Recursion is allowed.
411  */
412 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
413 {
414     vlc_mutex_lock (&lock->mutex);
415     while (lock->writer != 0)
416         vlc_cond_wait (&lock->read_wait, &lock->mutex);
417     if (lock->readers == ULONG_MAX)
418         abort ();
419     lock->readers++;
420     vlc_mutex_unlock (&lock->mutex);
421 }
422
423 /**
424  * Acquires a read/write lock for writing. Recursion is not allowed.
425  */
426 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
427 {
428     vlc_mutex_lock (&lock->mutex);
429     if (lock->writers == ULONG_MAX)
430         abort ();
431     lock->writers++;
432     while ((lock->readers > 0) || (lock->writer != 0))
433         vlc_cond_wait (&lock->write_wait, &lock->mutex);
434     lock->writers--;
435     lock->writer = GetCurrentThreadId ();
436     vlc_mutex_unlock (&lock->mutex);
437 }
438
439 /**
440  * Releases a read/write lock.
441  */
442 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
443 {
444     vlc_mutex_lock (&lock->mutex);
445     if (lock->readers > 0)
446         lock->readers--; /* Read unlock */
447     else
448         lock->writer = 0; /* Write unlock */
449
450     if (lock->writers > 0)
451     {
452         if (lock->readers == 0)
453             vlc_cond_signal (&lock->write_wait);
454     }
455     else
456         vlc_cond_broadcast (&lock->read_wait);
457     vlc_mutex_unlock (&lock->mutex);
458 }
459
460 /*** Thread-specific variables (TLS) ***/
461 struct vlc_threadvar
462 {
463     DWORD                 id;
464     void                (*destroy) (void *);
465     struct vlc_threadvar *prev;
466     struct vlc_threadvar *next;
467 } *vlc_threadvar_last = NULL;
468
469 int vlc_threadvar_create (vlc_threadvar_t *p_tls, void (*destr) (void *))
470 {
471     struct vlc_threadvar *var = malloc (sizeof (*var));
472     if (unlikely(var == NULL))
473         return errno;
474
475     var->id = TlsAlloc();
476     if (var->id == TLS_OUT_OF_INDEXES)
477     {
478         free (var);
479         return EAGAIN;
480     }
481     var->destroy = destr;
482     var->next = NULL;
483     *p_tls = var;
484
485     vlc_mutex_lock (&super_mutex);
486     var->prev = vlc_threadvar_last;
487     vlc_threadvar_last = var;
488     vlc_mutex_unlock (&super_mutex);
489     return 0;
490 }
491
492 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
493 {
494     struct vlc_threadvar *var = *p_tls;
495
496     vlc_mutex_lock (&super_mutex);
497     if (var->prev != NULL)
498         var->prev->next = var->next;
499     else
500         vlc_threadvar_last = var->next;
501     if (var->next != NULL)
502         var->next->prev = var->prev;
503     vlc_mutex_unlock (&super_mutex);
504
505     TlsFree (var->id);
506     free (var);
507 }
508
509 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
510 {
511     return TlsSetValue (key->id, value) ? ENOMEM : 0;
512 }
513
514 void *vlc_threadvar_get (vlc_threadvar_t key)
515 {
516     return TlsGetValue (key->id);
517 }
518
519 static void vlc_threadvar_cleanup (void)
520 {
521     vlc_threadvar_t key;
522
523 retry:
524     /* TODO: use RW lock or something similar */
525     vlc_mutex_lock (&super_mutex);
526     for (key = vlc_threadvar_last; key != NULL; key = key->prev)
527     {
528         void *value = vlc_threadvar_get (key);
529         if (value != NULL && key->destroy != NULL)
530         {
531             vlc_mutex_unlock (&super_mutex);
532             vlc_threadvar_set (key, NULL);
533             key->destroy (value);
534             goto retry;
535         }
536     }
537     vlc_mutex_unlock (&super_mutex);
538 }
539
540
541 /*** Threads ***/
542 void vlc_threads_setup (libvlc_int_t *p_libvlc)
543 {
544     (void) p_libvlc;
545 }
546
547 struct vlc_entry_data
548 {
549     void * (*func) (void *);
550     void *  data;
551     vlc_sem_t ready;
552 #ifdef UNDER_CE
553     HANDLE  cancel_event;
554 #endif
555 };
556
557 static unsigned __stdcall vlc_entry (void *p)
558 {
559     struct vlc_entry_data *entry = p;
560     vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
561     void *(*func) (void *) = entry->func;
562     void *data = entry->data;
563
564 #ifdef UNDER_CE
565     cancel_data.cancel_event = entry->cancel_event;
566 #endif
567     vlc_threadvar_set (cancel_key, &cancel_data);
568     vlc_sem_post (&entry->ready);
569     func (data);
570     vlc_threadvar_cleanup ();
571     return 0;
572 }
573
574 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
575                int priority)
576 {
577     int err = ENOMEM;
578     HANDLE hThread;
579
580     struct vlc_entry_data *entry_data = malloc (sizeof (*entry_data));
581     if (entry_data == NULL)
582         return ENOMEM;
583     entry_data->func = entry;
584     entry_data->data = data;
585     vlc_sem_init (&entry_data->ready, 0);
586
587 #ifndef UNDER_CE
588     /* When using the MSVCRT C library you have to use the _beginthreadex
589      * function instead of CreateThread, otherwise you'll end up with
590      * memory leaks and the signal functions not working (see Microsoft
591      * Knowledge Base, article 104641) */
592     hThread = (HANDLE)(uintptr_t)
593         _beginthreadex (NULL, 0, vlc_entry, entry_data, CREATE_SUSPENDED, NULL);
594     if (! hThread)
595     {
596         err = errno;
597         goto error;
598     }
599
600     *p_handle = hThread;
601
602 #else
603     vlc_thread_t th = malloc (sizeof (*th));
604     if (th == NULL)
605         goto error;
606     th->cancel_event = CreateEvent (NULL, FALSE, FALSE, NULL);
607     if (th->cancel_event == NULL)
608     {
609         free (th);
610         goto error;
611     }
612     entry_data->cancel_event = th->cancel_event;
613
614     /* Not sure if CREATE_SUSPENDED + ResumeThread() is any useful on WinCE.
615      * Thread handles act up, too. */
616     th->handle = CreateThread (NULL, 128*1024, vlc_entry, entry_data,
617                                CREATE_SUSPENDED, NULL);
618     if (th->handle == NULL)
619     {
620         CloseHandle (th->cancel_event);
621         free (th);
622         goto error;
623     }
624
625     *p_handle = th;
626     hThread = th->handle;
627
628 #endif
629
630     ResumeThread (hThread);
631     if (priority)
632         SetThreadPriority (hThread, priority);
633
634     /* Prevent cancellation until cancel_data is initialized. */
635     /* XXX: This could be postponed to vlc_cancel() or avoided completely by
636      * passing the "right" pointer to vlc_cancel_self(). */
637     vlc_sem_wait (&entry_data->ready);
638     vlc_sem_destroy (&entry_data->ready);
639     free (entry_data);
640
641     return 0;
642
643 error:
644     vlc_sem_destroy (&entry_data->ready);
645     free (entry_data);
646     return err;
647 }
648
649 void vlc_join (vlc_thread_t handle, void **result)
650 {
651 #ifdef UNDER_CE
652 # define handle handle->handle
653 #endif
654     do
655         vlc_testcancel ();
656     while (WaitForSingleObjectEx (handle, INFINITE, TRUE)
657                                                         == WAIT_IO_COMPLETION);
658
659     CloseHandle (handle);
660     assert (result == NULL); /* <- FIXME if ever needed */
661 #ifdef UNDER_CE
662 # undef handle
663     CloseHandle (handle->cancel_event);
664     free (handle);
665 #endif
666 }
667
668 void vlc_detach (vlc_thread_t handle)
669 {
670 #ifndef UNDER_CE
671     CloseHandle (handle);
672 #else
673     /* FIXME: handle->cancel_event leak */
674     CloseHandle (handle->handle);
675     free (handle);
676 #endif
677 }
678
679 /*** Thread cancellation ***/
680
681 /* APC procedure for thread cancellation */
682 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
683 {
684     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
685
686     if (likely(nfo != NULL))
687         nfo->killed = true;
688
689     (void)dummy;
690 }
691
692 void vlc_cancel (vlc_thread_t thread_id)
693 {
694 #ifndef UNDER_CE
695     QueueUserAPC (vlc_cancel_self, thread_id, 0);
696 #else
697     SetEvent (thread_id->cancel_event);
698 #endif
699 }
700
701 int vlc_savecancel (void)
702 {
703     int state;
704
705     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
706     if (nfo == NULL)
707         return false; /* Main thread - cannot be cancelled anyway */
708
709     state = nfo->killable;
710     nfo->killable = false;
711     return state;
712 }
713
714 void vlc_restorecancel (int state)
715 {
716     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
717     assert (state == false || state == true);
718
719     if (nfo == NULL)
720         return; /* Main thread - cannot be cancelled anyway */
721
722     assert (!nfo->killable);
723     nfo->killable = state != 0;
724 }
725
726 void vlc_testcancel (void)
727 {
728     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
729     if (nfo == NULL)
730         return; /* Main thread - cannot be cancelled anyway */
731
732     if (nfo->killable && nfo->killed)
733     {
734         for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
735              p->proc (p->data);
736         vlc_threadvar_cleanup ();
737 #ifndef UNDER_CE
738         _endthreadex(0);
739 #else
740         ExitThread(0);
741 #endif
742     }
743 }
744
745 void vlc_control_cancel (int cmd, ...)
746 {
747     /* NOTE: This function only modifies thread-specific data, so there is no
748      * need to lock anything. */
749     va_list ap;
750
751     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
752     if (nfo == NULL)
753         return; /* Main thread - cannot be cancelled anyway */
754
755     va_start (ap, cmd);
756     switch (cmd)
757     {
758         case VLC_CLEANUP_PUSH:
759         {
760             /* cleaner is a pointer to the caller stack, no need to allocate
761              * and copy anything. As a nice side effect, this cannot fail. */
762             vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
763             cleaner->next = nfo->cleaners;
764             nfo->cleaners = cleaner;
765             break;
766         }
767
768         case VLC_CLEANUP_POP:
769         {
770             nfo->cleaners = nfo->cleaners->next;
771             break;
772         }
773     }
774     va_end (ap);
775 }
776
777
778 /*** Timers ***/
779 struct vlc_timer
780 {
781 #ifndef UNDER_CE
782     HANDLE handle;
783 #else
784     unsigned id;
785     unsigned interval;
786 #endif
787     void (*func) (void *);
788     void *data;
789 };
790
791 #ifndef UNDER_CE
792 static void CALLBACK vlc_timer_do (void *val, BOOLEAN timeout)
793 {
794     struct vlc_timer *timer = val;
795
796     assert (timeout);
797     timer->func (timer->data);
798 }
799 #else
800 static void CALLBACK vlc_timer_do (unsigned timer_id, unsigned msg,
801                                    DWORD_PTR user, DWORD_PTR unused1,
802                                    DWORD_PTR unused2)
803 {
804     struct vlc_timer *timer = (struct vlc_timer *) user;
805     assert (timer_id == timer->id);
806     (void) msg;
807     (void) unused1;
808     (void) unused2;
809
810     timer->func (timer->data);
811
812     if (timer->interval)
813     {
814         mtime_t interval = timer->interval * 1000;
815         vlc_timer_schedule (timer, false, interval, interval);
816     }
817 }
818 #endif
819
820 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
821 {
822     struct vlc_timer *timer = malloc (sizeof (*timer));
823
824     if (timer == NULL)
825         return ENOMEM;
826     timer->func = func;
827     timer->data = data;
828 #ifndef UNDER_CE
829     timer->handle = INVALID_HANDLE_VALUE;
830 #else
831     timer->id = 0;
832     timer->interval = 0;
833 #endif
834     *id = timer;
835     return 0;
836 }
837
838 void vlc_timer_destroy (vlc_timer_t timer)
839 {
840 #ifndef UNDER_CE
841     if (timer->handle != INVALID_HANDLE_VALUE)
842         DeleteTimerQueueTimer (NULL, timer->handle, INVALID_HANDLE_VALUE);
843 #else
844     if (timer->id)
845         timeKillEvent (timer->id);
846     /* FIXME: timers that have not yet completed will trigger use-after-free */
847 #endif
848     free (timer);
849 }
850
851 void vlc_timer_schedule (vlc_timer_t timer, bool absolute,
852                          mtime_t value, mtime_t interval)
853 {
854 #ifndef UNDER_CE
855     if (timer->handle != INVALID_HANDLE_VALUE)
856     {
857         DeleteTimerQueueTimer (NULL, timer->handle, NULL);
858         timer->handle = INVALID_HANDLE_VALUE;
859     }
860 #else
861     if (timer->id)
862     {
863         timeKillEvent (timer->id);
864         timer->id = 0;
865         timer->interval = 0;
866     }
867 #endif
868     if (value == 0)
869         return; /* Disarm */
870
871     if (absolute)
872         value -= mdate ();
873     value = (value + 999) / 1000;
874     interval = (interval + 999) / 1000;
875
876 #ifndef UNDER_CE
877     if (!CreateTimerQueueTimer (&timer->handle, NULL, vlc_timer_do, timer,
878                                 value, interval, WT_EXECUTEDEFAULT))
879 #else
880     TIMECAPS caps;
881     timeGetDevCaps (&caps, sizeof(caps));
882
883     unsigned delay = value;
884     delay = __MAX(delay, caps.wPeriodMin);
885     delay = __MIN(delay, caps.wPeriodMax);
886
887     unsigned event = TIME_ONESHOT;
888
889     if (interval == delay)
890         event = TIME_PERIODIC;
891     else if (interval)
892         timer->interval = interval;
893
894     timer->id = timeSetEvent (delay, delay / 20, vlc_timer_do, (DWORD) timer,
895                               event);
896     if (!timer->id)
897 #endif
898         abort ();
899 }
900
901 unsigned vlc_timer_getoverrun (vlc_timer_t timer)
902 {
903     (void)timer;
904     return 0;
905 }