pa_unix_util.c 20 KB

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