svcdsub: Use existing helper
[vlc.git] / src / win32 / thread.c
blobf370a781f0279f2c518e1d99b2d2d309d4436806
1 /*****************************************************************************
2 * thread.c : Win32 back-end for LibVLC
3 *****************************************************************************
4 * Copyright (C) 1999-2016 VLC authors and VideoLAN
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
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.
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.
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 *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
32 #include <vlc_common.h>
33 #include <vlc_atomic.h>
35 #include "libvlc.h"
36 #include <stdarg.h>
37 #include <assert.h>
38 #include <limits.h>
39 #include <errno.h>
40 #include <time.h>
41 #if !VLC_WINSTORE_APP
42 #include <mmsystem.h>
43 #endif
45 /*** Static mutex and condition variable ***/
46 static CRITICAL_SECTION super_mutex;
47 static CONDITION_VARIABLE super_variable;
49 #define IS_INTERRUPTIBLE (!VLC_WINSTORE_APP || _WIN32_WINNT >= 0x0A00)
51 /*** Threads ***/
52 static DWORD thread_key;
54 struct vlc_thread
56 HANDLE id;
58 bool killable;
59 atomic_bool killed;
60 vlc_cleanup_t *cleaners;
62 void *(*entry) (void *);
63 void *data;
65 struct
67 atomic_int *addr;
68 CRITICAL_SECTION lock;
69 } wait;
72 /*** Condition variables (low-level) ***/
73 #if (_WIN32_WINNT < _WIN32_WINNT_VISTA)
74 static VOID (WINAPI *InitializeConditionVariable_)(PCONDITION_VARIABLE);
75 #define InitializeConditionVariable InitializeConditionVariable_
76 static BOOL (WINAPI *SleepConditionVariableCS_)(PCONDITION_VARIABLE,
77 PCRITICAL_SECTION, DWORD);
78 #define SleepConditionVariableCS SleepConditionVariableCS_
79 static VOID (WINAPI *WakeAllConditionVariable_)(PCONDITION_VARIABLE);
80 #define WakeAllConditionVariable WakeAllConditionVariable_
82 static void WINAPI DummyConditionVariable(CONDITION_VARIABLE *cv)
84 (void) cv;
87 static BOOL WINAPI SleepConditionVariableFallback(CONDITION_VARIABLE *cv,
88 CRITICAL_SECTION *cs,
89 DWORD ms)
91 (void) cv;
92 LeaveCriticalSection(cs);
93 SleepEx(ms > 5 ? 5 : ms, TRUE);
94 EnterCriticalSection(cs);
95 return ms != 0;
97 #endif
99 /*** Mutexes ***/
100 void vlc_mutex_init( vlc_mutex_t *p_mutex )
102 /* This creates a recursive mutex. This is OK as fast mutexes have
103 * no defined behavior in case of recursive locking. */
104 InitializeCriticalSection (&p_mutex->mutex);
105 p_mutex->dynamic = true;
108 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
110 InitializeCriticalSection( &p_mutex->mutex );
111 p_mutex->dynamic = true;
115 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
117 assert (p_mutex->dynamic);
118 DeleteCriticalSection (&p_mutex->mutex);
121 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
123 if (!p_mutex->dynamic)
124 { /* static mutexes */
125 EnterCriticalSection(&super_mutex);
126 while (p_mutex->locked)
128 p_mutex->contention++;
129 SleepConditionVariableCS(&super_variable, &super_mutex, INFINITE);
130 p_mutex->contention--;
132 p_mutex->locked = true;
133 LeaveCriticalSection(&super_mutex);
134 return;
137 EnterCriticalSection (&p_mutex->mutex);
140 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
142 if (!p_mutex->dynamic)
143 { /* static mutexes */
144 int ret = EBUSY;
146 EnterCriticalSection(&super_mutex);
147 if (!p_mutex->locked)
149 p_mutex->locked = true;
150 ret = 0;
152 LeaveCriticalSection(&super_mutex);
153 return ret;
156 return TryEnterCriticalSection (&p_mutex->mutex) ? 0 : EBUSY;
159 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
161 if (!p_mutex->dynamic)
162 { /* static mutexes */
163 EnterCriticalSection(&super_mutex);
164 assert (p_mutex->locked);
165 p_mutex->locked = false;
166 if (p_mutex->contention)
167 WakeAllConditionVariable(&super_variable);
168 LeaveCriticalSection(&super_mutex);
169 return;
172 LeaveCriticalSection (&p_mutex->mutex);
175 /*** Semaphore ***/
176 #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
177 # include <stdalign.h>
179 static inline HANDLE *vlc_sem_handle_p(vlc_sem_t *sem)
181 /* NOTE: vlc_sem_t layout cannot easily depend on Windows version */
182 static_assert (sizeof (HANDLE) <= sizeof (vlc_sem_t), "Size mismatch!");
183 static_assert ((alignof (HANDLE) % alignof (vlc_sem_t)) == 0,
184 "Alignment mismatch");
185 return (HANDLE *)sem;
187 #define vlc_sem_handle(sem) (*vlc_sem_handle_p(sem))
189 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
191 HANDLE handle = CreateSemaphore(NULL, value, 0x7fffffff, NULL);
192 if (handle == NULL)
193 abort ();
195 vlc_sem_handle(sem) = handle;
198 void vlc_sem_destroy (vlc_sem_t *sem)
200 CloseHandle(vlc_sem_handle(sem));
203 int vlc_sem_post (vlc_sem_t *sem)
205 ReleaseSemaphore(vlc_sem_handle(sem), 1, NULL);
206 return 0; /* FIXME */
209 void vlc_sem_wait (vlc_sem_t *sem)
211 HANDLE handle = vlc_sem_handle(sem);
212 DWORD result;
216 vlc_testcancel ();
217 result = WaitForSingleObjectEx(handle, INFINITE, TRUE);
219 /* Semaphore abandoned would be a bug. */
220 assert(result != WAIT_ABANDONED_0);
222 while (result == WAIT_IO_COMPLETION || result == WAIT_FAILED);
224 #endif
226 /*** Thread-specific variables (TLS) ***/
227 struct vlc_threadvar
229 DWORD id;
230 void (*destroy) (void *);
231 struct vlc_threadvar *prev;
232 struct vlc_threadvar *next;
233 } *vlc_threadvar_last = NULL;
235 int vlc_threadvar_create (vlc_threadvar_t *p_tls, void (*destr) (void *))
237 struct vlc_threadvar *var = malloc (sizeof (*var));
238 if (unlikely(var == NULL))
239 return errno;
241 var->id = TlsAlloc();
242 if (var->id == TLS_OUT_OF_INDEXES)
244 free (var);
245 return EAGAIN;
247 var->destroy = destr;
248 var->next = NULL;
249 *p_tls = var;
251 EnterCriticalSection(&super_mutex);
252 var->prev = vlc_threadvar_last;
253 if (var->prev)
254 var->prev->next = var;
256 vlc_threadvar_last = var;
257 LeaveCriticalSection(&super_mutex);
258 return 0;
261 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
263 struct vlc_threadvar *var = *p_tls;
265 EnterCriticalSection(&super_mutex);
266 if (var->prev != NULL)
267 var->prev->next = var->next;
269 if (var->next != NULL)
270 var->next->prev = var->prev;
271 else
272 vlc_threadvar_last = var->prev;
274 LeaveCriticalSection(&super_mutex);
276 TlsFree (var->id);
277 free (var);
280 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
282 int saved = GetLastError ();
284 if (!TlsSetValue(key->id, value))
285 return ENOMEM;
287 SetLastError(saved);
288 return 0;
291 void *vlc_threadvar_get (vlc_threadvar_t key)
293 int saved = GetLastError ();
294 void *value = TlsGetValue (key->id);
296 SetLastError(saved);
297 return value;
300 static void vlc_threadvars_cleanup(void)
302 vlc_threadvar_t key;
303 retry:
304 /* TODO: use RW lock or something similar */
305 EnterCriticalSection(&super_mutex);
306 for (key = vlc_threadvar_last; key != NULL; key = key->prev)
308 void *value = vlc_threadvar_get(key);
309 if (value != NULL && key->destroy != NULL)
311 LeaveCriticalSection(&super_mutex);
312 vlc_threadvar_set(key, NULL);
313 key->destroy(value);
314 goto retry;
317 LeaveCriticalSection(&super_mutex);
320 /*** Futeces^WAddress waits ***/
321 #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
322 static BOOL (WINAPI *WaitOnAddress_)(VOID volatile *, PVOID, SIZE_T, DWORD);
323 #define WaitOnAddress (*WaitOnAddress_)
324 static VOID (WINAPI *WakeByAddressAll_)(PVOID);
325 #define WakeByAddressAll (*WakeByAddressAll_)
326 static VOID (WINAPI *WakeByAddressSingle_)(PVOID);
327 #define WakeByAddressSingle (*WakeByAddressSingle_)
329 static struct wait_addr_bucket
331 CRITICAL_SECTION lock;
332 CONDITION_VARIABLE wait;
333 } wait_addr_buckets[32];
335 static struct wait_addr_bucket *wait_addr_get_bucket(void volatile *addr)
337 uintptr_t u = (uintptr_t)addr;
339 return wait_addr_buckets + ((u >> 3) % ARRAY_SIZE(wait_addr_buckets));
342 static void vlc_wait_addr_init(void)
344 for (size_t i = 0; i < ARRAY_SIZE(wait_addr_buckets); i++)
346 struct wait_addr_bucket *bucket = wait_addr_buckets + i;
348 InitializeCriticalSection(&bucket->lock);
349 InitializeConditionVariable(&bucket->wait);
353 static void vlc_wait_addr_deinit(void)
355 for (size_t i = 0; i < ARRAY_SIZE(wait_addr_buckets); i++)
357 struct wait_addr_bucket *bucket = wait_addr_buckets + i;
359 DeleteCriticalSection(&bucket->lock);
363 static BOOL WINAPI WaitOnAddressFallback(void volatile *addr, void *value,
364 SIZE_T size, DWORD ms)
366 struct wait_addr_bucket *bucket = wait_addr_get_bucket(addr);
367 uint64_t futex, val = 0;
368 BOOL ret = 0;
370 EnterCriticalSection(&bucket->lock);
372 switch (size)
374 case 1:
375 futex = atomic_load_explicit((atomic_char *)addr,
376 memory_order_relaxed);
377 val = *(const char *)value;
378 break;
379 case 2:
380 futex = atomic_load_explicit((atomic_short *)addr,
381 memory_order_relaxed);
382 val = *(const short *)value;
383 break;
384 case 4:
385 futex = atomic_load_explicit((atomic_int *)addr,
386 memory_order_relaxed);
387 val = *(const int *)value;
388 break;
389 case 8:
390 futex = atomic_load_explicit((atomic_llong *)addr,
391 memory_order_relaxed);
392 val = *(const long long *)value;
393 break;
394 default:
395 vlc_assert_unreachable();
398 if (futex == val)
399 ret = SleepConditionVariableCS(&bucket->wait, &bucket->lock, ms);
401 LeaveCriticalSection(&bucket->lock);
402 return ret;
405 static void WINAPI WakeByAddressFallback(void *addr)
407 struct wait_addr_bucket *bucket = wait_addr_get_bucket(addr);
409 /* Acquire the bucket critical section (only) to enforce proper sequencing.
410 * The critical section does not protect any actual memory object. */
411 EnterCriticalSection(&bucket->lock);
412 /* No other threads can hold the lock for this bucket while it is held
413 * here. Thus any other thread either:
414 * - is already sleeping in SleepConditionVariableCS(), and to be woken up
415 * by the following WakeAllConditionVariable(), or
416 * - has yet to retrieve the value at the wait address (with the
417 * 'switch (size)' block). */
418 LeaveCriticalSection(&bucket->lock);
419 /* At this point, other threads can retrieve the value at the wait address.
420 * But the value will have already been changed by our call site, thus
421 * (futex == val) will be false, and the threads will not go to sleep. */
423 /* Wake up any thread that was already sleeping. Since there are more than
424 * one wait address per bucket, all threads must be woken up :-/ */
425 WakeAllConditionVariable(&bucket->wait);
427 #endif
429 void vlc_addr_wait(void *addr, unsigned val)
431 WaitOnAddress(addr, &val, sizeof (val), -1);
434 bool vlc_addr_timedwait(void *addr, unsigned val, mtime_t delay)
436 delay = (delay + 999) / 1000;
438 if (delay > 0x7fffffff)
440 WaitOnAddress(addr, &val, sizeof (val), 0x7fffffff);
441 return true; /* woke up early, claim spurious wake-up */
444 return WaitOnAddress(addr, &val, sizeof (val), delay);
447 void vlc_addr_signal(void *addr)
449 WakeByAddressSingle(addr);
452 void vlc_addr_broadcast(void *addr)
454 WakeByAddressAll(addr);
457 /*** Threads ***/
458 static void vlc_thread_destroy(vlc_thread_t th)
460 DeleteCriticalSection(&th->wait.lock);
461 free(th);
464 static unsigned __stdcall vlc_entry (void *p)
466 struct vlc_thread *th = p;
468 TlsSetValue(thread_key, th);
469 th->killable = true;
470 th->data = th->entry (th->data);
471 TlsSetValue(thread_key, NULL);
473 if (th->id == NULL) /* Detached thread */
474 vlc_thread_destroy(th);
475 return 0;
478 static int vlc_clone_attr (vlc_thread_t *p_handle, bool detached,
479 void *(*entry) (void *), void *data, int priority)
481 struct vlc_thread *th = malloc (sizeof (*th));
482 if (unlikely(th == NULL))
483 return ENOMEM;
484 th->entry = entry;
485 th->data = data;
486 th->killable = false; /* not until vlc_entry() ! */
487 atomic_init(&th->killed, false);
488 th->cleaners = NULL;
489 th->wait.addr = NULL;
490 InitializeCriticalSection(&th->wait.lock);
492 /* When using the MSVCRT C library you have to use the _beginthreadex
493 * function instead of CreateThread, otherwise you'll end up with
494 * memory leaks and the signal functions not working (see Microsoft
495 * Knowledge Base, article 104641) */
496 uintptr_t h = _beginthreadex (NULL, 0, vlc_entry, th, 0, NULL);
497 if (h == 0)
499 int err = errno;
500 free (th);
501 return err;
504 if (detached)
506 CloseHandle((HANDLE)h);
507 th->id = NULL;
509 else
510 th->id = (HANDLE)h;
512 if (p_handle != NULL)
513 *p_handle = th;
515 if (priority)
516 SetThreadPriority (th->id, priority);
518 return 0;
521 int vlc_clone (vlc_thread_t *p_handle, void *(*entry) (void *),
522 void *data, int priority)
524 return vlc_clone_attr (p_handle, false, entry, data, priority);
527 void vlc_join (vlc_thread_t th, void **result)
529 DWORD ret;
533 vlc_testcancel ();
534 ret = WaitForSingleObjectEx(th->id, INFINITE, TRUE);
535 assert(ret != WAIT_ABANDONED_0);
537 while (ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED);
539 if (result != NULL)
540 *result = th->data;
541 CloseHandle (th->id);
542 vlc_thread_destroy(th);
545 int vlc_clone_detach (vlc_thread_t *p_handle, void *(*entry) (void *),
546 void *data, int priority)
548 vlc_thread_t th;
549 if (p_handle == NULL)
550 p_handle = &th;
552 return vlc_clone_attr (p_handle, true, entry, data, priority);
555 vlc_thread_t vlc_thread_self (void)
557 return TlsGetValue(thread_key);
560 unsigned long vlc_thread_id (void)
562 return GetCurrentThreadId ();
565 int vlc_set_priority (vlc_thread_t th, int priority)
567 if (!SetThreadPriority (th->id, priority))
568 return VLC_EGENERIC;
569 return VLC_SUCCESS;
572 /*** Thread cancellation ***/
574 #if IS_INTERRUPTIBLE
575 /* APC procedure for thread cancellation */
576 static void CALLBACK vlc_cancel_self (ULONG_PTR self)
578 (void) self;
580 #endif
582 void vlc_cancel (vlc_thread_t th)
584 atomic_store_explicit(&th->killed, true, memory_order_relaxed);
586 EnterCriticalSection(&th->wait.lock);
587 if (th->wait.addr != NULL)
589 atomic_fetch_or_explicit(th->wait.addr, 1, memory_order_relaxed);
590 vlc_addr_broadcast(th->wait.addr);
592 LeaveCriticalSection(&th->wait.lock);
594 #if IS_INTERRUPTIBLE
595 QueueUserAPC (vlc_cancel_self, th->id, (uintptr_t)th);
596 #endif
599 int vlc_savecancel (void)
601 struct vlc_thread *th = vlc_thread_self();
602 if (th == NULL)
603 return false; /* Main thread - cannot be cancelled anyway */
605 int state = th->killable;
606 th->killable = false;
607 return state;
610 void vlc_restorecancel (int state)
612 struct vlc_thread *th = vlc_thread_self();
613 assert (state == false || state == true);
615 if (th == NULL)
616 return; /* Main thread - cannot be cancelled anyway */
618 assert (!th->killable);
619 th->killable = state != 0;
622 void vlc_testcancel (void)
624 struct vlc_thread *th = vlc_thread_self();
625 if (th == NULL)
626 return; /* Main thread - cannot be cancelled anyway */
627 if (!th->killable)
628 return;
629 if (!atomic_load_explicit(&th->killed, memory_order_relaxed))
630 return;
632 th->killable = true; /* Do not re-enter cancellation cleanup */
634 for (vlc_cleanup_t *p = th->cleaners; p != NULL; p = p->next)
635 p->proc (p->data);
637 th->data = NULL; /* TODO: special value? */
638 if (th->id == NULL) /* Detached thread */
639 vlc_thread_destroy(th);
640 _endthreadex(0);
643 void vlc_control_cancel (int cmd, ...)
645 /* NOTE: This function only modifies thread-specific data, so there is no
646 * need to lock anything. */
647 va_list ap;
649 struct vlc_thread *th = vlc_thread_self();
650 if (th == NULL)
651 return; /* Main thread - cannot be cancelled anyway */
653 va_start (ap, cmd);
654 switch (cmd)
656 case VLC_CLEANUP_PUSH:
658 /* cleaner is a pointer to the caller stack, no need to allocate
659 * and copy anything. As a nice side effect, this cannot fail. */
660 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
661 cleaner->next = th->cleaners;
662 th->cleaners = cleaner;
663 break;
666 case VLC_CLEANUP_POP:
668 th->cleaners = th->cleaners->next;
669 break;
672 case VLC_CANCEL_ADDR_SET:
674 void *addr = va_arg(ap, void *);
676 EnterCriticalSection(&th->wait.lock);
677 assert(th->wait.addr == NULL);
678 th->wait.addr = addr;
679 LeaveCriticalSection(&th->wait.lock);
680 break;
683 case VLC_CANCEL_ADDR_CLEAR:
685 void *addr = va_arg(ap, void *);
687 EnterCriticalSection(&th->wait.lock);
688 assert(th->wait.addr == addr);
689 th->wait.addr = NULL;
690 LeaveCriticalSection(&th->wait.lock);
691 break;
694 va_end (ap);
697 /*** Clock ***/
698 static union
700 #if (_WIN32_WINNT < _WIN32_WINNT_WIN7)
701 struct
703 BOOL (*query) (PULONGLONG);
704 } interrupt;
705 #endif
706 #if (_WIN32_WINNT < _WIN32_WINNT_VISTA)
707 struct
709 ULONGLONG (*get) (void);
710 } tick;
711 #endif
712 struct
714 LARGE_INTEGER freq;
715 } perf;
716 #if !VLC_WINSTORE_APP
717 struct
719 MMRESULT (WINAPI *timeGetDevCaps)(LPTIMECAPS ptc,UINT cbtc);
720 DWORD (WINAPI *timeGetTime)(void);
721 } multimedia;
722 #endif
723 } clk;
725 static mtime_t mdate_interrupt (void)
727 ULONGLONG ts;
728 BOOL ret;
730 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN7)
731 ret = QueryUnbiasedInterruptTime (&ts);
732 #else
733 ret = clk.interrupt.query (&ts);
734 #endif
735 if (unlikely(!ret))
736 abort ();
738 /* hundreds of nanoseconds */
739 static_assert ((10000000 % CLOCK_FREQ) == 0, "Broken frequencies ratio");
740 return ts / (10000000 / CLOCK_FREQ);
743 static mtime_t mdate_tick (void)
745 #if (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
746 ULONGLONG ts = GetTickCount64 ();
747 #else
748 ULONGLONG ts = clk.tick.get ();
749 #endif
751 /* milliseconds */
752 static_assert ((CLOCK_FREQ % 1000) == 0, "Broken frequencies ratio");
753 return ts * (CLOCK_FREQ / 1000);
755 #if !VLC_WINSTORE_APP
756 static mtime_t mdate_multimedia (void)
758 DWORD ts = clk.multimedia.timeGetTime ();
760 /* milliseconds */
761 static_assert ((CLOCK_FREQ % 1000) == 0, "Broken frequencies ratio");
762 return ts * (CLOCK_FREQ / 1000);
764 #endif
766 static mtime_t mdate_perf (void)
768 /* We don't need the real date, just the value of a high precision timer */
769 LARGE_INTEGER counter;
770 if (!QueryPerformanceCounter (&counter))
771 abort ();
773 /* Convert to from (1/freq) to microsecond resolution */
774 /* We need to split the division to avoid 63-bits overflow */
775 lldiv_t d = lldiv (counter.QuadPart, clk.perf.freq.QuadPart);
777 return (d.quot * 1000000) + ((d.rem * 1000000) / clk.perf.freq.QuadPart);
780 static mtime_t mdate_wall (void)
782 FILETIME ts;
783 ULARGE_INTEGER s;
785 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) && !VLC_WINSTORE_APP
786 GetSystemTimePreciseAsFileTime (&ts);
787 #else
788 GetSystemTimeAsFileTime (&ts);
789 #endif
790 s.LowPart = ts.dwLowDateTime;
791 s.HighPart = ts.dwHighDateTime;
792 /* hundreds of nanoseconds */
793 static_assert ((10000000 % CLOCK_FREQ) == 0, "Broken frequencies ratio");
794 return s.QuadPart / (10000000 / CLOCK_FREQ);
797 static mtime_t mdate_default(void)
799 vlc_threads_setup(NULL);
800 return mdate_perf();
803 static mtime_t (*mdate_selected) (void) = mdate_default;
805 mtime_t mdate (void)
807 return mdate_selected ();
810 #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
811 void (mwait)(mtime_t deadline)
813 mtime_t delay;
815 vlc_testcancel();
816 while ((delay = (deadline - mdate())) > 0)
818 delay = (delay + 999) / 1000;
819 if (unlikely(delay > 0x7fffffff))
820 delay = 0x7fffffff;
822 SleepEx(delay, TRUE);
823 vlc_testcancel();
827 void (msleep)(mtime_t delay)
829 mwait (mdate () + delay);
831 #endif
833 static BOOL SelectClockSource(void *data)
835 vlc_object_t *obj = data;
837 #if VLC_WINSTORE_APP
838 const char *name = "perf";
839 #else
840 const char *name = "multimedia";
841 #endif
842 char *str = NULL;
843 if (obj != NULL)
844 str = var_InheritString(obj, "clock-source");
845 if (str != NULL)
846 name = str;
847 if (!strcmp (name, "interrupt"))
849 msg_Dbg (obj, "using interrupt time as clock source");
850 #if (_WIN32_WINNT < _WIN32_WINNT_WIN7)
851 HANDLE h = GetModuleHandle (_T("kernel32.dll"));
852 if (unlikely(h == NULL))
853 return FALSE;
854 clk.interrupt.query = (void *)GetProcAddress (h,
855 "QueryUnbiasedInterruptTime");
856 if (unlikely(clk.interrupt.query == NULL))
857 abort ();
858 #endif
859 mdate_selected = mdate_interrupt;
861 else
862 if (!strcmp (name, "tick"))
864 msg_Dbg (obj, "using Windows time as clock source");
865 #if (_WIN32_WINNT < _WIN32_WINNT_VISTA)
866 HANDLE h = GetModuleHandle (_T("kernel32.dll"));
867 if (unlikely(h == NULL))
868 return FALSE;
869 clk.tick.get = (void *)GetProcAddress (h, "GetTickCount64");
870 if (unlikely(clk.tick.get == NULL))
871 return FALSE;
872 #endif
873 mdate_selected = mdate_tick;
875 #if !VLC_WINSTORE_APP
876 else
877 if (!strcmp (name, "multimedia"))
879 TIMECAPS caps;
880 MMRESULT (WINAPI * timeBeginPeriod)(UINT);
882 HMODULE hWinmm = LoadLibrary(TEXT("winmm.dll"));
883 if (!hWinmm)
884 goto perf;
886 clk.multimedia.timeGetDevCaps = (void*)GetProcAddress(hWinmm, "timeGetDevCaps");
887 clk.multimedia.timeGetTime = (void*)GetProcAddress(hWinmm, "timeGetTime");
888 if (!clk.multimedia.timeGetDevCaps || !clk.multimedia.timeGetTime)
889 goto perf;
891 msg_Dbg (obj, "using multimedia timers as clock source");
892 if (clk.multimedia.timeGetDevCaps (&caps, sizeof (caps)) != MMSYSERR_NOERROR)
893 goto perf;
894 msg_Dbg (obj, " min period: %u ms, max period: %u ms",
895 caps.wPeriodMin, caps.wPeriodMax);
896 mdate_selected = mdate_multimedia;
898 timeBeginPeriod = (void*)GetProcAddress(hWinmm, "timeBeginPeriod");
899 if (timeBeginPeriod != NULL)
900 timeBeginPeriod(5);
902 #endif
903 else
904 if (!strcmp (name, "perf"))
906 perf:
907 msg_Dbg (obj, "using performance counters as clock source");
908 if (!QueryPerformanceFrequency (&clk.perf.freq))
909 abort ();
910 msg_Dbg (obj, " frequency: %llu Hz", clk.perf.freq.QuadPart);
911 mdate_selected = mdate_perf;
913 else
914 if (!strcmp (name, "wall"))
916 msg_Dbg (obj, "using system time as clock source");
917 mdate_selected = mdate_wall;
919 else
921 msg_Err (obj, "invalid clock source \"%s\"", name);
922 abort ();
924 free (str);
925 return TRUE;
928 size_t EnumClockSource (vlc_object_t *obj, const char *var,
929 char ***vp, char ***np)
931 const size_t max = 6;
932 char **values = xmalloc (sizeof (*values) * max);
933 char **names = xmalloc (sizeof (*names) * max);
934 size_t n = 0;
936 #if (_WIN32_WINNT < _WIN32_WINNT_WIN7)
937 DWORD version = LOWORD(GetVersion());
938 version = (LOBYTE(version) << 8) | (HIBYTE(version) << 0);
939 #endif
941 values[n] = xstrdup ("");
942 names[n] = xstrdup (_("Auto"));
943 n++;
944 #if (_WIN32_WINNT < _WIN32_WINNT_WIN7)
945 if (version >= 0x0601)
946 #endif
948 values[n] = xstrdup ("interrupt");
949 names[n] = xstrdup ("Interrupt time");
950 n++;
952 #if (_WIN32_WINNT < _WIN32_WINNT_VISTA)
953 if (version >= 0x0600)
954 #endif
956 values[n] = xstrdup ("tick");
957 names[n] = xstrdup ("Windows time");
958 n++;
960 #if !VLC_WINSTORE_APP
961 values[n] = xstrdup ("multimedia");
962 names[n] = xstrdup ("Multimedia timers");
963 n++;
964 #endif
965 values[n] = xstrdup ("perf");
966 names[n] = xstrdup ("Performance counters");
967 n++;
968 values[n] = xstrdup ("wall");
969 names[n] = xstrdup ("System time (DANGEROUS!)");
970 n++;
972 *vp = values;
973 *np = names;
974 (void) obj; (void) var;
975 return n;
979 /*** CPU ***/
980 unsigned vlc_GetCPUCount (void)
982 SYSTEM_INFO systemInfo;
984 GetNativeSystemInfo(&systemInfo);
986 return systemInfo.dwNumberOfProcessors;
990 /*** Initialization ***/
991 static CRITICAL_SECTION setup_lock; /* FIXME: use INIT_ONCE */
993 void vlc_threads_setup(libvlc_int_t *vlc)
995 EnterCriticalSection(&setup_lock);
996 if (mdate_selected != mdate_default)
998 LeaveCriticalSection(&setup_lock);
999 return;
1002 if (!SelectClockSource((vlc != NULL) ? VLC_OBJECT(vlc) : NULL))
1003 abort();
1004 assert(mdate_selected != mdate_default);
1006 #if !VLC_WINSTORE_APP
1007 /* Raise default priority of the current process */
1008 #ifndef ABOVE_NORMAL_PRIORITY_CLASS
1009 # define ABOVE_NORMAL_PRIORITY_CLASS 0x00008000
1010 #endif
1011 if (var_InheritBool(vlc, "high-priority"))
1013 if (SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS)
1014 || SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS))
1015 msg_Dbg(vlc, "raised process priority");
1016 else
1017 msg_Dbg(vlc, "could not raise process priority");
1019 #endif
1020 LeaveCriticalSection(&setup_lock);
1023 #define LOOKUP(s) (((s##_) = (void *)GetProcAddress(h, #s)) != NULL)
1025 extern vlc_rwlock_t config_lock;
1026 BOOL WINAPI DllMain (HINSTANCE, DWORD, LPVOID);
1028 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
1030 (void) hinstDll;
1031 (void) lpvReserved;
1033 switch (fdwReason)
1035 case DLL_PROCESS_ATTACH:
1037 #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
1038 HANDLE h = GetModuleHandle(TEXT("kernel32.dll"));
1039 if (unlikely(h == NULL))
1040 return FALSE;
1042 if (!LOOKUP(WaitOnAddress)
1043 || !LOOKUP(WakeByAddressAll) || !LOOKUP(WakeByAddressSingle))
1045 # if (_WIN32_WINNT < _WIN32_WINNT_VISTA)
1046 if (!LOOKUP(InitializeConditionVariable)
1047 || !LOOKUP(SleepConditionVariableCS)
1048 || !LOOKUP(WakeAllConditionVariable))
1050 InitializeConditionVariable_ = DummyConditionVariable;
1051 SleepConditionVariableCS_ = SleepConditionVariableFallback;
1052 WakeAllConditionVariable_ = DummyConditionVariable;
1054 # endif
1055 vlc_wait_addr_init();
1056 WaitOnAddress_ = WaitOnAddressFallback;
1057 WakeByAddressAll_ = WakeByAddressFallback;
1058 WakeByAddressSingle_ = WakeByAddressFallback;
1060 #endif
1061 thread_key = TlsAlloc();
1062 if (unlikely(thread_key == TLS_OUT_OF_INDEXES))
1063 return FALSE;
1064 InitializeCriticalSection(&setup_lock);
1065 InitializeCriticalSection(&super_mutex);
1066 InitializeConditionVariable(&super_variable);
1067 vlc_rwlock_init (&config_lock);
1068 vlc_CPU_init ();
1069 break;
1072 case DLL_PROCESS_DETACH:
1073 vlc_rwlock_destroy (&config_lock);
1074 DeleteCriticalSection(&super_mutex);
1075 DeleteCriticalSection(&setup_lock);
1076 TlsFree(thread_key);
1077 #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
1078 if (WaitOnAddress_ == WaitOnAddressFallback)
1079 vlc_wait_addr_deinit();
1080 #endif
1081 break;
1083 case DLL_THREAD_DETACH:
1084 vlc_threadvars_cleanup();
1085 break;
1087 return TRUE;