]> git.sesse.net Git - vlc/blob - src/win32/thread.c
win32: do not straddle on POSIX threads symbols
[vlc] / src / win32 / thread.c
1 /*****************************************************************************
2  * thread.c : Win32 back-end for LibVLC
3  *****************************************************************************
4  * Copyright (C) 1999-2009 VLC authors and VideoLAN
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 it
14  * under the terms of the GNU Lesser General Public License as published by
15  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * 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
40 /*** Static mutex and condition variable ***/
41 static vlc_mutex_t super_mutex;
42 static vlc_cond_t  super_variable;
43
44
45 /*** Common helpers ***/
46 static DWORD vlc_WaitForMultipleObjects (DWORD count, const HANDLE *handles,
47                                          DWORD delay)
48 {
49     DWORD ret;
50     if (count == 0)
51     {
52         ret = SleepEx (delay, TRUE);
53         if (ret == 0)
54             ret = WAIT_TIMEOUT;
55     }
56     else
57         ret = WaitForMultipleObjectsEx (count, handles, FALSE, delay, TRUE);
58
59     /* We do not abandon objects... this would be a bug */
60     assert (ret < WAIT_ABANDONED_0 || WAIT_ABANDONED_0 + count - 1 < ret);
61
62     if (unlikely(ret == WAIT_FAILED))
63         abort (); /* We are screwed! */
64     return ret;
65 }
66
67 static DWORD vlc_WaitForSingleObject (HANDLE handle, DWORD delay)
68 {
69     return vlc_WaitForMultipleObjects (1, &handle, delay);
70 }
71
72 static DWORD vlc_Sleep (DWORD delay)
73 {
74     DWORD ret = vlc_WaitForMultipleObjects (0, NULL, delay);
75     return (ret != WAIT_TIMEOUT) ? ret : 0;
76 }
77
78
79 /*** Mutexes ***/
80 void vlc_mutex_init( vlc_mutex_t *p_mutex )
81 {
82     /* This creates a recursive mutex. This is OK as fast mutexes have
83      * no defined behavior in case of recursive locking. */
84     InitializeCriticalSection (&p_mutex->mutex);
85     p_mutex->dynamic = true;
86 }
87
88 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
89 {
90     InitializeCriticalSection( &p_mutex->mutex );
91     p_mutex->dynamic = true;
92 }
93
94
95 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
96 {
97     assert (p_mutex->dynamic);
98     DeleteCriticalSection (&p_mutex->mutex);
99 }
100
101 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
102 {
103     if (!p_mutex->dynamic)
104     {   /* static mutexes */
105         int canc = vlc_savecancel ();
106         assert (p_mutex != &super_mutex); /* this one cannot be static */
107
108         vlc_mutex_lock (&super_mutex);
109         while (p_mutex->locked)
110         {
111             p_mutex->contention++;
112             vlc_cond_wait (&super_variable, &super_mutex);
113             p_mutex->contention--;
114         }
115         p_mutex->locked = true;
116         vlc_mutex_unlock (&super_mutex);
117         vlc_restorecancel (canc);
118         return;
119     }
120
121     EnterCriticalSection (&p_mutex->mutex);
122 }
123
124 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
125 {
126     if (!p_mutex->dynamic)
127     {   /* static mutexes */
128         int ret = EBUSY;
129
130         assert (p_mutex != &super_mutex); /* this one cannot be static */
131         vlc_mutex_lock (&super_mutex);
132         if (!p_mutex->locked)
133         {
134             p_mutex->locked = true;
135             ret = 0;
136         }
137         vlc_mutex_unlock (&super_mutex);
138         return ret;
139     }
140
141     return TryEnterCriticalSection (&p_mutex->mutex) ? 0 : EBUSY;
142 }
143
144 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
145 {
146     if (!p_mutex->dynamic)
147     {   /* static mutexes */
148         assert (p_mutex != &super_mutex); /* this one cannot be static */
149
150         vlc_mutex_lock (&super_mutex);
151         assert (p_mutex->locked);
152         p_mutex->locked = false;
153         if (p_mutex->contention)
154             vlc_cond_broadcast (&super_variable);
155         vlc_mutex_unlock (&super_mutex);
156         return;
157     }
158
159     LeaveCriticalSection (&p_mutex->mutex);
160 }
161
162 /*** Condition variables ***/
163 enum
164 {
165     VLC_CLOCK_STATIC=0, /* must be zero for VLC_STATIC_COND */
166     VLC_CLOCK_MONOTONIC,
167     VLC_CLOCK_REALTIME,
168 };
169
170 static void vlc_cond_init_common (vlc_cond_t *p_condvar, unsigned clock)
171 {
172     /* Create a manual-reset event (manual reset is needed for broadcast). */
173     p_condvar->handle = CreateEvent (NULL, TRUE, FALSE, NULL);
174     if (!p_condvar->handle)
175         abort();
176     p_condvar->clock = clock;
177 }
178
179 void vlc_cond_init (vlc_cond_t *p_condvar)
180 {
181     vlc_cond_init_common (p_condvar, VLC_CLOCK_MONOTONIC);
182 }
183
184 void vlc_cond_init_daytime (vlc_cond_t *p_condvar)
185 {
186     vlc_cond_init_common (p_condvar, VLC_CLOCK_REALTIME);
187 }
188
189 void vlc_cond_destroy (vlc_cond_t *p_condvar)
190 {
191     CloseHandle (p_condvar->handle);
192 }
193
194 void vlc_cond_signal (vlc_cond_t *p_condvar)
195 {
196     if (!p_condvar->clock)
197         return;
198
199     /* This is suboptimal but works. */
200     vlc_cond_broadcast (p_condvar);
201 }
202
203 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
204 {
205     if (!p_condvar->clock)
206         return;
207
208     /* Wake all threads up (as the event HANDLE has manual reset) */
209     SetEvent (p_condvar->handle);
210 }
211
212 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
213 {
214     DWORD result;
215
216     if (!p_condvar->clock)
217     {   /* FIXME FIXME FIXME */
218         msleep (50000);
219         return;
220     }
221
222     do
223     {
224         vlc_testcancel ();
225         vlc_mutex_unlock (p_mutex);
226         result = vlc_WaitForSingleObject (p_condvar->handle, INFINITE);
227         vlc_mutex_lock (p_mutex);
228     }
229     while (result == WAIT_IO_COMPLETION);
230
231     ResetEvent (p_condvar->handle);
232 }
233
234 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
235                         mtime_t deadline)
236 {
237     DWORD result;
238
239     do
240     {
241         vlc_testcancel ();
242
243         mtime_t total;
244         switch (p_condvar->clock)
245         {
246             case VLC_CLOCK_MONOTONIC:
247                 total = mdate();
248                 break;
249             case VLC_CLOCK_REALTIME: /* FIXME? sub-second precision */
250                 total = CLOCK_FREQ * time (NULL);
251                 break;
252             default:
253                 assert (!p_condvar->clock);
254                 /* FIXME FIXME FIXME */
255                 msleep (50000);
256                 return 0;
257         }
258         total = (deadline - total) / 1000;
259         if( total < 0 )
260             total = 0;
261
262         DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
263         vlc_mutex_unlock (p_mutex);
264         result = vlc_WaitForSingleObject (p_condvar->handle, delay);
265         vlc_mutex_lock (p_mutex);
266     }
267     while (result == WAIT_IO_COMPLETION);
268
269     ResetEvent (p_condvar->handle);
270
271     return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
272 }
273
274 /*** Semaphore ***/
275 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
276 {
277     *sem = CreateSemaphore (NULL, value, 0x7fffffff, NULL);
278     if (*sem == NULL)
279         abort ();
280 }
281
282 void vlc_sem_destroy (vlc_sem_t *sem)
283 {
284     CloseHandle (*sem);
285 }
286
287 int vlc_sem_post (vlc_sem_t *sem)
288 {
289     ReleaseSemaphore (*sem, 1, NULL);
290     return 0; /* FIXME */
291 }
292
293 void vlc_sem_wait (vlc_sem_t *sem)
294 {
295     DWORD result;
296
297     do
298     {
299         vlc_testcancel ();
300         result = vlc_WaitForSingleObject (*sem, INFINITE);
301     }
302     while (result == WAIT_IO_COMPLETION);
303 }
304
305 /*** Thread-specific variables (TLS) ***/
306 struct vlc_threadvar
307 {
308     DWORD                 id;
309     void                (*destroy) (void *);
310     struct vlc_threadvar *prev;
311     struct vlc_threadvar *next;
312 } *vlc_threadvar_last = NULL;
313
314 int vlc_threadvar_create (vlc_threadvar_t *p_tls, void (*destr) (void *))
315 {
316     struct vlc_threadvar *var = malloc (sizeof (*var));
317     if (unlikely(var == NULL))
318         return errno;
319
320     var->id = TlsAlloc();
321     if (var->id == TLS_OUT_OF_INDEXES)
322     {
323         free (var);
324         return EAGAIN;
325     }
326     var->destroy = destr;
327     var->next = NULL;
328     *p_tls = var;
329
330     vlc_mutex_lock (&super_mutex);
331     var->prev = vlc_threadvar_last;
332     if (var->prev)
333         var->prev->next = var;
334
335     vlc_threadvar_last = var;
336     vlc_mutex_unlock (&super_mutex);
337     return 0;
338 }
339
340 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
341 {
342     struct vlc_threadvar *var = *p_tls;
343
344     vlc_mutex_lock (&super_mutex);
345     if (var->prev != NULL)
346         var->prev->next = var->next;
347
348     if (var->next != NULL)
349         var->next->prev = var->prev;
350     else
351         vlc_threadvar_last = var->prev;
352
353     vlc_mutex_unlock (&super_mutex);
354
355     TlsFree (var->id);
356     free (var);
357 }
358
359 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
360 {
361     return TlsSetValue (key->id, value) ? ENOMEM : 0;
362 }
363
364 void *vlc_threadvar_get (vlc_threadvar_t key)
365 {
366     return TlsGetValue (key->id);
367 }
368
369 /*** Threads ***/
370 static vlc_threadvar_t thread_key;
371
372 /** Per-thread data */
373 struct vlc_thread
374 {
375     HANDLE         id;
376
377     bool           detached;
378     bool           killable;
379     bool           killed;
380     vlc_cleanup_t *cleaners;
381
382     void        *(*entry) (void *);
383     void          *data;
384 };
385
386 static void vlc_thread_cleanup (struct vlc_thread *th)
387 {
388     vlc_threadvar_t key;
389
390 retry:
391     /* TODO: use RW lock or something similar */
392     vlc_mutex_lock (&super_mutex);
393     for (key = vlc_threadvar_last; key != NULL; key = key->prev)
394     {
395         void *value = vlc_threadvar_get (key);
396         if (value != NULL && key->destroy != NULL)
397         {
398             vlc_mutex_unlock (&super_mutex);
399             vlc_threadvar_set (key, NULL);
400             key->destroy (value);
401             goto retry;
402         }
403     }
404     vlc_mutex_unlock (&super_mutex);
405
406     if (th->detached)
407     {
408         CloseHandle (th->id);
409         free (th);
410     }
411 }
412
413 static unsigned __stdcall vlc_entry (void *p)
414 {
415     struct vlc_thread *th = p;
416
417     vlc_threadvar_set (thread_key, th);
418     th->killable = true;
419     th->data = th->entry (th->data);
420     vlc_thread_cleanup (th);
421     return 0;
422 }
423
424 static int vlc_clone_attr (vlc_thread_t *p_handle, bool detached,
425                            void *(*entry) (void *), void *data, int priority)
426 {
427     struct vlc_thread *th = malloc (sizeof (*th));
428     if (unlikely(th == NULL))
429         return ENOMEM;
430     th->entry = entry;
431     th->data = data;
432     th->detached = detached;
433     th->killable = false; /* not until vlc_entry() ! */
434     th->killed = false;
435     th->cleaners = NULL;
436
437     HANDLE hThread;
438     /* When using the MSVCRT C library you have to use the _beginthreadex
439      * function instead of CreateThread, otherwise you'll end up with
440      * memory leaks and the signal functions not working (see Microsoft
441      * Knowledge Base, article 104641) */
442     uintptr_t h;
443
444     h = _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
445     if (h == 0)
446     {
447         int err = errno;
448         free (th);
449         return err;
450     }
451     hThread = (HANDLE)h;
452
453     /* Thread is suspended, so we can safely set th->id */
454     th->id = hThread;
455     if (p_handle != NULL)
456         *p_handle = th;
457
458     if (priority)
459         SetThreadPriority (hThread, priority);
460
461     ResumeThread (hThread);
462
463     return 0;
464 }
465
466 int vlc_clone (vlc_thread_t *p_handle, void *(*entry) (void *),
467                 void *data, int priority)
468 {
469     return vlc_clone_attr (p_handle, false, entry, data, priority);
470 }
471
472 void vlc_join (vlc_thread_t th, void **result)
473 {
474     do
475         vlc_testcancel ();
476     while (vlc_WaitForSingleObject (th->id, INFINITE) == WAIT_IO_COMPLETION);
477
478     if (result != NULL)
479         *result = th->data;
480     CloseHandle (th->id);
481     free (th);
482 }
483
484 int vlc_clone_detach (vlc_thread_t *p_handle, void *(*entry) (void *),
485                       void *data, int priority)
486 {
487     vlc_thread_t th;
488     if (p_handle == NULL)
489         p_handle = &th;
490
491     return vlc_clone_attr (p_handle, true, entry, data, priority);
492 }
493
494 int vlc_set_priority (vlc_thread_t th, int priority)
495 {
496     if (!SetThreadPriority (th->id, priority))
497         return VLC_EGENERIC;
498     return VLC_SUCCESS;
499 }
500
501 /*** Thread cancellation ***/
502
503 /* APC procedure for thread cancellation */
504 static void CALLBACK vlc_cancel_self (ULONG_PTR self)
505 {
506     struct vlc_thread *th = (void *)self;
507
508     if (likely(th != NULL))
509         th->killed = true;
510 }
511
512 void vlc_cancel (vlc_thread_t th)
513 {
514     QueueUserAPC (vlc_cancel_self, th->id, (uintptr_t)th);
515 }
516
517 int vlc_savecancel (void)
518 {
519     struct vlc_thread *th = vlc_threadvar_get (thread_key);
520     if (th == NULL)
521         return false; /* Main thread - cannot be cancelled anyway */
522
523     int state = th->killable;
524     th->killable = false;
525     return state;
526 }
527
528 void vlc_restorecancel (int state)
529 {
530     struct vlc_thread *th = vlc_threadvar_get (thread_key);
531     assert (state == false || state == true);
532
533     if (th == NULL)
534         return; /* Main thread - cannot be cancelled anyway */
535
536     assert (!th->killable);
537     th->killable = state != 0;
538 }
539
540 void vlc_testcancel (void)
541 {
542     struct vlc_thread *th = vlc_threadvar_get (thread_key);
543     if (th == NULL)
544         return; /* Main thread - cannot be cancelled anyway */
545
546     if (th->killable && th->killed)
547     {
548         for (vlc_cleanup_t *p = th->cleaners; p != NULL; p = p->next)
549              p->proc (p->data);
550
551         th->data = NULL; /* TODO: special value? */
552         vlc_thread_cleanup (th);
553         _endthreadex(0);
554     }
555 }
556
557 void vlc_control_cancel (int cmd, ...)
558 {
559     /* NOTE: This function only modifies thread-specific data, so there is no
560      * need to lock anything. */
561     va_list ap;
562
563     struct vlc_thread *th = vlc_threadvar_get (thread_key);
564     if (th == NULL)
565         return; /* Main thread - cannot be cancelled anyway */
566
567     va_start (ap, cmd);
568     switch (cmd)
569     {
570         case VLC_CLEANUP_PUSH:
571         {
572             /* cleaner is a pointer to the caller stack, no need to allocate
573              * and copy anything. As a nice side effect, this cannot fail. */
574             vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
575             cleaner->next = th->cleaners;
576             th->cleaners = cleaner;
577             break;
578         }
579
580         case VLC_CLEANUP_POP:
581         {
582             th->cleaners = th->cleaners->next;
583             break;
584         }
585     }
586     va_end (ap);
587 }
588
589 /*** Clock ***/
590 static CRITICAL_SECTION clock_lock;
591
592 static mtime_t mdate_giveup (void)
593 {
594     abort ();
595 }
596
597 static mtime_t (*mdate_selected) (void) = mdate_giveup;
598
599 mtime_t mdate (void)
600 {
601     return mdate_selected ();
602 }
603
604 static union
605 {
606     struct
607     {
608 #if (_WIN32_WINNT < 0x0601)
609         BOOL (*query) (PULONGLONG);
610 #endif
611     } interrupt;
612     struct
613     {
614 #if (_WIN32_WINNT < 0x0600)
615         ULONGLONG (*get) (void);
616 #endif
617     } tick;
618     struct
619     {
620         LARGE_INTEGER freq;
621     } perf;
622 } clk;
623
624 static mtime_t mdate_interrupt (void)
625 {
626     ULONGLONG ts;
627     BOOL ret;
628
629 #if (_WIN32_WINNT >= 0x0601)
630     ret = QueryUnbiasedInterruptTime (&ts);
631 #else
632     ret = clk.interrupt.query (&ts);
633 #endif
634     if (unlikely(!ret))
635         abort ();
636
637     /* hundreds of nanoseconds */
638     static_assert ((10000000 % CLOCK_FREQ) == 0, "Broken frequencies ratio");
639     return ts / (10000000 / CLOCK_FREQ);
640 }
641
642 static mtime_t mdate_tick (void)
643 {
644 #if (_WIN32_WINNT >= 0x0600)
645     ULONGLONG ts = GetTickCount64 ();
646 #else
647     ULONGLONG ts = clk.tick.get ();
648 #endif
649
650     /* milliseconds */
651     static_assert ((CLOCK_FREQ % 1000) == 0, "Broken frequencies ratio");
652     return ts * (CLOCK_FREQ / 1000);
653 }
654 #if !VLC_WINSTORE_APP
655 #include <mmsystem.h>
656 static mtime_t mdate_multimedia (void)
657 {
658      DWORD ts = timeGetTime ();
659
660     /* milliseconds */
661     static_assert ((CLOCK_FREQ % 1000) == 0, "Broken frequencies ratio");
662     return ts * (CLOCK_FREQ / 1000);
663 }
664 #endif
665
666 static mtime_t mdate_perf (void)
667 {
668     /* We don't need the real date, just the value of a high precision timer */
669     LARGE_INTEGER counter;
670     if (!QueryPerformanceCounter (&counter))
671         abort ();
672
673     /* Convert to from (1/freq) to microsecond resolution */
674     /* We need to split the division to avoid 63-bits overflow */
675     lldiv_t d = lldiv (counter.QuadPart, clk.perf.freq.QuadPart);
676
677     return (d.quot * 1000000) + ((d.rem * 1000000) / clk.perf.freq.QuadPart);
678 }
679
680 static mtime_t mdate_wall (void)
681 {
682     FILETIME ts;
683     ULARGE_INTEGER s;
684
685 #if (_WIN32_WINNT >= 0x0602) && !VLC_WINSTORE_APP
686     GetSystemTimePreciseAsFileTime (&ts);
687 #else
688     GetSystemTimeAsFileTime (&ts);
689 #endif
690     s.LowPart = ts.dwLowDateTime;
691     s.HighPart = ts.dwHighDateTime;
692     /* hundreds of nanoseconds */
693     static_assert ((10000000 % CLOCK_FREQ) == 0, "Broken frequencies ratio");
694     return s.QuadPart / (10000000 / CLOCK_FREQ);
695 }
696
697 #undef mwait
698 void mwait (mtime_t deadline)
699 {
700     mtime_t delay;
701
702     vlc_testcancel();
703     while ((delay = (deadline - mdate())) > 0)
704     {
705         delay /= 1000;
706         if (unlikely(delay > 0x7fffffff))
707             delay = 0x7fffffff;
708         vlc_Sleep (delay);
709         vlc_testcancel();
710     }
711 }
712
713 #undef msleep
714 void msleep (mtime_t delay)
715 {
716     mwait (mdate () + delay);
717 }
718
719 static void SelectClockSource (vlc_object_t *obj)
720 {
721     EnterCriticalSection (&clock_lock);
722     if (mdate_selected != mdate_giveup)
723     {
724         LeaveCriticalSection (&clock_lock);
725         return;
726     }
727
728 #if VLC_WINSTORE_APP
729     const char *name = "perf";
730 #else
731     const char *name = "multimedia";
732 #endif
733     char *str = var_InheritString (obj, "clock-source");
734     if (str != NULL)
735         name = str;
736     if (!strcmp (name, "interrupt"))
737     {
738         msg_Dbg (obj, "using interrupt time as clock source");
739 #if (_WIN32_WINNT < 0x0601)
740         HANDLE h = GetModuleHandle (_T("kernel32.dll"));
741         if (unlikely(h == NULL))
742             abort ();
743         clk.interrupt.query = (void *)GetProcAddress (h,
744                                                       "QueryUnbiasedInterruptTime");
745         if (unlikely(clk.interrupt.query == NULL))
746             abort ();
747 #endif
748         mdate_selected = mdate_interrupt;
749     }
750     else
751     if (!strcmp (name, "tick"))
752     {
753         msg_Dbg (obj, "using Windows time as clock source");
754 #if (_WIN32_WINNT < 0x0600)
755         HANDLE h = GetModuleHandle (_T("kernel32.dll"));
756         if (unlikely(h == NULL))
757             abort ();
758         clk.tick.get = (void *)GetProcAddress (h, "GetTickCount64");
759         if (unlikely(clk.tick.get == NULL))
760             abort ();
761 #endif
762         mdate_selected = mdate_tick;
763     }
764 #if !VLC_WINSTORE_APP
765     else
766     if (!strcmp (name, "multimedia"))
767     {
768         TIMECAPS caps;
769
770         msg_Dbg (obj, "using multimedia timers as clock source");
771         if (timeGetDevCaps (&caps, sizeof (caps)) != MMSYSERR_NOERROR)
772             abort ();
773         msg_Dbg (obj, " min period: %u ms, max period: %u ms",
774                  caps.wPeriodMin, caps.wPeriodMax);
775         mdate_selected = mdate_multimedia;
776     }
777 #endif
778     else
779     if (!strcmp (name, "perf"))
780     {
781         msg_Dbg (obj, "using performance counters as clock source");
782         if (!QueryPerformanceFrequency (&clk.perf.freq))
783             abort ();
784         msg_Dbg (obj, " frequency: %llu Hz", clk.perf.freq.QuadPart);
785         mdate_selected = mdate_perf;
786     }
787     else
788     if (!strcmp (name, "wall"))
789     {
790         msg_Dbg (obj, "using system time as clock source");
791         mdate_selected = mdate_wall;
792     }
793     else
794     {
795         msg_Err (obj, "invalid clock source \"%s\"", name);
796         abort ();
797     }
798     LeaveCriticalSection (&clock_lock);
799     free (str);
800 }
801
802 #define xstrdup(str) (strdup(str) ?: (abort(), NULL))
803
804 size_t EnumClockSource (vlc_object_t *obj, const char *var,
805                         char ***vp, char ***np)
806 {
807     const size_t max = 6;
808     char **values = xmalloc (sizeof (*values) * max);
809     char **names = xmalloc (sizeof (*names) * max);
810     size_t n = 0;
811
812 #if (_WIN32_WINNT < 0x0601)
813     DWORD version = LOWORD(GetVersion());
814     version = (LOBYTE(version) << 8) | (HIBYTE(version) << 0);
815 #endif
816
817     values[n] = xstrdup ("");
818     names[n] = xstrdup (_("Auto"));
819     n++;
820 #if (_WIN32_WINNT < 0x0601)
821     if (version >= 0x0601)
822 #endif
823     {
824         values[n] = xstrdup ("interrupt");
825         names[n] = xstrdup ("Interrupt time");
826         n++;
827     }
828 #if (_WIN32_WINNT < 0x0600)
829     if (version >= 0x0600)
830 #endif
831     {
832         values[n] = xstrdup ("tick");
833         names[n] = xstrdup ("Windows time");
834         n++;
835     }
836 #if !VLC_WINSTORE_APP
837     values[n] = xstrdup ("multimedia");
838     names[n] = xstrdup ("Multimedia timers");
839     n++;
840 #endif
841     values[n] = xstrdup ("perf");
842     names[n] = xstrdup ("Performance counters");
843     n++;
844     values[n] = xstrdup ("wall");
845     names[n] = xstrdup ("System time (DANGEROUS!)");
846     n++;
847
848     *vp = values;
849     *np = names;
850     (void) obj; (void) var;
851     return n;
852 }
853
854
855 /*** Timers ***/
856 struct vlc_timer
857 {
858     HANDLE handle;
859     void (*func) (void *);
860     void *data;
861 };
862
863 static void CALLBACK vlc_timer_do (void *val, BOOLEAN timeout)
864 {
865     struct vlc_timer *timer = val;
866
867     assert (timeout);
868     timer->func (timer->data);
869 }
870
871 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
872 {
873     struct vlc_timer *timer = malloc (sizeof (*timer));
874
875     if (timer == NULL)
876         return ENOMEM;
877     timer->func = func;
878     timer->data = data;
879     timer->handle = INVALID_HANDLE_VALUE;
880     *id = timer;
881     return 0;
882 }
883
884 void vlc_timer_destroy (vlc_timer_t timer)
885 {
886     if (timer->handle != INVALID_HANDLE_VALUE)
887         DeleteTimerQueueTimer (NULL, timer->handle, INVALID_HANDLE_VALUE);
888     free (timer);
889 }
890
891 void vlc_timer_schedule (vlc_timer_t timer, bool absolute,
892                          mtime_t value, mtime_t interval)
893 {
894     if (timer->handle != INVALID_HANDLE_VALUE)
895     {
896         DeleteTimerQueueTimer (NULL, timer->handle, NULL);
897         timer->handle = INVALID_HANDLE_VALUE;
898     }
899     if (value == 0)
900         return; /* Disarm */
901
902     if (absolute)
903         value -= mdate ();
904     value = (value + 999) / 1000;
905     interval = (interval + 999) / 1000;
906
907     if (!CreateTimerQueueTimer (&timer->handle, NULL, vlc_timer_do, timer,
908                                 value, interval, WT_EXECUTEDEFAULT))
909         abort ();
910 }
911
912 unsigned vlc_timer_getoverrun (vlc_timer_t timer)
913 {
914     (void)timer;
915     return 0;
916 }
917
918
919 /*** CPU ***/
920 unsigned vlc_GetCPUCount (void)
921 {
922     SYSTEM_INFO systemInfo;
923
924     GetNativeSystemInfo(&systemInfo);
925
926     return systemInfo.dwNumberOfProcessors;
927 }
928
929
930 /*** Initialization ***/
931 void vlc_threads_setup (libvlc_int_t *p_libvlc)
932 {
933     SelectClockSource (VLC_OBJECT(p_libvlc));
934 }
935
936 extern vlc_rwlock_t config_lock;
937 BOOL WINAPI DllMain (HINSTANCE, DWORD, LPVOID);
938
939 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
940 {
941     (void) hinstDll;
942     (void) lpvReserved;
943
944     switch (fdwReason)
945     {
946         case DLL_PROCESS_ATTACH:
947             InitializeCriticalSection (&clock_lock);
948             vlc_mutex_init (&super_mutex);
949             vlc_cond_init (&super_variable);
950             vlc_threadvar_create (&thread_key, NULL);
951             vlc_rwlock_init (&config_lock);
952             vlc_CPU_init ();
953             break;
954
955         case DLL_PROCESS_DETACH:
956             vlc_rwlock_destroy (&config_lock);
957             vlc_threadvar_delete (&thread_key);
958             vlc_cond_destroy (&super_variable);
959             vlc_mutex_destroy (&super_mutex);
960             DeleteCriticalSection (&clock_lock);
961             break;
962     }
963     return TRUE;
964 }