Debian Codegraph @

3rdparty/iaxclient/lib/portaudio/src/os/unix/pa_unix_util.c

raw symbols SCIP
1 /*
2 * $Id: pa_unix_util.c,v 1.1 2006/06/10 21:30:56 dmazzoni Exp $
3 * Portable Audio I/O Library
4 * UNIX platform-specific support functions
5 *
6 * Based on the Open Source API proposed by Ross Bencina
7 * Copyright (c) 1999-2000 Ross Bencina
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining
10 * a copy of this software and associated documentation files
11 * (the "Software"), to deal in the Software without restriction,
12 * including without limitation the rights to use, copy, modify, merge,
13 * publish, distribute, sublicense, and/or sell copies of the Software,
14 * and to permit persons to whom the Software is furnished to do so,
15 * subject to the following conditions:
16 *
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
19 *
20 * Any person wishing to distribute modifications to the Software is
21 * requested to send the modifications to the original developer so that
22 * they can be incorporated into the canonical version.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
27 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
28 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 */
32
33
34 #include <pthread.h>
35 #include <unistd.h>
36 #include <stdlib.h>
37 #include <time.h>
38 #include <sys/time.h>
39 #include <assert.h>
40 #include <string.h> /* For memset */
41 #include <math.h>
42 #include <errno.h>
43
44 #include "pa_util.h"
45 #include "pa_unix_util.h"
46
47 /*
48 Track memory allocations to avoid leaks.
49 */
50
51 #if PA_TRACK_MEMORY
52 static int numAllocations_ = 0;
53 #endif
54
55
56 void *PaUtil_AllocateMemory( long size )
57 {
58 void *result = malloc( size );
59
60 #if PA_TRACK_MEMORY
61 if( result != NULL ) numAllocations_ += 1;
62 #endif
63 return result;
64 }
65
66
67 void PaUtil_FreeMemory( void *block )
68 {
69 if( block != NULL )
70 {
71 free( block );
72 #if PA_TRACK_MEMORY
73 numAllocations_ -= 1;
74 #endif
75
76 }
77 }
78
79
80 int PaUtil_CountCurrentlyAllocatedBlocks( void )
81 {
82 #if PA_TRACK_MEMORY
83 return numAllocations_;
84 #else
85 return 0;
86 #endif
87 }
88
89
90 void Pa_Sleep( long msec )
91 {
92 #ifdef HAVE_NANOSLEEP
93 struct timespec req = {0}, rem = {0};
94 PaTime time = msec / 1.e3;
95 req.tv_sec = (time_t)time;
96 assert(time - req.tv_sec < 1.0);
97 req.tv_nsec = (long)((time - req.tv_sec) * 1.e9);
98 nanosleep(&req, &rem);
99 /* XXX: Try sleeping the remaining time (contained in rem) if interrupted by a signal? */
100 #else
101 while( msec > 999 ) /* For OpenBSD and IRIX, argument */
102 { /* to usleep must be < 1000000. */
103 usleep( 999000 );
104 msec -= 999;
105 }
106 usleep( msec * 1000 );
107 #endif
108 }
109
110 /* *** NOT USED YET: ***
111 static int usePerformanceCounter_;
112 static double microsecondsPerTick_;
113 */
114
115 void PaUtil_InitializeClock( void )
116 {
117 /* TODO */
118 }
119
120
121 PaTime PaUtil_GetTime( void )
122 {
123 #ifdef HAVE_CLOCK_GETTIME
124 struct timespec tp;
125 clock_gettime(CLOCK_REALTIME, &tp);
126 return (PaTime)(tp.tv_sec + tp.tv_nsec / 1.e9);
127 #else
128 struct timeval tv;
129 gettimeofday( &tv, NULL );
130 return (PaTime) tv.tv_usec / 1000000. + tv.tv_sec;
131 #endif
132 }
133
134 PaError PaUtil_InitializeThreading( PaUtilThreading *threading )
135 {
136 (void) paUtilErr_;
137 return paNoError;
138 }
139
140 void PaUtil_TerminateThreading( PaUtilThreading *threading )
141 {
142 }
143
144 PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data )
145 {
146 pthread_create( &threading->callbackThread, NULL, threadRoutine, data );
147 return paNoError;
148 }
149
150 PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult )
151 {
152 PaError result = paNoError;
153 void *pret;
154
155 if( exitResult )
156 *exitResult = paNoError;
157
158 /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */
159 if( !wait )
160 pthread_cancel( threading->callbackThread ); /* XXX: Safe to call this if the thread has exited on its own? */
161 pthread_join( threading->callbackThread, &pret );
162
163 #ifdef PTHREAD_CANCELED
164 if( pret && PTHREAD_CANCELED != pret )
165 #else
166 /* !wait means the thread may have been canceled */
167 if( pret && wait )
168 #endif
169 {
170 if( exitResult )
171 *exitResult = *(PaError *) pret;
172 free( pret );
173 }
174
175 return result;
176 }
177
178 /* Threading */
179 /* paUnixMainThread
180 * We have to be a bit careful with defining this global variable,
181 * as explained below. */
182 #ifdef __apple__
183 /* apple/gcc has a "problem" with global vars and dynamic libs.
184 Initializing it seems to fix the problem.
185 Described a bit in this thread:
186 http://gcc.gnu.org/ml/gcc/2005-06/msg00179.html
187 */
188 pthread_t paUnixMainThread = 0;
189 #else
190 /*pthreads are opaque. We don't know that asigning it an int value
191 always makes sense, so we don't initialize it unless we have to.*/
192 pthread_t paUnixMainThread = 0;
193 #endif
194
195 PaError PaUnixThreading_Initialize()
196 {
197 paUnixMainThread = pthread_self();
198 return paNoError;
199 }
200
201 #if 0
202 PaError PaUnixThread_Initialize( PaUnixThread* self )
203 {
204 th->watchdogRunning = 0;
205 th->rtSched = 0;
206 th->callbackTime = 0;
207 th->callbackCpuTime = 0;
208 th->useWatchdog = 1;
209 th->throttledSleepTime = 0;
210 th->cpuLoadMeasurer = clm;
211
212 th->rtPrio = (sched_get_priority_max( SCHED_FIFO ) - sched_get_priority_min( SCHED_FIFO )) / 2
213 + sched_get_priority_min( SCHED_FIFO );
214 }
215 #endif
216
217 PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild )
218 {
219 PaError result = paNoError;
220 pthread_attr_t attr;
221 int started = 0;
222
223 memset( self, 0, sizeof (PaUnixThread) );
224 PaUnixMutex_Initialize( &self->mtx );
225 PA_ASSERT_CALL( pthread_cond_init( &self->cond, NULL ), 0 );
226
227 self->parentWaiting = 0 != waitForChild;
228
229 /* Spawn thread */
230
231 #if 0 && defined _POSIX_MEMLOCK && (_POSIX_MEMLOCK != -1)
232 if( th->rtSched )
233 {
234 if( mlockall( MCL_CURRENT | MCL_FUTURE ) < 0 )
235 {
236 int savedErrno = errno; /* In case errno gets overwritten */
237 assert( savedErrno != EINVAL ); /* Most likely a programmer error */
238 PA_UNLESS( (savedErrno == EPERM), paInternalError );
239 PA_DEBUG(( "%s: Failed locking memory\n", __FUNCTION__ ));
240 }
241 else
242 PA_DEBUG(( "%s: Successfully locked memory\n", __FUNCTION__ ));
243 }
244 #endif
245
246 PA_UNLESS( !pthread_attr_init( &attr ), paInternalError );
247 /* Priority relative to other processes */
248 PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError );
249
250 PA_UNLESS( !pthread_create( &self->thread, &attr, threadFunc, threadArg ), paInternalError );
251 started = 1;
252
253 #if 0
254 if( th->rtSched )
255 {
256 if( th->useWatchdog )
257 {
258 int err;
259 struct sched_param wdSpm = { 0 };
260 /* Launch watchdog, watchdog sets callback thread priority */
261 int prio = PA_MIN( th->rtPrio + 4, sched_get_priority_max( SCHED_FIFO ) );
262 wdSpm.sched_priority = prio;
263
264 PA_UNLESS( !pthread_attr_init( &attr ), paInternalError );
265 PA_UNLESS( !pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED ), paInternalError );
266 PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError );
267 PA_UNLESS( !pthread_attr_setschedpolicy( &attr, SCHED_FIFO ), paInternalError );
268 PA_UNLESS( !pthread_attr_setschedparam( &attr, &wdSpm ), paInternalError );
269 if( (err = pthread_create( &th->watchdogThread, &attr, &WatchdogFunc, th )) )
270 {
271 PA_UNLESS( err == EPERM, paInternalError );
272 /* Permission error, go on without realtime privileges */
273 PA_DEBUG(( "Failed bumping priority\n" ));
274 }
275 else
276 {
277 int policy;
278 th->watchdogRunning = 1;
279 PA_ENSURE_SYSTEM( pthread_getschedparam( th->watchdogThread, &policy, &wdSpm ), 0 );
280 /* Check if priority is right, policy could potentially differ from SCHED_FIFO (but that's alright) */
281 if( wdSpm.sched_priority != prio )
282 {
283 PA_DEBUG(( "Watchdog priority not set correctly (%d)\n", wdSpm.sched_priority ));
284 PA_ENSURE( paInternalError );
285 }
286 }
287 }
288 else
289 PA_ENSURE( BoostPriority( th ) );
290 }
291 #endif
292
293 if( self->parentWaiting )
294 {
295 PaTime till;
296 struct timespec ts;
297 int res = 0;
298 PaTime now;
299
300 PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );
301
302 /* Wait for stream to be started */
303 now = PaUtil_GetTime();
304 till = now + waitForChild;
305
306 while( self->parentWaiting && !res )
307 {
308 if( waitForChild > 0 )
309 {
310 ts.tv_sec = (time_t) floor( till );
311 ts.tv_nsec = (long) ((till - floor( till )) * 1e9);
312 res = pthread_cond_timedwait( &self->cond, &self->mtx.mtx, &ts );
313 }
314 else
315 {
316 res = pthread_cond_wait( &self->cond, &self->mtx.mtx );
317 }
318 }
319
320 PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) );
321
322 PA_UNLESS( !res || ETIMEDOUT == res, paInternalError );
323 PA_DEBUG(( "%s: Waited for %g seconds for stream to start\n", __FUNCTION__, PaUtil_GetTime() - now ));
324 if( ETIMEDOUT == res )
325 {
326 PA_ENSURE( paTimedOut );
327 }
328 }
329
330 end:
331 return result;
332 error:
333 if( started )
334 {
335 PaUnixThread_Terminate( self, 0, NULL );
336 }
337
338 goto end;
339 }
340
341 PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult )
342 {
343 PaError result = paNoError;
344 void* pret;
345
346 if( exitResult )
347 {
348 *exitResult = paNoError;
349 }
350 #if 0
351 if( watchdogExitResult )
352 *watchdogExitResult = paNoError;
353
354 if( th->watchdogRunning )
355 {
356 pthread_cancel( th->watchdogThread );
357 PA_ENSURE_SYSTEM( pthread_join( th->watchdogThread, &pret ), 0 );
358
359 if( pret && pret != PTHREAD_CANCELED )
360 {
361 if( watchdogExitResult )
362 *watchdogExitResult = *(PaError *) pret;
363 free( pret );
364 }
365 }
366 #endif
367
368 /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */
369 /* TODO: Make join time out */
370 self->stopRequested = wait;
371 if( !wait )
372 {
373 PA_DEBUG(( "%s: Canceling thread %d\n", __FUNCTION__, self->thread ));
374 /* XXX: Safe to call this if the thread has exited on its own? */
375 pthread_cancel( self->thread );
376 }
377 PA_DEBUG(( "%s: Joining thread %d\n", __FUNCTION__, self->thread ));
378 PA_ENSURE_SYSTEM( pthread_join( self->thread, &pret ), 0 );
379
380 if( pret && PTHREAD_CANCELED != pret )
381 {
382 if( exitResult )
383 {
384 *exitResult = *(PaError*)pret;
385 }
386 free( pret );
387 }
388
389 error:
390 PA_ASSERT_CALL( PaUnixMutex_Terminate( &self->mtx ), paNoError );
391 //PA_ASSERT_CALL( pthread_cond_destroy( &self->cond ), 0 );
392
393 return result;
394 }
395
396 PaError PaUnixThread_PrepareNotify( PaUnixThread* self )
397 {
398 PaError result = paNoError;
399 PA_UNLESS( self->parentWaiting, paInternalError );
400
401 PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );
402 self->locked = 1;
403
404 error:
405 return result;
406 }
407
408 PaError PaUnixThread_NotifyParent( PaUnixThread* self )
409 {
410 PaError result = paNoError;
411 PA_UNLESS( self->parentWaiting, paInternalError );
412
413 if( !self->locked )
414 {
415 PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );
416 self->locked = 1;
417 }
418 self->parentWaiting = 0;
419 pthread_cond_signal( &self->cond );
420 PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) );
421 self->locked = 0;
422
423 error:
424 return result;
425 }
426
427 int PaUnixThread_StopRequested( PaUnixThread* self )
428 {
429 return self->stopRequested;
430 }
431
432 PaError PaUnixMutex_Initialize( PaUnixMutex* self )
433 {
434 PaError result = paNoError;
435 PA_ASSERT_CALL( pthread_mutex_init( &self->mtx, NULL ), 0 );
436 return result;
437 }
438
439 PaError PaUnixMutex_Terminate( PaUnixMutex* self )
440 {
441 PaError result = paNoError;
442 PA_ASSERT_CALL( pthread_mutex_destroy( &self->mtx ), 0 );
443 return result;
444 }
445
446 /** Lock mutex.
447 *
448 * We're disabling thread cancellation while the thread is holding a lock, so mutexes are
449 * properly unlocked at termination time.
450 */
451 PaError PaUnixMutex_Lock( PaUnixMutex* self )
452 {
453 PaError result = paNoError;
454 int oldState;
455
456 PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &oldState ), 0 );
457 PA_ENSURE_SYSTEM( pthread_mutex_lock( &self->mtx ), 0 );
458
459 error:
460 return result;
461 }
462
463 /** Unlock mutex.
464 *
465 * Thread cancellation is enabled again after the mutex is properly unlocked.
466 */
467 PaError PaUnixMutex_Unlock( PaUnixMutex* self )
468 {
469 PaError result = paNoError;
470 int oldState;
471
472 PA_ENSURE_SYSTEM( pthread_mutex_unlock( &self->mtx ), 0 );
473 PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldState ), 0 );
474
475 error:
476 return result;
477 }
478
479 #if 0
480 /* Threading utility struct */
481 typedef struct PaAlsaThreading
482 {
483 pthread_t watchdogThread;
484 pthread_t callbackThread;
485 int watchdogRunning;
486 int rtSched;
487 int rtPrio;
488 int useWatchdog;
489 unsigned long throttledSleepTime;
490 volatile PaTime callbackTime;
491 volatile PaTime callbackCpuTime;
492 PaUtilCpuLoadMeasurer *cpuLoadMeasurer;
493 } PaAlsaThreading;
494
495 static void OnWatchdogExit( void *userData )
496 {
497 PaAlsaThreading *th = (PaAlsaThreading *) userData;
498 struct sched_param spm = { 0 };
499 assert( th );
500
501 PA_ASSERT_CALL( pthread_setschedparam( th->callbackThread, SCHED_OTHER, &spm ), 0 ); /* Lower before exiting */
502 PA_DEBUG(( "Watchdog exiting\n" ));
503 }
504
505 static PaError BoostPriority( PaAlsaThreading *th )
506 {
507 PaError result = paNoError;
508 struct sched_param spm = { 0 };
509 spm.sched_priority = th->rtPrio;
510
511 assert( th );
512
513 if( pthread_setschedparam( th->callbackThread, SCHED_FIFO, &spm ) != 0 )
514 {
515 PA_UNLESS( errno == EPERM, paInternalError ); /* Lack permission to raise priority */
516 PA_DEBUG(( "Failed bumping priority\n" ));
517 result = 0;
518 }
519 else
520 result = 1; /* Success */
521 error:
522 return result;
523 }
524
525 static void *WatchdogFunc( void *userData )
526 {
527 PaError result = paNoError, *pres = NULL;
528 int err;
529 PaAlsaThreading *th = (PaAlsaThreading *) userData;
530 unsigned intervalMsec = 500;
531 const PaTime maxSeconds = 3.; /* Max seconds between callbacks */
532 PaTime timeThen = PaUtil_GetTime(), timeNow, timeElapsed, cpuTimeThen, cpuTimeNow, cpuTimeElapsed;
533 double cpuLoad, avgCpuLoad = 0.;
534 int throttled = 0;
535
536 assert( th );
537
538 /* Execute OnWatchdogExit when exiting */
539 pthread_cleanup_push( &OnWatchdogExit, th );
540
541 /* Boost priority of callback thread */
542 PA_ENSURE( result = BoostPriority( th ) );
543 if( !result )
544 {
545 /* Boost failed, might as well exit */
546 pthread_exit( NULL );
547 }
548
549 cpuTimeThen = th->callbackCpuTime;
550 {
551 int policy;
552 struct sched_param spm = { 0 };
553 pthread_getschedparam( pthread_self(), &policy, &spm );
554 PA_DEBUG(( "%s: Watchdog priority is %d\n", __FUNCTION__, spm.sched_priority ));
555 }
556
557 while( 1 )
558 {
559 double lowpassCoeff = 0.9, lowpassCoeff1 = 0.99999 - lowpassCoeff;
560
561 /* Test before and after in case whatever underlying sleep call isn't interrupted by pthread_cancel */
562 pthread_testcancel();
563 Pa_Sleep( intervalMsec );
564 pthread_testcancel();
565
566 if( PaUtil_GetTime() - th->callbackTime > maxSeconds )
567 {
568 PA_DEBUG(( "Watchdog: Terminating callback thread\n" ));
569 /* Tell thread to terminate */
570 err = pthread_kill( th->callbackThread, SIGKILL );
571 pthread_exit( NULL );
572 }
573
574 PA_DEBUG(( "%s: PortAudio reports CPU load: %g\n", __FUNCTION__, PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) ));
575
576 /* Check if we should throttle, or unthrottle :P */
577 cpuTimeNow = th->callbackCpuTime;
578 cpuTimeElapsed = cpuTimeNow - cpuTimeThen;
579 cpuTimeThen = cpuTimeNow;
580
581 timeNow = PaUtil_GetTime();
582 timeElapsed = timeNow - timeThen;
583 timeThen = timeNow;
584 cpuLoad = cpuTimeElapsed / timeElapsed;
585 avgCpuLoad = avgCpuLoad * lowpassCoeff + cpuLoad * lowpassCoeff1;
586 /*
587 if( throttled )
588 PA_DEBUG(( "Watchdog: CPU load: %g, %g\n", avgCpuLoad, cpuTimeElapsed ));
589 */
590 if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) > .925 )
591 {
592 static int policy;
593 static struct sched_param spm = { 0 };
594 static const struct sched_param defaultSpm = { 0 };
595 PA_DEBUG(( "%s: Throttling audio thread, priority %d\n", __FUNCTION__, spm.sched_priority ));
596
597 pthread_getschedparam( th->callbackThread, &policy, &spm );
598 if( !pthread_setschedparam( th->callbackThread, SCHED_OTHER, &defaultSpm ) )
599 {
600 throttled = 1;
601 }
602 else
603 PA_DEBUG(( "Watchdog: Couldn't lower priority of audio thread: %s\n", strerror( errno ) ));
604
605 /* Give other processes a go, before raising priority again */
606 PA_DEBUG(( "%s: Watchdog sleeping for %lu msecs before unthrottling\n", __FUNCTION__, th->throttledSleepTime ));
607 Pa_Sleep( th->throttledSleepTime );
608
609 /* Reset callback priority */
610 if( pthread_setschedparam( th->callbackThread, SCHED_FIFO, &spm ) != 0 )
611 {
612 PA_DEBUG(( "%s: Couldn't raise priority of audio thread: %s\n", __FUNCTION__, strerror( errno ) ));
613 }
614
615 if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) >= .99 )
616 intervalMsec = 50;
617 else
618 intervalMsec = 100;
619
620 /*
621 lowpassCoeff = .97;
622 lowpassCoeff1 = .99999 - lowpassCoeff;
623 */
624 }
625 else if( throttled && avgCpuLoad < .8 )
626 {
627 intervalMsec = 500;
628 throttled = 0;
629
630 /*
631 lowpassCoeff = .9;
632 lowpassCoeff1 = .99999 - lowpassCoeff;
633 */
634 }
635 }
636
637 pthread_cleanup_pop( 1 ); /* Execute cleanup on exit */
638
639 error:
640 /* Shouldn't get here in the normal case */
641
642 /* Pass on error code */
643 pres = malloc( sizeof (PaError) );
644 *pres = result;
645
646 pthread_exit( pres );
647 }
648
649 static void CallbackUpdate( PaAlsaThreading *th )
650 {
651 th->callbackTime = PaUtil_GetTime();
652 th->callbackCpuTime = PaUtil_GetCpuLoad( th->cpuLoadMeasurer );
653 }
654 #endif
655
656 /*
657 static void *CanaryFunc( void *userData )
658 {
659 const unsigned intervalMsec = 1000;
660 PaUtilThreading *th = (PaUtilThreading *) userData;
661
662 while( 1 )
663 {
664 th->canaryTime = PaUtil_GetTime();
665
666 pthread_testcancel();
667 Pa_Sleep( intervalMsec );
668 }
669
670 pthread_exit( NULL );
671 }
672 */