PageRenderTime 419ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 3ms

/services/audioflinger/Threads.cpp

https://gitlab.com/F4KROM/android_frameworks_av
C++ | 6415 lines | 4924 code | 641 blank | 850 comment | 1347 complexity | c67907e47d7ffb79b79b5d0f997b1f70 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. **
  3. ** Copyright 2012, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. ** http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */
  17. #define LOG_TAG "AudioFlinger"
  18. //#define LOG_NDEBUG 0
  19. #define ATRACE_TAG ATRACE_TAG_AUDIO
  20. #include "Configuration.h"
  21. #include <math.h>
  22. #include <fcntl.h>
  23. #include <sys/stat.h>
  24. #include <cutils/properties.h>
  25. #include <media/AudioParameter.h>
  26. #include <media/AudioResamplerPublic.h>
  27. #include <utils/Log.h>
  28. #include <utils/Trace.h>
  29. #include <private/media/AudioTrackShared.h>
  30. #include <hardware/audio.h>
  31. #include <audio_effects/effect_ns.h>
  32. #include <audio_effects/effect_aec.h>
  33. #include <audio_utils/primitives.h>
  34. #include <audio_utils/format.h>
  35. #include <audio_utils/minifloat.h>
  36. // NBAIO implementations
  37. #include <media/nbaio/AudioStreamInSource.h>
  38. #include <media/nbaio/AudioStreamOutSink.h>
  39. #include <media/nbaio/MonoPipe.h>
  40. #include <media/nbaio/MonoPipeReader.h>
  41. #include <media/nbaio/Pipe.h>
  42. #include <media/nbaio/PipeReader.h>
  43. #include <media/nbaio/SourceAudioBufferProvider.h>
  44. #include <powermanager/PowerManager.h>
  45. #include <common_time/cc_helper.h>
  46. #include <common_time/local_clock.h>
  47. #include "AudioFlinger.h"
  48. #include "AudioMixer.h"
  49. #include "FastMixer.h"
  50. #include "FastCapture.h"
  51. #include "ServiceUtilities.h"
  52. #include "SchedulingPolicyService.h"
  53. #ifdef ADD_BATTERY_DATA
  54. #include <media/IMediaPlayerService.h>
  55. #include <media/IMediaDeathNotifier.h>
  56. #endif
  57. #ifdef DEBUG_CPU_USAGE
  58. #include <cpustats/CentralTendencyStatistics.h>
  59. #include <cpustats/ThreadCpuUsage.h>
  60. #endif
  61. // ----------------------------------------------------------------------------
  62. // Note: the following macro is used for extremely verbose logging message. In
  63. // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
  64. // 0; but one side effect of this is to turn all LOGV's as well. Some messages
  65. // are so verbose that we want to suppress them even when we have ALOG_ASSERT
  66. // turned on. Do not uncomment the #def below unless you really know what you
  67. // are doing and want to see all of the extremely verbose messages.
  68. //#define VERY_VERY_VERBOSE_LOGGING
  69. #ifdef VERY_VERY_VERBOSE_LOGGING
  70. #define ALOGVV ALOGV
  71. #else
  72. #define ALOGVV(a...) do { } while(0)
  73. #endif
  74. #define max(a, b) ((a) > (b) ? (a) : (b))
  75. namespace android {
  76. // retry counts for buffer fill timeout
  77. // 50 * ~20msecs = 1 second
  78. static const int8_t kMaxTrackRetries = 50;
  79. static const int8_t kMaxTrackStartupRetries = 50;
  80. // allow less retry attempts on direct output thread.
  81. // direct outputs can be a scarce resource in audio hardware and should
  82. // be released as quickly as possible.
  83. static const int8_t kMaxTrackRetriesDirect = 2;
  84. // don't warn about blocked writes or record buffer overflows more often than this
  85. static const nsecs_t kWarningThrottleNs = seconds(5);
  86. // RecordThread loop sleep time upon application overrun or audio HAL read error
  87. static const int kRecordThreadSleepUs = 5000;
  88. // maximum time to wait in sendConfigEvent_l() for a status to be received
  89. static const nsecs_t kConfigEventTimeoutNs = seconds(2);
  90. // minimum sleep time for the mixer thread loop when tracks are active but in underrun
  91. static const uint32_t kMinThreadSleepTimeUs = 5000;
  92. // maximum divider applied to the active sleep time in the mixer thread loop
  93. static const uint32_t kMaxThreadSleepTimeShift = 2;
  94. // minimum normal sink buffer size, expressed in milliseconds rather than frames
  95. static const uint32_t kMinNormalSinkBufferSizeMs = 20;
  96. // maximum normal sink buffer size
  97. static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
  98. // Offloaded output thread standby delay: allows track transition without going to standby
  99. static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
  100. // Whether to use fast mixer
  101. static const enum {
  102. FastMixer_Never, // never initialize or use: for debugging only
  103. FastMixer_Always, // always initialize and use, even if not needed: for debugging only
  104. // normal mixer multiplier is 1
  105. FastMixer_Static, // initialize if needed, then use all the time if initialized,
  106. // multiplier is calculated based on min & max normal mixer buffer size
  107. FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
  108. // multiplier is calculated based on min & max normal mixer buffer size
  109. // FIXME for FastMixer_Dynamic:
  110. // Supporting this option will require fixing HALs that can't handle large writes.
  111. // For example, one HAL implementation returns an error from a large write,
  112. // and another HAL implementation corrupts memory, possibly in the sample rate converter.
  113. // We could either fix the HAL implementations, or provide a wrapper that breaks
  114. // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
  115. } kUseFastMixer = FastMixer_Static;
  116. // Whether to use fast capture
  117. static const enum {
  118. FastCapture_Never, // never initialize or use: for debugging only
  119. FastCapture_Always, // always initialize and use, even if not needed: for debugging only
  120. FastCapture_Static, // initialize if needed, then use all the time if initialized
  121. } kUseFastCapture = FastCapture_Static;
  122. // Priorities for requestPriority
  123. static const int kPriorityAudioApp = 2;
  124. static const int kPriorityFastMixer = 3;
  125. static const int kPriorityFastCapture = 3;
  126. // IAudioFlinger::createTrack() reports back to client the total size of shared memory area
  127. // for the track. The client then sub-divides this into smaller buffers for its use.
  128. // Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
  129. // So for now we just assume that client is double-buffered for fast tracks.
  130. // FIXME It would be better for client to tell AudioFlinger the value of N,
  131. // so AudioFlinger could allocate the right amount of memory.
  132. // See the client's minBufCount and mNotificationFramesAct calculations for details.
  133. // This is the default value, if not specified by property.
  134. static const int kFastTrackMultiplier = 2;
  135. // The minimum and maximum allowed values
  136. static const int kFastTrackMultiplierMin = 1;
  137. static const int kFastTrackMultiplierMax = 2;
  138. // The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
  139. static int sFastTrackMultiplier = kFastTrackMultiplier;
  140. // See Thread::readOnlyHeap().
  141. // Initially this heap is used to allocate client buffers for "fast" AudioRecord.
  142. // Eventually it will be the single buffer that FastCapture writes into via HAL read(),
  143. // and that all "fast" AudioRecord clients read from. In either case, the size can be small.
  144. static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
  145. // ----------------------------------------------------------------------------
  146. static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
  147. static void sFastTrackMultiplierInit()
  148. {
  149. char value[PROPERTY_VALUE_MAX];
  150. if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
  151. char *endptr;
  152. unsigned long ul = strtoul(value, &endptr, 0);
  153. if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
  154. sFastTrackMultiplier = (int) ul;
  155. }
  156. }
  157. }
  158. // ----------------------------------------------------------------------------
  159. #ifdef ADD_BATTERY_DATA
  160. // To collect the amplifier usage
  161. static void addBatteryData(uint32_t params) {
  162. sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
  163. if (service == NULL) {
  164. // it already logged
  165. return;
  166. }
  167. service->addBatteryData(params);
  168. }
  169. #endif
  170. // ----------------------------------------------------------------------------
  171. // CPU Stats
  172. // ----------------------------------------------------------------------------
  173. class CpuStats {
  174. public:
  175. CpuStats();
  176. void sample(const String8 &title);
  177. #ifdef DEBUG_CPU_USAGE
  178. private:
  179. ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
  180. CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
  181. CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
  182. int mCpuNum; // thread's current CPU number
  183. int mCpukHz; // frequency of thread's current CPU in kHz
  184. #endif
  185. };
  186. CpuStats::CpuStats()
  187. #ifdef DEBUG_CPU_USAGE
  188. : mCpuNum(-1), mCpukHz(-1)
  189. #endif
  190. {
  191. }
  192. void CpuStats::sample(const String8 &title
  193. #ifndef DEBUG_CPU_USAGE
  194. __unused
  195. #endif
  196. ) {
  197. #ifdef DEBUG_CPU_USAGE
  198. // get current thread's delta CPU time in wall clock ns
  199. double wcNs;
  200. bool valid = mCpuUsage.sampleAndEnable(wcNs);
  201. // record sample for wall clock statistics
  202. if (valid) {
  203. mWcStats.sample(wcNs);
  204. }
  205. // get the current CPU number
  206. int cpuNum = sched_getcpu();
  207. // get the current CPU frequency in kHz
  208. int cpukHz = mCpuUsage.getCpukHz(cpuNum);
  209. // check if either CPU number or frequency changed
  210. if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
  211. mCpuNum = cpuNum;
  212. mCpukHz = cpukHz;
  213. // ignore sample for purposes of cycles
  214. valid = false;
  215. }
  216. // if no change in CPU number or frequency, then record sample for cycle statistics
  217. if (valid && mCpukHz > 0) {
  218. double cycles = wcNs * cpukHz * 0.000001;
  219. mHzStats.sample(cycles);
  220. }
  221. unsigned n = mWcStats.n();
  222. // mCpuUsage.elapsed() is expensive, so don't call it every loop
  223. if ((n & 127) == 1) {
  224. long long elapsed = mCpuUsage.elapsed();
  225. if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
  226. double perLoop = elapsed / (double) n;
  227. double perLoop100 = perLoop * 0.01;
  228. double perLoop1k = perLoop * 0.001;
  229. double mean = mWcStats.mean();
  230. double stddev = mWcStats.stddev();
  231. double minimum = mWcStats.minimum();
  232. double maximum = mWcStats.maximum();
  233. double meanCycles = mHzStats.mean();
  234. double stddevCycles = mHzStats.stddev();
  235. double minCycles = mHzStats.minimum();
  236. double maxCycles = mHzStats.maximum();
  237. mCpuUsage.resetElapsed();
  238. mWcStats.reset();
  239. mHzStats.reset();
  240. ALOGD("CPU usage for %s over past %.1f secs\n"
  241. " (%u mixer loops at %.1f mean ms per loop):\n"
  242. " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
  243. " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
  244. " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
  245. title.string(),
  246. elapsed * .000000001, n, perLoop * .000001,
  247. mean * .001,
  248. stddev * .001,
  249. minimum * .001,
  250. maximum * .001,
  251. mean / perLoop100,
  252. stddev / perLoop100,
  253. minimum / perLoop100,
  254. maximum / perLoop100,
  255. meanCycles / perLoop1k,
  256. stddevCycles / perLoop1k,
  257. minCycles / perLoop1k,
  258. maxCycles / perLoop1k);
  259. }
  260. }
  261. #endif
  262. };
  263. // ----------------------------------------------------------------------------
  264. // ThreadBase
  265. // ----------------------------------------------------------------------------
  266. AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
  267. audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
  268. : Thread(false /*canCallJava*/),
  269. mType(type),
  270. mAudioFlinger(audioFlinger),
  271. // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
  272. // are set by PlaybackThread::readOutputParameters_l() or
  273. // RecordThread::readInputParameters_l()
  274. //FIXME: mStandby should be true here. Is this some kind of hack?
  275. mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
  276. mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
  277. // mName will be set by concrete (non-virtual) subclass
  278. mDeathRecipient(new PMDeathRecipient(this))
  279. {
  280. }
  281. AudioFlinger::ThreadBase::~ThreadBase()
  282. {
  283. // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
  284. mConfigEvents.clear();
  285. // do not lock the mutex in destructor
  286. releaseWakeLock_l();
  287. if (mPowerManager != 0) {
  288. sp<IBinder> binder = mPowerManager->asBinder();
  289. binder->unlinkToDeath(mDeathRecipient);
  290. }
  291. }
  292. status_t AudioFlinger::ThreadBase::readyToRun()
  293. {
  294. status_t status = initCheck();
  295. if (status == NO_ERROR) {
  296. ALOGI("AudioFlinger's thread %p ready to run", this);
  297. } else {
  298. ALOGE("No working audio driver found.");
  299. }
  300. return status;
  301. }
  302. void AudioFlinger::ThreadBase::exit()
  303. {
  304. ALOGV("ThreadBase::exit");
  305. // do any cleanup required for exit to succeed
  306. preExit();
  307. {
  308. // This lock prevents the following race in thread (uniprocessor for illustration):
  309. // if (!exitPending()) {
  310. // // context switch from here to exit()
  311. // // exit() calls requestExit(), what exitPending() observes
  312. // // exit() calls signal(), which is dropped since no waiters
  313. // // context switch back from exit() to here
  314. // mWaitWorkCV.wait(...);
  315. // // now thread is hung
  316. // }
  317. AutoMutex lock(mLock);
  318. requestExit();
  319. mWaitWorkCV.broadcast();
  320. }
  321. // When Thread::requestExitAndWait is made virtual and this method is renamed to
  322. // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
  323. requestExitAndWait();
  324. }
  325. status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
  326. {
  327. status_t status;
  328. ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
  329. Mutex::Autolock _l(mLock);
  330. return sendSetParameterConfigEvent_l(keyValuePairs);
  331. }
  332. // sendConfigEvent_l() must be called with ThreadBase::mLock held
  333. // Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
  334. status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
  335. {
  336. status_t status = NO_ERROR;
  337. mConfigEvents.add(event);
  338. ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
  339. mWaitWorkCV.signal();
  340. mLock.unlock();
  341. {
  342. Mutex::Autolock _l(event->mLock);
  343. while (event->mWaitStatus) {
  344. if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
  345. event->mStatus = TIMED_OUT;
  346. event->mWaitStatus = false;
  347. }
  348. }
  349. status = event->mStatus;
  350. }
  351. mLock.lock();
  352. return status;
  353. }
  354. void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
  355. {
  356. Mutex::Autolock _l(mLock);
  357. sendIoConfigEvent_l(event, param);
  358. }
  359. // sendIoConfigEvent_l() must be called with ThreadBase::mLock held
  360. void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
  361. {
  362. sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
  363. sendConfigEvent_l(configEvent);
  364. }
  365. // sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
  366. void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
  367. {
  368. sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
  369. sendConfigEvent_l(configEvent);
  370. }
  371. // sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
  372. status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
  373. {
  374. sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
  375. return sendConfigEvent_l(configEvent);
  376. }
  377. status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
  378. const struct audio_patch *patch,
  379. audio_patch_handle_t *handle)
  380. {
  381. Mutex::Autolock _l(mLock);
  382. sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
  383. status_t status = sendConfigEvent_l(configEvent);
  384. if (status == NO_ERROR) {
  385. CreateAudioPatchConfigEventData *data =
  386. (CreateAudioPatchConfigEventData *)configEvent->mData.get();
  387. *handle = data->mHandle;
  388. }
  389. return status;
  390. }
  391. status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
  392. const audio_patch_handle_t handle)
  393. {
  394. Mutex::Autolock _l(mLock);
  395. sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
  396. return sendConfigEvent_l(configEvent);
  397. }
  398. // post condition: mConfigEvents.isEmpty()
  399. void AudioFlinger::ThreadBase::processConfigEvents_l()
  400. {
  401. bool configChanged = false;
  402. while (!mConfigEvents.isEmpty()) {
  403. ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
  404. sp<ConfigEvent> event = mConfigEvents[0];
  405. mConfigEvents.removeAt(0);
  406. switch (event->mType) {
  407. case CFG_EVENT_PRIO: {
  408. PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
  409. // FIXME Need to understand why this has to be done asynchronously
  410. int err = requestPriority(data->mPid, data->mTid, data->mPrio,
  411. true /*asynchronous*/);
  412. if (err != 0) {
  413. ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
  414. data->mPrio, data->mPid, data->mTid, err);
  415. }
  416. } break;
  417. case CFG_EVENT_IO: {
  418. IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
  419. audioConfigChanged(data->mEvent, data->mParam);
  420. } break;
  421. case CFG_EVENT_SET_PARAMETER: {
  422. SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
  423. if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
  424. configChanged = true;
  425. }
  426. } break;
  427. case CFG_EVENT_CREATE_AUDIO_PATCH: {
  428. CreateAudioPatchConfigEventData *data =
  429. (CreateAudioPatchConfigEventData *)event->mData.get();
  430. event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
  431. } break;
  432. case CFG_EVENT_RELEASE_AUDIO_PATCH: {
  433. ReleaseAudioPatchConfigEventData *data =
  434. (ReleaseAudioPatchConfigEventData *)event->mData.get();
  435. event->mStatus = releaseAudioPatch_l(data->mHandle);
  436. } break;
  437. default:
  438. ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
  439. break;
  440. }
  441. {
  442. Mutex::Autolock _l(event->mLock);
  443. if (event->mWaitStatus) {
  444. event->mWaitStatus = false;
  445. event->mCond.signal();
  446. }
  447. }
  448. ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
  449. }
  450. if (configChanged) {
  451. cacheParameters_l();
  452. }
  453. }
  454. String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
  455. String8 s;
  456. if (output) {
  457. if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
  458. if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
  459. if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
  460. if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
  461. if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
  462. if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
  463. if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
  464. if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
  465. if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
  466. if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
  467. if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
  468. if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
  469. if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
  470. if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
  471. if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
  472. if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
  473. if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
  474. if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
  475. if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
  476. } else {
  477. if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
  478. if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
  479. if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
  480. if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
  481. if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
  482. if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
  483. if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
  484. if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
  485. if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
  486. if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
  487. if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
  488. if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
  489. if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
  490. if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
  491. if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
  492. }
  493. int len = s.length();
  494. if (s.length() > 2) {
  495. char *str = s.lockBuffer(len);
  496. s.unlockBuffer(len - 2);
  497. }
  498. return s;
  499. }
  500. void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
  501. {
  502. const size_t SIZE = 256;
  503. char buffer[SIZE];
  504. String8 result;
  505. bool locked = AudioFlinger::dumpTryLock(mLock);
  506. if (!locked) {
  507. dprintf(fd, "thread %p maybe dead locked\n", this);
  508. }
  509. dprintf(fd, " I/O handle: %d\n", mId);
  510. dprintf(fd, " TID: %d\n", getTid());
  511. dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
  512. dprintf(fd, " Sample rate: %u\n", mSampleRate);
  513. dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
  514. dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
  515. dprintf(fd, " Channel Count: %u\n", mChannelCount);
  516. dprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
  517. channelMaskToString(mChannelMask, mType != RECORD).string());
  518. dprintf(fd, " Format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
  519. dprintf(fd, " Frame size: %zu\n", mFrameSize);
  520. dprintf(fd, " Pending config events:");
  521. size_t numConfig = mConfigEvents.size();
  522. if (numConfig) {
  523. for (size_t i = 0; i < numConfig; i++) {
  524. mConfigEvents[i]->dump(buffer, SIZE);
  525. dprintf(fd, "\n %s", buffer);
  526. }
  527. dprintf(fd, "\n");
  528. } else {
  529. dprintf(fd, " none\n");
  530. }
  531. if (locked) {
  532. mLock.unlock();
  533. }
  534. }
  535. void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
  536. {
  537. const size_t SIZE = 256;
  538. char buffer[SIZE];
  539. String8 result;
  540. size_t numEffectChains = mEffectChains.size();
  541. snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
  542. write(fd, buffer, strlen(buffer));
  543. for (size_t i = 0; i < numEffectChains; ++i) {
  544. sp<EffectChain> chain = mEffectChains[i];
  545. if (chain != 0) {
  546. chain->dump(fd, args);
  547. }
  548. }
  549. }
  550. void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
  551. {
  552. Mutex::Autolock _l(mLock);
  553. acquireWakeLock_l(uid);
  554. }
  555. String16 AudioFlinger::ThreadBase::getWakeLockTag()
  556. {
  557. switch (mType) {
  558. case MIXER:
  559. return String16("AudioMix");
  560. case DIRECT:
  561. return String16("AudioDirectOut");
  562. case DUPLICATING:
  563. return String16("AudioDup");
  564. case RECORD:
  565. return String16("AudioIn");
  566. case OFFLOAD:
  567. return String16("AudioOffload");
  568. default:
  569. ALOG_ASSERT(false);
  570. return String16("AudioUnknown");
  571. }
  572. }
  573. void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
  574. {
  575. getPowerManager_l();
  576. if (mPowerManager != 0) {
  577. sp<IBinder> binder = new BBinder();
  578. status_t status;
  579. if (uid >= 0) {
  580. status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
  581. binder,
  582. getWakeLockTag(),
  583. String16("media"),
  584. uid,
  585. true /* FIXME force oneway contrary to .aidl */);
  586. } else {
  587. status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
  588. binder,
  589. getWakeLockTag(),
  590. String16("media"),
  591. true /* FIXME force oneway contrary to .aidl */);
  592. }
  593. if (status == NO_ERROR) {
  594. mWakeLockToken = binder;
  595. }
  596. ALOGV("acquireWakeLock_l() %s status %d", mName, status);
  597. }
  598. }
  599. void AudioFlinger::ThreadBase::releaseWakeLock()
  600. {
  601. Mutex::Autolock _l(mLock);
  602. releaseWakeLock_l();
  603. }
  604. void AudioFlinger::ThreadBase::releaseWakeLock_l()
  605. {
  606. if (mWakeLockToken != 0) {
  607. ALOGV("releaseWakeLock_l() %s", mName);
  608. if (mPowerManager != 0) {
  609. mPowerManager->releaseWakeLock(mWakeLockToken, 0,
  610. true /* FIXME force oneway contrary to .aidl */);
  611. }
  612. mWakeLockToken.clear();
  613. }
  614. }
  615. void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
  616. Mutex::Autolock _l(mLock);
  617. updateWakeLockUids_l(uids);
  618. }
  619. void AudioFlinger::ThreadBase::getPowerManager_l() {
  620. if (mPowerManager == 0) {
  621. // use checkService() to avoid blocking if power service is not up yet
  622. sp<IBinder> binder =
  623. defaultServiceManager()->checkService(String16("power"));
  624. if (binder == 0) {
  625. ALOGW("Thread %s cannot connect to the power manager service", mName);
  626. } else {
  627. mPowerManager = interface_cast<IPowerManager>(binder);
  628. binder->linkToDeath(mDeathRecipient);
  629. }
  630. }
  631. }
  632. void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
  633. getPowerManager_l();
  634. if (mWakeLockToken == NULL) {
  635. ALOGE("no wake lock to update!");
  636. return;
  637. }
  638. if (mPowerManager != 0) {
  639. sp<IBinder> binder = new BBinder();
  640. status_t status;
  641. status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
  642. true /* FIXME force oneway contrary to .aidl */);
  643. ALOGV("acquireWakeLock_l() %s status %d", mName, status);
  644. }
  645. }
  646. void AudioFlinger::ThreadBase::clearPowerManager()
  647. {
  648. Mutex::Autolock _l(mLock);
  649. releaseWakeLock_l();
  650. mPowerManager.clear();
  651. }
  652. void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
  653. {
  654. sp<ThreadBase> thread = mThread.promote();
  655. if (thread != 0) {
  656. thread->clearPowerManager();
  657. }
  658. ALOGW("power manager service died !!!");
  659. }
  660. void AudioFlinger::ThreadBase::setEffectSuspended(
  661. const effect_uuid_t *type, bool suspend, int sessionId)
  662. {
  663. Mutex::Autolock _l(mLock);
  664. setEffectSuspended_l(type, suspend, sessionId);
  665. }
  666. void AudioFlinger::ThreadBase::setEffectSuspended_l(
  667. const effect_uuid_t *type, bool suspend, int sessionId)
  668. {
  669. sp<EffectChain> chain = getEffectChain_l(sessionId);
  670. if (chain != 0) {
  671. if (type != NULL) {
  672. chain->setEffectSuspended_l(type, suspend);
  673. } else {
  674. chain->setEffectSuspendedAll_l(suspend);
  675. }
  676. }
  677. updateSuspendedSessions_l(type, suspend, sessionId);
  678. }
  679. void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
  680. {
  681. ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
  682. if (index < 0) {
  683. return;
  684. }
  685. const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
  686. mSuspendedSessions.valueAt(index);
  687. for (size_t i = 0; i < sessionEffects.size(); i++) {
  688. sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
  689. for (int j = 0; j < desc->mRefCount; j++) {
  690. if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
  691. chain->setEffectSuspendedAll_l(true);
  692. } else {
  693. ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
  694. desc->mType.timeLow);
  695. chain->setEffectSuspended_l(&desc->mType, true);
  696. }
  697. }
  698. }
  699. }
  700. void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
  701. bool suspend,
  702. int sessionId)
  703. {
  704. ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
  705. KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
  706. if (suspend) {
  707. if (index >= 0) {
  708. sessionEffects = mSuspendedSessions.valueAt(index);
  709. } else {
  710. mSuspendedSessions.add(sessionId, sessionEffects);
  711. }
  712. } else {
  713. if (index < 0) {
  714. return;
  715. }
  716. sessionEffects = mSuspendedSessions.valueAt(index);
  717. }
  718. int key = EffectChain::kKeyForSuspendAll;
  719. if (type != NULL) {
  720. key = type->timeLow;
  721. }
  722. index = sessionEffects.indexOfKey(key);
  723. sp<SuspendedSessionDesc> desc;
  724. if (suspend) {
  725. if (index >= 0) {
  726. desc = sessionEffects.valueAt(index);
  727. } else {
  728. desc = new SuspendedSessionDesc();
  729. if (type != NULL) {
  730. desc->mType = *type;
  731. }
  732. sessionEffects.add(key, desc);
  733. ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
  734. }
  735. desc->mRefCount++;
  736. } else {
  737. if (index < 0) {
  738. return;
  739. }
  740. desc = sessionEffects.valueAt(index);
  741. if (--desc->mRefCount == 0) {
  742. ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
  743. sessionEffects.removeItemsAt(index);
  744. if (sessionEffects.isEmpty()) {
  745. ALOGV("updateSuspendedSessions_l() restore removing session %d",
  746. sessionId);
  747. mSuspendedSessions.removeItem(sessionId);
  748. }
  749. }
  750. }
  751. if (!sessionEffects.isEmpty()) {
  752. mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
  753. }
  754. }
  755. void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
  756. bool enabled,
  757. int sessionId)
  758. {
  759. Mutex::Autolock _l(mLock);
  760. checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
  761. }
  762. void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
  763. bool enabled,
  764. int sessionId)
  765. {
  766. if (mType != RECORD) {
  767. // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
  768. // another session. This gives the priority to well behaved effect control panels
  769. // and applications not using global effects.
  770. // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
  771. // global effects
  772. if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
  773. setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
  774. }
  775. }
  776. sp<EffectChain> chain = getEffectChain_l(sessionId);
  777. if (chain != 0) {
  778. chain->checkSuspendOnEffectEnabled(effect, enabled);
  779. }
  780. }
  781. // ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
  782. sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
  783. const sp<AudioFlinger::Client>& client,
  784. const sp<IEffectClient>& effectClient,
  785. int32_t priority,
  786. int sessionId,
  787. effect_descriptor_t *desc,
  788. int *enabled,
  789. status_t *status)
  790. {
  791. sp<EffectModule> effect;
  792. sp<EffectHandle> handle;
  793. status_t lStatus;
  794. sp<EffectChain> chain;
  795. bool chainCreated = false;
  796. bool effectCreated = false;
  797. bool effectRegistered = false;
  798. lStatus = initCheck();
  799. if (lStatus != NO_ERROR) {
  800. ALOGW("createEffect_l() Audio driver not initialized.");
  801. goto Exit;
  802. }
  803. // Reject any effect on Direct output threads for now, since the format of
  804. // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
  805. if (mType == DIRECT) {
  806. ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
  807. desc->name, mName);
  808. lStatus = BAD_VALUE;
  809. goto Exit;
  810. }
  811. // Reject any effect on mixer or duplicating multichannel sinks.
  812. // TODO: fix both format and multichannel issues with effects.
  813. if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
  814. ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
  815. desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
  816. lStatus = BAD_VALUE;
  817. goto Exit;
  818. }
  819. // Allow global effects only on offloaded and mixer threads
  820. if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
  821. switch (mType) {
  822. case MIXER:
  823. case OFFLOAD:
  824. break;
  825. case DIRECT:
  826. case DUPLICATING:
  827. case RECORD:
  828. default:
  829. ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
  830. lStatus = BAD_VALUE;
  831. goto Exit;
  832. }
  833. }
  834. // Only Pre processor effects are allowed on input threads and only on input threads
  835. if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
  836. ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
  837. desc->name, desc->flags, mType);
  838. lStatus = BAD_VALUE;
  839. goto Exit;
  840. }
  841. ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
  842. { // scope for mLock
  843. Mutex::Autolock _l(mLock);
  844. // check for existing effect chain with the requested audio session
  845. chain = getEffectChain_l(sessionId);
  846. if (chain == 0) {
  847. // create a new chain for this session
  848. ALOGV("createEffect_l() new effect chain for session %d", sessionId);
  849. chain = new EffectChain(this, sessionId);
  850. addEffectChain_l(chain);
  851. chain->setStrategy(getStrategyForSession_l(sessionId));
  852. chainCreated = true;
  853. } else {
  854. effect = chain->getEffectFromDesc_l(desc);
  855. }
  856. ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
  857. if (effect == 0) {
  858. int id = mAudioFlinger->nextUniqueId();
  859. // Check CPU and memory usage
  860. lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
  861. if (lStatus != NO_ERROR) {
  862. goto Exit;
  863. }
  864. effectRegistered = true;
  865. // create a new effect module if none present in the chain
  866. effect = new EffectModule(this, chain, desc, id, sessionId);
  867. lStatus = effect->status();
  868. if (lStatus != NO_ERROR) {
  869. goto Exit;
  870. }
  871. effect->setOffloaded(mType == OFFLOAD, mId);
  872. lStatus = chain->addEffect_l(effect);
  873. if (lStatus != NO_ERROR) {
  874. goto Exit;
  875. }
  876. effectCreated = true;
  877. effect->setDevice(mOutDevice);
  878. effect->setDevice(mInDevice);
  879. effect->setMode(mAudioFlinger->getMode());
  880. effect->setAudioSource(mAudioSource);
  881. }
  882. // create effect handle and connect it to effect module
  883. handle = new EffectHandle(effect, client, effectClient, priority);
  884. lStatus = handle->initCheck();
  885. if (lStatus == OK) {
  886. lStatus = effect->addHandle(handle.get());
  887. }
  888. if (enabled != NULL) {
  889. *enabled = (int)effect->isEnabled();
  890. }
  891. }
  892. Exit:
  893. if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
  894. Mutex::Autolock _l(mLock);
  895. if (effectCreated) {
  896. chain->removeEffect_l(effect);
  897. }
  898. if (effectRegistered) {
  899. AudioSystem::unregisterEffect(effect->id());
  900. }
  901. if (chainCreated) {
  902. removeEffectChain_l(chain);
  903. }
  904. handle.clear();
  905. }
  906. *status = lStatus;
  907. return handle;
  908. }
  909. sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
  910. {
  911. Mutex::Autolock _l(mLock);
  912. return getEffect_l(sessionId, effectId);
  913. }
  914. sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
  915. {
  916. sp<EffectChain> chain = getEffectChain_l(sessionId);
  917. return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
  918. }
  919. // PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
  920. // PlaybackThread::mLock held
  921. status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
  922. {
  923. // check for existing effect chain with the requested audio session
  924. int sessionId = effect->sessionId();
  925. sp<EffectChain> chain = getEffectChain_l(sessionId);
  926. bool chainCreated = false;
  927. ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
  928. "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
  929. this, effect->desc().name, effect->desc().flags);
  930. if (chain == 0) {
  931. // create a new chain for this session
  932. ALOGV("addEffect_l() new effect chain for session %d", sessionId);
  933. chain = new EffectChain(this, sessionId);
  934. addEffectChain_l(chain);
  935. chain->setStrategy(getStrategyForSession_l(sessionId));
  936. chainCreated = true;
  937. }
  938. ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
  939. if (chain->getEffectFromId_l(effect->id()) != 0) {
  940. ALOGW("addEffect_l() %p effect %s already present in chain %p",
  941. this, effect->desc().name, chain.get());
  942. return BAD_VALUE;
  943. }
  944. effect->setOffloaded(mType == OFFLOAD, mId);
  945. status_t status = chain->addEffect_l(effect);
  946. if (status != NO_ERROR) {
  947. if (chainCreated) {
  948. removeEffectChain_l(chain);
  949. }
  950. return status;
  951. }
  952. effect->setDevice(mOutDevice);
  953. effect->setDevice(mInDevice);
  954. effect->setMode(mAudioFlinger->getMode());
  955. effect->setAudioSource(mAudioSource);
  956. return NO_ERROR;
  957. }
  958. void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
  959. ALOGV("removeEffect_l() %p effect %p", this, effect.get());
  960. effect_descriptor_t desc = effect->desc();
  961. if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
  962. detachAuxEffect_l(effect->id());
  963. }
  964. sp<EffectChain> chain = effect->chain().promote();
  965. if (chain != 0) {
  966. // remove effect chain if removing last effect
  967. if (chain->removeEffect_l(effect) == 0) {
  968. removeEffectChain_l(chain);
  969. }
  970. } else {
  971. ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
  972. }
  973. }
  974. void AudioFlinger::ThreadBase::lockEffectChains_l(
  975. Vector< sp<AudioFlinger::EffectChain> >& effectChains)
  976. {
  977. effectChains = mEffectChains;
  978. for (size_t i = 0; i < mEffectChains.size(); i++) {
  979. mEffectChains[i]->lock();
  980. }
  981. }
  982. void AudioFlinger::ThreadBase::unlockEffectChains(
  983. const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
  984. {
  985. for (size_t i = 0; i < effectChains.size(); i++) {
  986. effectChains[i]->unlock();
  987. }
  988. }
  989. sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
  990. {
  991. Mutex::Autolock _l(mLock);
  992. return getEffectChain_l(sessionId);
  993. }
  994. sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
  995. {
  996. size_t size = mEffectChains.size();
  997. for (size_t i = 0; i < size; i++) {
  998. if (mEffectChains[i]->sessionId() == sessionId) {
  999. return mEffectChains[i];
  1000. }
  1001. }
  1002. return 0;
  1003. }
  1004. void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
  1005. {
  1006. Mutex::Autolock _l(mLock);
  1007. size_t size = mEffectChains.size();
  1008. for (size_t i = 0; i < size; i++) {
  1009. mEffectChains[i]->setMode_l(mode);
  1010. }
  1011. }
  1012. void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
  1013. {
  1014. config->type = AUDIO_PORT_TYPE_MIX;
  1015. config->ext.mix.handle = mId;
  1016. config->sample_rate = mSampleRate;
  1017. config->format = mFormat;
  1018. config->channel_mask = mChannelMask;
  1019. config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
  1020. AUDIO_PORT_CONFIG_FORMAT;
  1021. }
  1022. // ----------------------------------------------------------------------------
  1023. // Playback
  1024. // ----------------------------------------------------------------------------
  1025. AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
  1026. AudioStreamOut* output,
  1027. audio_io_handle_t id,
  1028. audio_devices_t device,
  1029. type_t type)
  1030. : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
  1031. mNormalFrameCount(0), mSinkBuffer(NULL),
  1032. mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
  1033. mMixerBuffer(NULL),
  1034. mMixerBufferSize(0),
  1035. mMixerBufferFormat(AUDIO_FORMAT_INVALID),
  1036. mMixerBufferValid(false),
  1037. mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
  1038. mEffectBuffer(NULL),
  1039. mEffectBufferSize(0),
  1040. mEffectBufferFormat(AUDIO_FORMAT_INVALID),
  1041. mEffectBufferValid(false),
  1042. mSuspended(0), mBytesWritten(0),
  1043. mActiveTracksGeneration(0),
  1044. // mStreamTypes[] initialized in constructor body
  1045. mOutput(output),
  1046. mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
  1047. mMixerStatus(MIXER_IDLE),
  1048. mMixerStatusIgnoringFastTracks(MIXER_IDLE),
  1049. standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
  1050. mBytesRemaining(0),
  1051. mCurrentWriteLength(0),
  1052. mUseAsyncWrite(false),
  1053. mWriteAckSequence(0),
  1054. mDrainSequence(0),
  1055. mSignalPending(false),
  1056. mScreenState(AudioFlinger::mScreenState),
  1057. // index 0 is reserved for normal mixer's submix
  1058. mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
  1059. mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
  1060. // mLatchD, mLatchQ,
  1061. mLatchDValid(false), mLatchQValid(false)
  1062. {
  1063. snprintf(mName, kNameLength, "AudioOut_%X", id);
  1064. mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
  1065. // Assumes constructor is called by AudioFlinger with it's mLock held, but
  1066. // it would be safer to explicitly pass initial masterVolume/masterMute as
  1067. // parameter.
  1068. //
  1069. // If the HAL we are using has support for master volume or master mute,
  1070. // then do not attenuate or mute during mixing (just leave the volume at 1.0
  1071. // and the mute set to false).
  1072. mMasterVolume = audioFlinger->masterVolume_l();
  1073. mMasterMute = audioFlinger->masterMute_l();
  1074. if (mOutput && mOutput->audioHwDev) {
  1075. if (mOutput->audioHwDev->canSetMasterVolume()) {
  1076. mMasterVolume = 1.0;
  1077. }
  1078. if (mOutput->audioHwDev->canSetMasterMute()) {
  1079. mMasterMute = false;
  1080. }
  1081. }
  1082. readOutputParameters_l();
  1083. // ++ operator does not compile
  1084. for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
  1085. stream = (audio_stream_type_t) (stream + 1)) {
  1086. mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
  1087. mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
  1088. }
  1089. }
  1090. AudioFlinger::PlaybackThread::~PlaybackThread()
  1091. {
  1092. mAudioFlinger->unregisterWriter(mNBLogWriter);
  1093. free(mSinkBuffer);
  1094. free(mMixerBuffer);
  1095. free(mEffectBuffer);
  1096. }
  1097. void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
  1098. {
  1099. dumpInternals(fd, args);
  1100. dumpTracks(fd, args);
  1101. dumpEffectChains(fd, args);
  1102. }
  1103. void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
  1104. {
  1105. const size_t SIZE = 256;
  1106. char buffer[SIZE];
  1107. String8 result;
  1108. result.appendFormat(" Stream volumes in dB: ");
  1109. for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
  1110. const stream_type_t *st = &mStreamTypes[i];
  1111. if (i > 0) {
  1112. result.appendFormat(", ");
  1113. }
  1114. result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
  1115. if (st->mute) {
  1116. result.append("M");
  1117. }
  1118. }
  1119. result.append("\n");
  1120. write(fd, result.string(), result.length());
  1121. result.clear();
  1122. // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
  1123. FastTrackUnderruns underruns = getFastTrackUnderruns(0);
  1124. dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
  1125. underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
  1126. size_t numtracks = mTracks.size();
  1127. size_t numactive = mActiveTracks.size();
  1128. dprintf(fd, " %d Tracks", numtracks);
  1129. size_t numactiveseen = 0;
  1130. if (numtracks) {
  1131. dprintf(fd, " of which %d are active\n", numactive);
  1132. Track::appendDumpHeader(result);
  1133. for (size_t i = 0; i < numtracks; ++i) {
  1134. sp<Track> track = mTracks[i];
  1135. if (track != 0) {
  1136. bool active = mActiveTracks.indexOf(track) >= 0;
  1137. if (active) {
  1138. numactiveseen++;
  1139. }
  1140. track->dump(buffer, SIZE, active);
  1141. result.append(buffer);
  1142. }
  1143. }
  1144. } else {
  1145. result.append("\n");
  1146. }
  1147. if (numactiveseen != numactive) {
  1148. // some tracks in the active list were not in the tracks list
  1149. snprintf(buffer, SIZE, " The following tracks are in the active list but"
  1150. " not in the track list\n");
  1151. result.append(buffer);
  1152. Track::appendDumpHeader(result);
  1153. for (size_t i = 0; i < numactive; ++i) {
  1154. sp<Track> track = mActiveTracks[i].promote();
  1155. if (track != 0 && mTracks.indexOf(track) < 0) {
  1156. track->dump(buffer, SIZE, true);
  1157. result.append(buffer);
  1158. }
  1159. }
  1160. }
  1161. write(fd, result.string(), result.size());
  1162. }
  1163. void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
  1164. {
  1165. dprintf(fd, "\nOutput thread %p:\n", this);
  1166. dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
  1167. dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
  1168. dprintf(fd, " Total writes: %d\n", mNumWrites);
  1169. dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
  1170. dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
  1171. dprintf(fd, " Suspend count: %d\n", mSuspended);
  1172. dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
  1173. dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
  1174. dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
  1175. dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
  1176. dumpBase(fd, args);
  1177. }
  1178. // Thread virtuals
  1179. void AudioFlinger::PlaybackThread::onFirstRef()
  1180. {
  1181. run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
  1182. }
  1183. // ThreadBase virtuals
  1184. void AudioFlinger::PlaybackThread::preExit()
  1185. {
  1186. ALOGV(" preExit()");
  1187. // FIXME this is using hard-coded strings but in the future, this functionality will be
  1188. // converted to use audio HAL extensions required to support tunneling
  1189. mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
  1190. }
  1191. // PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
  1192. sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
  1193. const sp<AudioFlinger::Client>& client,
  1194. audio_stream_type_t streamType,
  1195. uint32_t sampleRate,
  1196. audio_format_t format,
  1197. audio_channel_mask_t channelMask,
  1198. size_t *pFrameCount,
  1199. const sp<IMemory>& sharedBuffer,
  1200. int sessionId,
  1201. IAudioFlinger::track_flags_t *flags,
  1202. pid_t tid,
  1203. int uid,
  1204. status_t *status)
  1205. {
  1206. size_t frameCount = *pFrameCount;
  1207. sp<Track> track;
  1208. status_t lStatus;
  1209. bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) !=

Large files files are truncated, but you can click here to view the full file