mux: ts: don't set fmt.extra for subt
[vlc.git] / src / darwin / thread.c
blobb4991fa4c91267b6aa6e46ccec3c00ef49c71072
1 /*****************************************************************************
2 * thread.c : pthread back-end for LibVLC
3 *****************************************************************************
4 * Copyright (C) 1999-2013 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 * Felix Paul Kühne <fkuehne # videolan.org>
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 <signal.h>
37 #include <errno.h>
38 #include <assert.h>
40 #include <pthread.h>
41 #include <mach/mach_init.h> /* mach_task_self in semaphores */
42 #include <mach/mach_time.h>
43 #include <execinfo.h>
45 static mach_timebase_info_data_t vlc_clock_conversion_factor;
47 static void vlc_clock_setup_once (void)
49 if (unlikely(mach_timebase_info (&vlc_clock_conversion_factor) != 0))
50 abort ();
53 static pthread_once_t vlc_clock_once = PTHREAD_ONCE_INIT;
55 #define vlc_clock_setup() \
56 pthread_once(&vlc_clock_once, vlc_clock_setup_once)
58 static struct timespec mtime_to_ts (mtime_t date)
60 lldiv_t d = lldiv (date, CLOCK_FREQ);
61 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
63 return ts;
66 /* Print a backtrace to the standard error for debugging purpose. */
67 void vlc_trace (const char *fn, const char *file, unsigned line)
69 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
70 fflush (stderr); /* needed before switch to low-level I/O */
71 void *stack[20];
72 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
73 backtrace_symbols_fd (stack, len, 2);
74 fsync (2);
77 #ifndef NDEBUG
78 /* Reports a fatal error from the threading layer, for debugging purposes. */
79 static void
80 vlc_thread_fatal (const char *action, int error,
81 const char *function, const char *file, unsigned line)
83 int canc = vlc_savecancel ();
84 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
85 action, error, vlc_thread_id ());
86 vlc_trace (function, file, line);
88 char buf[1000];
89 const char *msg;
91 switch (strerror_r (error, buf, sizeof (buf)))
93 case 0:
94 msg = buf;
95 break;
96 case ERANGE: /* should never happen */
97 msg = "unknown (too big to display)";
98 break;
99 default:
100 msg = "unknown (invalid error number)";
101 break;
103 fprintf (stderr, " Error message: %s\n", msg);
104 fflush (stderr);
106 vlc_restorecancel (canc);
107 abort ();
110 # define VLC_THREAD_ASSERT( action ) \
111 if (unlikely(val)) \
112 vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
113 #else
114 # define VLC_THREAD_ASSERT( action ) ((void)val)
115 #endif
117 /* Initializes a fast mutex. */
118 void vlc_mutex_init( vlc_mutex_t *p_mutex )
120 pthread_mutexattr_t attr;
122 if (unlikely(pthread_mutexattr_init (&attr)))
123 abort();
124 #ifdef NDEBUG
125 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_DEFAULT);
126 #else
127 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK);
128 #endif
129 if (unlikely(pthread_mutex_init (p_mutex, &attr)))
130 abort();
131 pthread_mutexattr_destroy( &attr );
134 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
136 pthread_mutexattr_t attr;
138 if (unlikely(pthread_mutexattr_init (&attr)))
139 abort();
140 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
141 if (unlikely(pthread_mutex_init (p_mutex, &attr)))
142 abort();
143 pthread_mutexattr_destroy( &attr );
147 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
149 int val = pthread_mutex_destroy( p_mutex );
150 VLC_THREAD_ASSERT ("destroying mutex");
153 #ifndef NDEBUG
154 # ifdef HAVE_VALGRIND_VALGRIND_H
155 # include <valgrind/valgrind.h>
156 # else
157 # define RUNNING_ON_VALGRIND (0)
158 # endif
160 void vlc_assert_locked (vlc_mutex_t *p_mutex)
162 if (RUNNING_ON_VALGRIND > 0)
163 return;
164 assert (pthread_mutex_lock (p_mutex) == EDEADLK);
166 #endif
168 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
170 int val = pthread_mutex_lock( p_mutex );
171 VLC_THREAD_ASSERT ("locking mutex");
174 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
176 int val = pthread_mutex_trylock( p_mutex );
178 if (val != EBUSY)
179 VLC_THREAD_ASSERT ("locking mutex");
180 return val;
183 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
185 int val = pthread_mutex_unlock( p_mutex );
186 VLC_THREAD_ASSERT ("unlocking mutex");
189 void vlc_cond_init (vlc_cond_t *p_condvar)
191 if (unlikely(pthread_cond_init (p_condvar, NULL)))
192 abort ();
195 void vlc_cond_init_daytime (vlc_cond_t *p_condvar)
197 if (unlikely(pthread_cond_init (p_condvar, NULL)))
198 abort ();
201 void vlc_cond_destroy (vlc_cond_t *p_condvar)
203 int val = pthread_cond_destroy (p_condvar);
205 /* due to a faulty pthread implementation within Darwin 11 and
206 * later condition variables cannot be destroyed without
207 * terminating the application immediately.
208 * This Darwin kernel issue is still present in version 13
209 * and might not be resolved prior to Darwin 15.
210 * radar://12496249
212 * To work-around this, we are just leaking the condition variable
213 * which is acceptable due to VLC's low number of created variables
214 * and its usually limited runtime.
215 * Ideally, we should implement a re-useable pool.
217 if (val != 0) {
218 #ifndef NDEBUG
219 printf("pthread_cond_destroy returned %i\n", val);
220 #endif
222 if (val == EBUSY)
223 return;
226 VLC_THREAD_ASSERT ("destroying condition");
229 void vlc_cond_signal (vlc_cond_t *p_condvar)
231 int val = pthread_cond_signal (p_condvar);
232 VLC_THREAD_ASSERT ("signaling condition variable");
235 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
237 pthread_cond_broadcast (p_condvar);
240 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
242 int val = pthread_cond_wait (p_condvar, p_mutex);
243 VLC_THREAD_ASSERT ("waiting on condition");
246 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
247 mtime_t deadline)
249 /* according to POSIX standards, cond_timedwait should be a cancellation point
250 * Of course, Darwin does not care */
251 pthread_testcancel();
254 * mdate() is the monotonic clock, pthread_cond_timedwait expects
255 * origin of gettimeofday(). Use timedwait_relative_np() instead.
257 mtime_t base = mdate();
258 deadline -= base;
259 if (deadline < 0)
260 deadline = 0;
262 struct timespec ts = mtime_to_ts(deadline);
263 int val = pthread_cond_timedwait_relative_np(p_condvar, p_mutex, &ts);
264 if (val != ETIMEDOUT)
265 VLC_THREAD_ASSERT ("timed-waiting on condition");
266 return val;
269 /* variant for vlc_cond_init_daytime */
270 int vlc_cond_timedwait_daytime (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
271 time_t deadline)
274 * Note that both pthread_cond_timedwait_relative_np and pthread_cond_timedwait
275 * convert the given timeout to a mach absolute deadline, with system startup
276 * as the time origin. There is no way you can change this behaviour.
278 * For more details, see: https://devforums.apple.com/message/931605
281 pthread_testcancel();
284 * FIXME: It is assumed, that in this case the system waits until the real
285 * time deadline is passed, even if the real time is adjusted in between.
286 * This is not fulfilled, as described above.
288 struct timespec ts = mtime_to_ts(deadline);
289 int val = pthread_cond_timedwait(p_condvar, p_mutex, &ts);
291 if (val != ETIMEDOUT)
292 VLC_THREAD_ASSERT ("timed-waiting on condition");
293 return val;
297 /* Initialize a semaphore. */
298 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
300 if (unlikely(semaphore_create(mach_task_self(), sem, SYNC_POLICY_FIFO, value) != KERN_SUCCESS))
301 abort ();
304 void vlc_sem_destroy (vlc_sem_t *sem)
306 int val;
308 if (likely(semaphore_destroy(mach_task_self(), *sem) == KERN_SUCCESS))
309 return;
311 val = EINVAL;
313 VLC_THREAD_ASSERT ("destroying semaphore");
316 int vlc_sem_post (vlc_sem_t *sem)
318 int val;
320 if (likely(semaphore_signal(*sem) == KERN_SUCCESS))
321 return 0;
323 val = EINVAL;
325 if (unlikely(val != EOVERFLOW))
326 VLC_THREAD_ASSERT ("unlocking semaphore");
327 return val;
330 void vlc_sem_wait (vlc_sem_t *sem)
332 int val;
334 if (likely(semaphore_wait(*sem) == KERN_SUCCESS))
335 return;
337 val = EINVAL;
339 VLC_THREAD_ASSERT ("locking semaphore");
342 void vlc_rwlock_init (vlc_rwlock_t *lock)
344 if (unlikely(pthread_rwlock_init (lock, NULL)))
345 abort ();
348 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
350 int val = pthread_rwlock_destroy (lock);
351 VLC_THREAD_ASSERT ("destroying R/W lock");
354 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
356 int val = pthread_rwlock_rdlock (lock);
357 VLC_THREAD_ASSERT ("acquiring R/W lock for reading");
360 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
362 int val = pthread_rwlock_wrlock (lock);
363 VLC_THREAD_ASSERT ("acquiring R/W lock for writing");
366 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
368 int val = pthread_rwlock_unlock (lock);
369 VLC_THREAD_ASSERT ("releasing R/W lock");
372 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
374 return pthread_key_create (key, destr);
377 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
379 pthread_key_delete (*p_tls);
382 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
384 return pthread_setspecific (key, value);
387 void *vlc_threadvar_get (vlc_threadvar_t key)
389 return pthread_getspecific (key);
392 void vlc_threads_setup (libvlc_int_t *p_libvlc)
394 (void) p_libvlc;
397 static int vlc_clone_attr (vlc_thread_t *th, pthread_attr_t *attr,
398 void *(*entry) (void *), void *data, int priority)
400 int ret;
402 sigset_t oldset;
404 sigset_t set;
405 sigemptyset (&set);
406 sigdelset (&set, SIGHUP);
407 sigaddset (&set, SIGINT);
408 sigaddset (&set, SIGQUIT);
409 sigaddset (&set, SIGTERM);
411 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
412 pthread_sigmask (SIG_BLOCK, &set, &oldset);
415 (void) priority;
417 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
419 #ifdef VLC_STACKSIZE
420 ret = pthread_attr_setstacksize (attr, VLC_STACKSIZE);
421 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
422 #endif
424 ret = pthread_create (th, attr, entry, data);
425 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
426 pthread_attr_destroy (attr);
427 return ret;
430 int vlc_clone (vlc_thread_t *th, void *(*entry) (void *), void *data,
431 int priority)
433 pthread_attr_t attr;
435 pthread_attr_init (&attr);
436 return vlc_clone_attr (th, &attr, entry, data, priority);
439 void vlc_join (vlc_thread_t handle, void **result)
441 int val = pthread_join (handle, result);
442 VLC_THREAD_ASSERT ("joining thread");
445 int vlc_clone_detach (vlc_thread_t *th, void *(*entry) (void *), void *data,
446 int priority)
448 vlc_thread_t dummy;
449 pthread_attr_t attr;
451 if (th == NULL)
452 th = &dummy;
454 pthread_attr_init (&attr);
455 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
456 return vlc_clone_attr (th, &attr, entry, data, priority);
459 vlc_thread_t vlc_thread_self (void)
461 return pthread_self ();
464 unsigned long vlc_thread_id (void)
466 return -1;
469 int vlc_set_priority (vlc_thread_t th, int priority)
471 (void) th; (void) priority;
472 return VLC_SUCCESS;
475 void vlc_cancel (vlc_thread_t thread_id)
477 pthread_cancel (thread_id);
480 int vlc_savecancel (void)
482 int state;
483 int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
485 VLC_THREAD_ASSERT ("saving cancellation");
486 return state;
489 void vlc_restorecancel (int state)
491 #ifndef NDEBUG
492 int oldstate, val;
494 val = pthread_setcancelstate (state, &oldstate);
495 VLC_THREAD_ASSERT ("restoring cancellation");
497 if (unlikely(oldstate != PTHREAD_CANCEL_DISABLE))
498 vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
499 __func__, __FILE__, __LINE__);
500 #else
501 pthread_setcancelstate (state, NULL);
502 #endif
505 void vlc_testcancel (void)
507 pthread_testcancel ();
510 void vlc_control_cancel (int cmd, ...)
512 (void) cmd;
513 vlc_assert_unreachable ();
516 mtime_t mdate (void)
518 vlc_clock_setup();
519 uint64_t date = mach_absolute_time();
521 /* denom is uint32_t, switch to 64 bits to prevent overflow. */
522 uint64_t denom = vlc_clock_conversion_factor.denom;
524 /* Switch to microsecs */
525 denom *= 1000LL;
527 /* Split the division to prevent overflow */
528 lldiv_t d = lldiv (vlc_clock_conversion_factor.numer, denom);
530 return (d.quot * date) + ((d.rem * date) / denom);
533 #undef mwait
534 void mwait (mtime_t deadline)
536 deadline -= mdate ();
537 if (deadline > 0)
538 msleep (deadline);
541 #undef msleep
542 void msleep (mtime_t delay)
544 struct timespec ts = mtime_to_ts (delay);
546 /* nanosleep uses mach_absolute_time and mach_wait_until internally,
547 but also handles kernel errors. Thus we use just this. */
548 while (nanosleep (&ts, &ts) == -1)
549 assert (errno == EINTR);
552 unsigned vlc_GetCPUCount(void)
554 return sysconf(_SC_NPROCESSORS_CONF);