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