Merge commit 'b22693b06d1e5d73454a65c203b4d31c1ca5b69a'
[ffmpeg.git] / compat / w32pthreads.h
1 /*
2  * Copyright (C) 2010-2011 x264 project
3  *
4  * Authors: Steven Walters <kemuri9@gmail.com>
5  *          Pegasys Inc. <http://www.pegasys-inc.com>
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /**
25  * @file
26  * w32threads to pthreads wrapper
27  */
28
29 #ifndef FFMPEG_COMPAT_W32PTHREADS_H
30 #define FFMPEG_COMPAT_W32PTHREADS_H
31
32 /* Build up a pthread-like API using underlying Windows API. Have only static
33  * methods so as to not conflict with a potentially linked in pthread-win32
34  * library.
35  * As most functions here are used without checking return values,
36  * only implement return values as necessary. */
37
38 #define WIN32_LEAN_AND_MEAN
39 #include <windows.h>
40 #include <process.h>
41
42 #include "libavutil/attributes.h"
43 #include "libavutil/common.h"
44 #include "libavutil/internal.h"
45 #include "libavutil/mem.h"
46
47 typedef struct pthread_t {
48     void *handle;
49     void *(*func)(void* arg);
50     void *arg;
51     void *ret;
52 } pthread_t;
53
54 /* the conditional variable api for windows 6.0+ uses critical sections and
55  * not mutexes */
56 typedef CRITICAL_SECTION pthread_mutex_t;
57
58 /* This is the CONDITION_VARIABLE typedef for using Windows' native
59  * conditional variables on kernels 6.0+. */
60 #if HAVE_CONDITION_VARIABLE_PTR
61 typedef CONDITION_VARIABLE pthread_cond_t;
62 #else
63 typedef struct pthread_cond_t {
64     void *Ptr;
65 } pthread_cond_t;
66 #endif
67
68 #if _WIN32_WINNT >= 0x0600
69 #define InitializeCriticalSection(x) InitializeCriticalSectionEx(x, 0, 0)
70 #define WaitForSingleObject(a, b) WaitForSingleObjectEx(a, b, FALSE)
71 #endif
72
73 static av_unused unsigned __stdcall attribute_align_arg win32thread_worker(void *arg)
74 {
75     pthread_t *h = arg;
76     h->ret = h->func(h->arg);
77     return 0;
78 }
79
80 static av_unused int pthread_create(pthread_t *thread, const void *unused_attr,
81                                     void *(*start_routine)(void*), void *arg)
82 {
83     thread->func   = start_routine;
84     thread->arg    = arg;
85     thread->handle = (void*)_beginthreadex(NULL, 0, win32thread_worker, thread,
86                                            0, NULL);
87     return !thread->handle;
88 }
89
90 static av_unused int pthread_join(pthread_t thread, void **value_ptr)
91 {
92     DWORD ret = WaitForSingleObject(thread.handle, INFINITE);
93     if (ret != WAIT_OBJECT_0) {
94         if (ret == WAIT_ABANDONED)
95             return EINVAL;
96         else
97             return EDEADLK;
98     }
99     if (value_ptr)
100         *value_ptr = thread.ret;
101     CloseHandle(thread.handle);
102     return 0;
103 }
104
105 static inline int pthread_mutex_init(pthread_mutex_t *m, void* attr)
106 {
107     InitializeCriticalSection(m);
108     return 0;
109 }
110 static inline int pthread_mutex_destroy(pthread_mutex_t *m)
111 {
112     DeleteCriticalSection(m);
113     return 0;
114 }
115 static inline int pthread_mutex_lock(pthread_mutex_t *m)
116 {
117     EnterCriticalSection(m);
118     return 0;
119 }
120 static inline int pthread_mutex_unlock(pthread_mutex_t *m)
121 {
122     LeaveCriticalSection(m);
123     return 0;
124 }
125
126 #if _WIN32_WINNT >= 0x0600
127 typedef INIT_ONCE pthread_once_t;
128 #define PTHREAD_ONCE_INIT INIT_ONCE_STATIC_INIT
129
130 static av_unused int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
131 {
132     BOOL pending = FALSE;
133     InitOnceBeginInitialize(once_control, 0, &pending, NULL);
134     if (pending)
135         init_routine();
136     InitOnceComplete(once_control, 0, NULL);
137     return 0;
138 }
139
140 static inline int pthread_cond_init(pthread_cond_t *cond, const void *unused_attr)
141 {
142     InitializeConditionVariable(cond);
143     return 0;
144 }
145
146 /* native condition variables do not destroy */
147 static inline int pthread_cond_destroy(pthread_cond_t *cond)
148 {
149     return 0;
150 }
151
152 static inline int pthread_cond_broadcast(pthread_cond_t *cond)
153 {
154     WakeAllConditionVariable(cond);
155     return 0;
156 }
157
158 static inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
159 {
160     SleepConditionVariableCS(cond, mutex, INFINITE);
161     return 0;
162 }
163
164 static inline int pthread_cond_signal(pthread_cond_t *cond)
165 {
166     WakeConditionVariable(cond);
167     return 0;
168 }
169
170 #else // _WIN32_WINNT < 0x0600
171 /* for pre-Windows 6.0 platforms, define INIT_ONCE struct,
172  * compatible to the one used in the native API */
173
174 typedef union pthread_once_t  {
175     void * Ptr;    ///< For the Windows 6.0+ native functions
176     LONG state;    ///< For the pre-Windows 6.0 compat code
177 } pthread_once_t;
178
179 #define PTHREAD_ONCE_INIT {0}
180
181 /* function pointers to init once API on windows 6.0+ kernels */
182 static BOOL (WINAPI *initonce_begin)(pthread_once_t *lpInitOnce, DWORD dwFlags, BOOL *fPending, void **lpContext);
183 static BOOL (WINAPI *initonce_complete)(pthread_once_t *lpInitOnce, DWORD dwFlags, void *lpContext);
184
185 /* pre-Windows 6.0 compat using a spin-lock */
186 static inline void w32thread_once_fallback(LONG volatile *state, void (*init_routine)(void))
187 {
188     switch (InterlockedCompareExchange(state, 1, 0)) {
189     /* Initial run */
190     case 0:
191         init_routine();
192         InterlockedExchange(state, 2);
193         break;
194     /* Another thread is running init */
195     case 1:
196         while (1) {
197             MemoryBarrier();
198             if (*state == 2)
199                 break;
200             Sleep(0);
201         }
202         break;
203     /* Initialization complete */
204     case 2:
205         break;
206     }
207 }
208
209 static av_unused int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
210 {
211     /* Use native functions on Windows 6.0+ */
212     if (initonce_begin && initonce_complete) {
213         BOOL pending = FALSE;
214         initonce_begin(once_control, 0, &pending, NULL);
215         if (pending)
216             init_routine();
217         initonce_complete(once_control, 0, NULL);
218         return 0;
219     }
220
221     w32thread_once_fallback(&once_control->state, init_routine);
222     return 0;
223 }
224
225 /* for pre-Windows 6.0 platforms we need to define and use our own condition
226  * variable and api */
227
228 typedef struct  win32_cond_t {
229     pthread_mutex_t mtx_broadcast;
230     pthread_mutex_t mtx_waiter_count;
231     volatile int waiter_count;
232     HANDLE semaphore;
233     HANDLE waiters_done;
234     volatile int is_broadcast;
235 } win32_cond_t;
236
237 /* function pointers to conditional variable API on windows 6.0+ kernels */
238 static void (WINAPI *cond_broadcast)(pthread_cond_t *cond);
239 static void (WINAPI *cond_init)(pthread_cond_t *cond);
240 static void (WINAPI *cond_signal)(pthread_cond_t *cond);
241 static BOOL (WINAPI *cond_wait)(pthread_cond_t *cond, pthread_mutex_t *mutex,
242                                 DWORD milliseconds);
243
244 static av_unused int pthread_cond_init(pthread_cond_t *cond, const void *unused_attr)
245 {
246     win32_cond_t *win32_cond = NULL;
247     if (cond_init) {
248         cond_init(cond);
249         return 0;
250     }
251
252     /* non native condition variables */
253     win32_cond = av_mallocz(sizeof(win32_cond_t));
254     if (!win32_cond)
255         return ENOMEM;
256     cond->Ptr = win32_cond;
257     win32_cond->semaphore = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
258     if (!win32_cond->semaphore)
259         return ENOMEM;
260     win32_cond->waiters_done = CreateEvent(NULL, TRUE, FALSE, NULL);
261     if (!win32_cond->waiters_done)
262         return ENOMEM;
263
264     pthread_mutex_init(&win32_cond->mtx_waiter_count, NULL);
265     pthread_mutex_init(&win32_cond->mtx_broadcast, NULL);
266     return 0;
267 }
268
269 static av_unused int pthread_cond_destroy(pthread_cond_t *cond)
270 {
271     win32_cond_t *win32_cond = cond->Ptr;
272     /* native condition variables do not destroy */
273     if (cond_init)
274         return 0;
275
276     /* non native condition variables */
277     CloseHandle(win32_cond->semaphore);
278     CloseHandle(win32_cond->waiters_done);
279     pthread_mutex_destroy(&win32_cond->mtx_waiter_count);
280     pthread_mutex_destroy(&win32_cond->mtx_broadcast);
281     av_freep(&win32_cond);
282     cond->Ptr = NULL;
283     return 0;
284 }
285
286 static av_unused int pthread_cond_broadcast(pthread_cond_t *cond)
287 {
288     win32_cond_t *win32_cond = cond->Ptr;
289     int have_waiter;
290
291     if (cond_broadcast) {
292         cond_broadcast(cond);
293         return 0;
294     }
295
296     /* non native condition variables */
297     pthread_mutex_lock(&win32_cond->mtx_broadcast);
298     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
299     have_waiter = 0;
300
301     if (win32_cond->waiter_count) {
302         win32_cond->is_broadcast = 1;
303         have_waiter = 1;
304     }
305
306     if (have_waiter) {
307         ReleaseSemaphore(win32_cond->semaphore, win32_cond->waiter_count, NULL);
308         pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
309         WaitForSingleObject(win32_cond->waiters_done, INFINITE);
310         ResetEvent(win32_cond->waiters_done);
311         win32_cond->is_broadcast = 0;
312     } else
313         pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
314     pthread_mutex_unlock(&win32_cond->mtx_broadcast);
315     return 0;
316 }
317
318 static av_unused int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
319 {
320     win32_cond_t *win32_cond = cond->Ptr;
321     int last_waiter;
322     if (cond_wait) {
323         cond_wait(cond, mutex, INFINITE);
324         return 0;
325     }
326
327     /* non native condition variables */
328     pthread_mutex_lock(&win32_cond->mtx_broadcast);
329     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
330     win32_cond->waiter_count++;
331     pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
332     pthread_mutex_unlock(&win32_cond->mtx_broadcast);
333
334     // unlock the external mutex
335     pthread_mutex_unlock(mutex);
336     WaitForSingleObject(win32_cond->semaphore, INFINITE);
337
338     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
339     win32_cond->waiter_count--;
340     last_waiter = !win32_cond->waiter_count || !win32_cond->is_broadcast;
341     pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
342
343     if (last_waiter)
344         SetEvent(win32_cond->waiters_done);
345
346     // lock the external mutex
347     return pthread_mutex_lock(mutex);
348 }
349
350 static av_unused int pthread_cond_signal(pthread_cond_t *cond)
351 {
352     win32_cond_t *win32_cond = cond->Ptr;
353     int have_waiter;
354     if (cond_signal) {
355         cond_signal(cond);
356         return 0;
357     }
358
359     pthread_mutex_lock(&win32_cond->mtx_broadcast);
360
361     /* non-native condition variables */
362     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
363     have_waiter = win32_cond->waiter_count;
364     pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
365
366     if (have_waiter) {
367         ReleaseSemaphore(win32_cond->semaphore, 1, NULL);
368         WaitForSingleObject(win32_cond->waiters_done, INFINITE);
369         ResetEvent(win32_cond->waiters_done);
370     }
371
372     pthread_mutex_unlock(&win32_cond->mtx_broadcast);
373     return 0;
374 }
375 #endif
376
377 static av_unused void w32thread_init(void)
378 {
379 #if _WIN32_WINNT < 0x0600
380     HANDLE kernel_dll = GetModuleHandle(TEXT("kernel32.dll"));
381     /* if one is available, then they should all be available */
382     cond_init      =
383         (void*)GetProcAddress(kernel_dll, "InitializeConditionVariable");
384     cond_broadcast =
385         (void*)GetProcAddress(kernel_dll, "WakeAllConditionVariable");
386     cond_signal    =
387         (void*)GetProcAddress(kernel_dll, "WakeConditionVariable");
388     cond_wait      =
389         (void*)GetProcAddress(kernel_dll, "SleepConditionVariableCS");
390     initonce_begin =
391         (void*)GetProcAddress(kernel_dll, "InitOnceBeginInitialize");
392     initonce_complete =
393         (void*)GetProcAddress(kernel_dll, "InitOnceComplete");
394 #endif
395
396 }
397
398 #endif /* FFMPEG_COMPAT_W32PTHREADS_H */