PageRenderTime 91ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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) != 0;
  1210. // client expresses a preference for FAST, but we get the final say
  1211. if (*flags & IAudioFlinger::TRACK_FAST) {
  1212. if (
  1213. // not timed
  1214. (!isTimed) &&
  1215. // either of these use cases:
  1216. (
  1217. // use case 1: shared buffer with any frame count
  1218. (
  1219. (sharedBuffer != 0)
  1220. ) ||
  1221. // use case 2: callback handler and frame count is default or at least as large as HAL
  1222. (
  1223. (tid != -1) &&
  1224. ((frameCount == 0) ||
  1225. (frameCount >= mFrameCount))
  1226. )
  1227. ) &&
  1228. // PCM data
  1229. audio_is_linear_pcm(format) &&
  1230. // identical channel mask to sink, or mono in and stereo sink
  1231. (channelMask == mChannelMask ||
  1232. (channelMask == AUDIO_CHANNEL_OUT_MONO &&
  1233. mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
  1234. // hardware sample rate
  1235. (sampleRate == mSampleRate) &&
  1236. // normal mixer has an associated fast mixer
  1237. hasFastMixer() &&
  1238. // there are sufficient fast track slots available
  1239. (mFastTrackAvailMask != 0)
  1240. // FIXME test that MixerThread for this fast track has a capable output HAL
  1241. // FIXME add a permission test also?
  1242. ) {
  1243. // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
  1244. if (frameCount == 0) {
  1245. // read the fast track multiplier property the first time it is needed
  1246. int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
  1247. if (ok != 0) {
  1248. ALOGE("%s pthread_once failed: %d", __func__, ok);
  1249. }
  1250. frameCount = mFrameCount * sFastTrackMultiplier;
  1251. }
  1252. ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
  1253. frameCount, mFrameCount);
  1254. } else {
  1255. ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
  1256. "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
  1257. "sampleRate=%u mSampleRate=%u "
  1258. "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
  1259. isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
  1260. audio_is_linear_pcm(format),
  1261. channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
  1262. *flags &= ~IAudioFlinger::TRACK_FAST;
  1263. // For compatibility with AudioTrack calculation, buffer depth is forced
  1264. // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
  1265. // This is probably too conservative, but legacy application code may depend on it.
  1266. // If you change this calculation, also review the start threshold which is related.
  1267. uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
  1268. uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
  1269. if (minBufCount < 2) {
  1270. minBufCount = 2;
  1271. }
  1272. size_t minFrameCount = mNormalFrameCount * minBufCount;
  1273. if (frameCount < minFrameCount) {
  1274. frameCount = minFrameCount;
  1275. }
  1276. }
  1277. }
  1278. *pFrameCount = frameCount;
  1279. switch (mType) {
  1280. case DIRECT:
  1281. if (audio_is_linear_pcm(format)) {
  1282. if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
  1283. ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
  1284. "for output %p with format %#x",
  1285. sampleRate, format, channelMask, mOutput, mFormat);
  1286. lStatus = BAD_VALUE;
  1287. goto Exit;
  1288. }
  1289. }
  1290. break;
  1291. case OFFLOAD:
  1292. if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
  1293. ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
  1294. "for output %p with format %#x",
  1295. sampleRate, format, channelMask, mOutput, mFormat);
  1296. lStatus = BAD_VALUE;
  1297. goto Exit;
  1298. }
  1299. break;
  1300. default:
  1301. if (!audio_is_linear_pcm(format)) {
  1302. ALOGE("createTrack_l() Bad parameter: format %#x \""
  1303. "for output %p with format %#x",
  1304. format, mOutput, mFormat);
  1305. lStatus = BAD_VALUE;
  1306. goto Exit;
  1307. }
  1308. if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
  1309. ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
  1310. lStatus = BAD_VALUE;
  1311. goto Exit;
  1312. }
  1313. break;
  1314. }
  1315. lStatus = initCheck();
  1316. if (lStatus != NO_ERROR) {
  1317. ALOGE("createTrack_l() audio driver not initialized");
  1318. goto Exit;
  1319. }
  1320. { // scope for mLock
  1321. Mutex::Autolock _l(mLock);
  1322. // all tracks in same audio session must share the same routing strategy otherwise
  1323. // conflicts will happen when tracks are moved from one output to another by audio policy
  1324. // manager
  1325. uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
  1326. for (size_t i = 0; i < mTracks.size(); ++i) {
  1327. sp<Track> t = mTracks[i];
  1328. if (t != 0 && t->isExternalTrack()) {
  1329. uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
  1330. if (sessionId == t->sessionId() && strategy != actual) {
  1331. ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
  1332. strategy, actual);
  1333. lStatus = BAD_VALUE;
  1334. goto Exit;
  1335. }
  1336. }
  1337. }
  1338. if (!isTimed) {
  1339. track = new Track(this, client, streamType, sampleRate, format,
  1340. channelMask, frameCount, NULL, sharedBuffer,
  1341. sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
  1342. } else {
  1343. track = TimedTrack::create(this, client, streamType, sampleRate, format,
  1344. channelMask, frameCount, sharedBuffer, sessionId, uid);
  1345. }
  1346. // new Track always returns non-NULL,
  1347. // but TimedTrack::create() is a factory that could fail by returning NULL
  1348. lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
  1349. if (lStatus != NO_ERROR) {
  1350. ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
  1351. // track must be cleared from the caller as the caller has the AF lock
  1352. goto Exit;
  1353. }
  1354. mTracks.add(track);
  1355. sp<EffectChain> chain = getEffectChain_l(sessionId);
  1356. if (chain != 0) {
  1357. ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
  1358. track->setMainBuffer(chain->inBuffer());
  1359. chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
  1360. chain->incTrackCnt();
  1361. }
  1362. if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
  1363. pid_t callingPid = IPCThreadState::self()->getCallingPid();
  1364. // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
  1365. // so ask activity manager to do this on our behalf
  1366. sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
  1367. }
  1368. }
  1369. lStatus = NO_ERROR;
  1370. Exit:
  1371. *status = lStatus;
  1372. return track;
  1373. }
  1374. uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
  1375. {
  1376. return latency;
  1377. }
  1378. uint32_t AudioFlinger::PlaybackThread::latency() const
  1379. {
  1380. Mutex::Autolock _l(mLock);
  1381. return latency_l();
  1382. }
  1383. uint32_t AudioFlinger::PlaybackThread::latency_l() const
  1384. {
  1385. if (initCheck() == NO_ERROR) {
  1386. return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
  1387. } else {
  1388. return 0;
  1389. }
  1390. }
  1391. void AudioFlinger::PlaybackThread::setMasterVolume(float value)
  1392. {
  1393. Mutex::Autolock _l(mLock);
  1394. // Don't apply master volume in SW if our HAL can do it for us.
  1395. if (mOutput && mOutput->audioHwDev &&
  1396. mOutput->audioHwDev->canSetMasterVolume()) {
  1397. mMasterVolume = 1.0;
  1398. } else {
  1399. mMasterVolume = value;
  1400. }
  1401. }
  1402. void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
  1403. {
  1404. Mutex::Autolock _l(mLock);
  1405. // Don't apply master mute in SW if our HAL can do it for us.
  1406. if (mOutput && mOutput->audioHwDev &&
  1407. mOutput->audioHwDev->canSetMasterMute()) {
  1408. mMasterMute = false;
  1409. } else {
  1410. mMasterMute = muted;
  1411. }
  1412. }
  1413. void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
  1414. {
  1415. Mutex::Autolock _l(mLock);
  1416. mStreamTypes[stream].volume = value;
  1417. broadcast_l();
  1418. }
  1419. void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
  1420. {
  1421. Mutex::Autolock _l(mLock);
  1422. mStreamTypes[stream].mute = muted;
  1423. broadcast_l();
  1424. }
  1425. float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
  1426. {
  1427. Mutex::Autolock _l(mLock);
  1428. return mStreamTypes[stream].volume;
  1429. }
  1430. // addTrack_l() must be called with ThreadBase::mLock held
  1431. status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
  1432. {
  1433. status_t status = ALREADY_EXISTS;
  1434. // set retry count for buffer fill
  1435. track->mRetryCount = kMaxTrackStartupRetries;
  1436. if (mActiveTracks.indexOf(track) < 0) {
  1437. // the track is newly added, make sure it fills up all its
  1438. // buffers before playing. This is to ensure the client will
  1439. // effectively get the latency it requested.
  1440. if (track->isExternalTrack()) {
  1441. TrackBase::track_state state = track->mState;
  1442. mLock.unlock();
  1443. status = AudioSystem::startOutput(mId, track->streamType(),
  1444. (audio_session_t)track->sessionId());
  1445. mLock.lock();
  1446. // abort track was stopped/paused while we released the lock
  1447. if (state != track->mState) {
  1448. if (status == NO_ERROR) {
  1449. mLock.unlock();
  1450. AudioSystem::stopOutput(mId, track->streamType(),
  1451. (audio_session_t)track->sessionId());
  1452. mLock.lock();
  1453. }
  1454. return INVALID_OPERATION;
  1455. }
  1456. // abort if start is rejected by audio policy manager
  1457. if (status != NO_ERROR) {
  1458. return PERMISSION_DENIED;
  1459. }
  1460. #ifdef ADD_BATTERY_DATA
  1461. // to track the speaker usage
  1462. addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
  1463. #endif
  1464. }
  1465. track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
  1466. track->mResetDone = false;
  1467. track->mPresentationCompleteFrames = 0;
  1468. mActiveTracks.add(track);
  1469. mWakeLockUids.add(track->uid());
  1470. mActiveTracksGeneration++;
  1471. mLatestActiveTrack = track;
  1472. sp<EffectChain> chain = getEffectChain_l(track->sessionId());
  1473. if (chain != 0) {
  1474. ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
  1475. track->sessionId());
  1476. chain->incActiveTrackCnt();
  1477. }
  1478. status = NO_ERROR;
  1479. }
  1480. onAddNewTrack_l();
  1481. return status;
  1482. }
  1483. bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
  1484. {
  1485. track->terminate();
  1486. // active tracks are removed by threadLoop()
  1487. bool trackActive = (mActiveTracks.indexOf(track) >= 0);
  1488. track->mState = TrackBase::STOPPED;
  1489. if (!trackActive) {
  1490. removeTrack_l(track);
  1491. } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
  1492. track->mState = TrackBase::STOPPING_1;
  1493. }
  1494. return trackActive;
  1495. }
  1496. void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
  1497. {
  1498. track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
  1499. mTracks.remove(track);
  1500. deleteTrackName_l(track->name());
  1501. // redundant as track is about to be destroyed, for dumpsys only
  1502. track->mName = -1;
  1503. if (track->isFastTrack()) {
  1504. int index = track->mFastIndex;
  1505. ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
  1506. ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
  1507. mFastTrackAvailMask |= 1 << index;
  1508. // redundant as track is about to be destroyed, for dumpsys only
  1509. track->mFastIndex = -1;
  1510. }
  1511. sp<EffectChain> chain = getEffectChain_l(track->sessionId());
  1512. if (chain != 0) {
  1513. chain->decTrackCnt();
  1514. }
  1515. }
  1516. void AudioFlinger::PlaybackThread::broadcast_l()
  1517. {
  1518. // Thread could be blocked waiting for async
  1519. // so signal it to handle state changes immediately
  1520. // If threadLoop is currently unlocked a signal of mWaitWorkCV will
  1521. // be lost so we also flag to prevent it blocking on mWaitWorkCV
  1522. mSignalPending = true;
  1523. mWaitWorkCV.broadcast();
  1524. }
  1525. String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
  1526. {
  1527. Mutex::Autolock _l(mLock);
  1528. if (initCheck() != NO_ERROR) {
  1529. return String8();
  1530. }
  1531. char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
  1532. const String8 out_s8(s);
  1533. free(s);
  1534. return out_s8;
  1535. }
  1536. void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
  1537. AudioSystem::OutputDescriptor desc;
  1538. void *param2 = NULL;
  1539. ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
  1540. param);
  1541. switch (event) {
  1542. case AudioSystem::OUTPUT_OPENED:
  1543. case AudioSystem::OUTPUT_CONFIG_CHANGED:
  1544. desc.channelMask = mChannelMask;
  1545. desc.samplingRate = mSampleRate;
  1546. desc.format = mFormat;
  1547. desc.frameCount = mNormalFrameCount; // FIXME see
  1548. // AudioFlinger::frameCount(audio_io_handle_t)
  1549. desc.latency = latency_l();
  1550. param2 = &desc;
  1551. break;
  1552. case AudioSystem::STREAM_CONFIG_CHANGED:
  1553. param2 = &param;
  1554. case AudioSystem::OUTPUT_CLOSED:
  1555. default:
  1556. break;
  1557. }
  1558. mAudioFlinger->audioConfigChanged(event, mId, param2);
  1559. }
  1560. void AudioFlinger::PlaybackThread::writeCallback()
  1561. {
  1562. ALOG_ASSERT(mCallbackThread != 0);
  1563. mCallbackThread->resetWriteBlocked();
  1564. }
  1565. void AudioFlinger::PlaybackThread::drainCallback()
  1566. {
  1567. ALOG_ASSERT(mCallbackThread != 0);
  1568. mCallbackThread->resetDraining();
  1569. }
  1570. void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
  1571. {
  1572. Mutex::Autolock _l(mLock);
  1573. // reject out of sequence requests
  1574. if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
  1575. mWriteAckSequence &= ~1;
  1576. mWaitWorkCV.signal();
  1577. }
  1578. }
  1579. void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
  1580. {
  1581. Mutex::Autolock _l(mLock);
  1582. // reject out of sequence requests
  1583. if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
  1584. mDrainSequence &= ~1;
  1585. mWaitWorkCV.signal();
  1586. }
  1587. }
  1588. // static
  1589. int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
  1590. void *param __unused,
  1591. void *cookie)
  1592. {
  1593. AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
  1594. ALOGV("asyncCallback() event %d", event);
  1595. switch (event) {
  1596. case STREAM_CBK_EVENT_WRITE_READY:
  1597. me->writeCallback();
  1598. break;
  1599. case STREAM_CBK_EVENT_DRAIN_READY:
  1600. me->drainCallback();
  1601. break;
  1602. default:
  1603. ALOGW("asyncCallback() unknown event %d", event);
  1604. break;
  1605. }
  1606. return 0;
  1607. }
  1608. void AudioFlinger::PlaybackThread::readOutputParameters_l()
  1609. {
  1610. // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
  1611. mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
  1612. mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
  1613. if (!audio_is_output_channel(mChannelMask)) {
  1614. LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
  1615. }
  1616. if ((mType == MIXER || mType == DUPLICATING)
  1617. && !isValidPcmSinkChannelMask(mChannelMask)) {
  1618. LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
  1619. mChannelMask);
  1620. }
  1621. mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
  1622. mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
  1623. mFormat = mHALFormat;
  1624. if (!audio_is_valid_format(mFormat)) {
  1625. LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
  1626. }
  1627. if ((mType == MIXER || mType == DUPLICATING)
  1628. && !isValidPcmSinkFormat(mFormat)) {
  1629. LOG_FATAL("HAL format %#x not supported for mixed output",
  1630. mFormat);
  1631. }
  1632. mFrameSize = audio_stream_out_frame_size(mOutput->stream);
  1633. mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
  1634. mFrameCount = mBufferSize / mFrameSize;
  1635. if (mFrameCount & 15) {
  1636. ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
  1637. mFrameCount);
  1638. }
  1639. if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
  1640. (mOutput->stream->set_callback != NULL)) {
  1641. if (mOutput->stream->set_callback(mOutput->stream,
  1642. AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
  1643. mUseAsyncWrite = true;
  1644. mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
  1645. }
  1646. }
  1647. mHwSupportsPause = false;
  1648. if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
  1649. if (mOutput->stream->pause != NULL) {
  1650. if (mOutput->stream->resume != NULL) {
  1651. mHwSupportsPause = true;
  1652. } else {
  1653. ALOGW("direct output implements pause but not resume");
  1654. }
  1655. } else if (mOutput->stream->resume != NULL) {
  1656. ALOGW("direct output implements resume but not pause");
  1657. }
  1658. }
  1659. // Calculate size of normal sink buffer relative to the HAL output buffer size
  1660. double multiplier = 1.0;
  1661. if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
  1662. kUseFastMixer == FastMixer_Dynamic)) {
  1663. size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
  1664. size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
  1665. // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
  1666. minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
  1667. maxNormalFrameCount = maxNormalFrameCount & ~15;
  1668. if (maxNormalFrameCount < minNormalFrameCount) {
  1669. maxNormalFrameCount = minNormalFrameCount;
  1670. }
  1671. multiplier = (double) minNormalFrameCount / (double) mFrameCount;
  1672. if (multiplier <= 1.0) {
  1673. multiplier = 1.0;
  1674. } else if (multiplier <= 2.0) {
  1675. if (2 * mFrameCount <= maxNormalFrameCount) {
  1676. multiplier = 2.0;
  1677. } else {
  1678. multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
  1679. }
  1680. } else {
  1681. // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
  1682. // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
  1683. // track, but we sometimes have to do this to satisfy the maximum frame count
  1684. // constraint)
  1685. // FIXME this rounding up should not be done if no HAL SRC
  1686. uint32_t truncMult = (uint32_t) multiplier;
  1687. if ((truncMult & 1)) {
  1688. if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
  1689. ++truncMult;
  1690. }
  1691. }
  1692. multiplier = (double) truncMult;
  1693. }
  1694. }
  1695. mNormalFrameCount = multiplier * mFrameCount;
  1696. // round up to nearest 16 frames to satisfy AudioMixer
  1697. if (mType == MIXER || mType == DUPLICATING) {
  1698. mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
  1699. }
  1700. ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
  1701. mNormalFrameCount);
  1702. // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
  1703. // Originally this was int16_t[] array, need to remove legacy implications.
  1704. free(mSinkBuffer);
  1705. mSinkBuffer = NULL;
  1706. // For sink buffer size, we use the frame size from the downstream sink to avoid problems
  1707. // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
  1708. const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
  1709. (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
  1710. // We resize the mMixerBuffer according to the requirements of the sink buffer which
  1711. // drives the output.
  1712. free(mMixerBuffer);
  1713. mMixerBuffer = NULL;
  1714. if (mMixerBufferEnabled) {
  1715. mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
  1716. mMixerBufferSize = mNormalFrameCount * mChannelCount
  1717. * audio_bytes_per_sample(mMixerBufferFormat);
  1718. (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
  1719. }
  1720. free(mEffectBuffer);
  1721. mEffectBuffer = NULL;
  1722. if (mEffectBufferEnabled) {
  1723. mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
  1724. mEffectBufferSize = mNormalFrameCount * mChannelCount
  1725. * audio_bytes_per_sample(mEffectBufferFormat);
  1726. (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
  1727. }
  1728. // force reconfiguration of effect chains and engines to take new buffer size and audio
  1729. // parameters into account
  1730. // Note that mLock is not held when readOutputParameters_l() is called from the constructor
  1731. // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
  1732. // matter.
  1733. // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
  1734. Vector< sp<EffectChain> > effectChains = mEffectChains;
  1735. for (size_t i = 0; i < effectChains.size(); i ++) {
  1736. mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
  1737. }
  1738. }
  1739. status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
  1740. {
  1741. if (halFrames == NULL || dspFrames == NULL) {
  1742. return BAD_VALUE;
  1743. }
  1744. Mutex::Autolock _l(mLock);
  1745. if (initCheck() != NO_ERROR) {
  1746. return INVALID_OPERATION;
  1747. }
  1748. size_t framesWritten = mBytesWritten / mFrameSize;
  1749. *halFrames = framesWritten;
  1750. if (isSuspended()) {
  1751. // return an estimation of rendered frames when the output is suspended
  1752. size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
  1753. *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
  1754. return NO_ERROR;
  1755. } else {
  1756. status_t status;
  1757. uint32_t frames;
  1758. status = mOutput->stream->get_render_position(mOutput->stream, &frames);
  1759. *dspFrames = (size_t)frames;
  1760. return status;
  1761. }
  1762. }
  1763. uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
  1764. {
  1765. Mutex::Autolock _l(mLock);
  1766. uint32_t result = 0;
  1767. if (getEffectChain_l(sessionId) != 0) {
  1768. result = EFFECT_SESSION;
  1769. }
  1770. for (size_t i = 0; i < mTracks.size(); ++i) {
  1771. sp<Track> track = mTracks[i];
  1772. if (sessionId == track->sessionId() && !track->isInvalid()) {
  1773. result |= TRACK_SESSION;
  1774. break;
  1775. }
  1776. }
  1777. return result;
  1778. }
  1779. uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
  1780. {
  1781. // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
  1782. // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
  1783. if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
  1784. return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
  1785. }
  1786. for (size_t i = 0; i < mTracks.size(); i++) {
  1787. sp<Track> track = mTracks[i];
  1788. if (sessionId == track->sessionId() && !track->isInvalid()) {
  1789. return AudioSystem::getStrategyForStream(track->streamType());
  1790. }
  1791. }
  1792. return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
  1793. }
  1794. AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
  1795. {
  1796. Mutex::Autolock _l(mLock);
  1797. return mOutput;
  1798. }
  1799. AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
  1800. {
  1801. Mutex::Autolock _l(mLock);
  1802. AudioStreamOut *output = mOutput;
  1803. mOutput = NULL;
  1804. // FIXME FastMixer might also have a raw ptr to mOutputSink;
  1805. // must push a NULL and wait for ack
  1806. mOutputSink.clear();
  1807. mPipeSink.clear();
  1808. mNormalSink.clear();
  1809. return output;
  1810. }
  1811. // this method must always be called either with ThreadBase mLock held or inside the thread loop
  1812. audio_stream_t* AudioFlinger::PlaybackThread::stream() const
  1813. {
  1814. if (mOutput == NULL) {
  1815. return NULL;
  1816. }
  1817. return &mOutput->stream->common;
  1818. }
  1819. uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
  1820. {
  1821. return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
  1822. }
  1823. status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
  1824. {
  1825. if (!isValidSyncEvent(event)) {
  1826. return BAD_VALUE;
  1827. }
  1828. Mutex::Autolock _l(mLock);
  1829. for (size_t i = 0; i < mTracks.size(); ++i) {
  1830. sp<Track> track = mTracks[i];
  1831. if (event->triggerSession() == track->sessionId()) {
  1832. (void) track->setSyncEvent(event);
  1833. return NO_ERROR;
  1834. }
  1835. }
  1836. return NAME_NOT_FOUND;
  1837. }
  1838. bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
  1839. {
  1840. return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
  1841. }
  1842. void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
  1843. const Vector< sp<Track> >& tracksToRemove)
  1844. {
  1845. size_t count = tracksToRemove.size();
  1846. if (count > 0) {
  1847. for (size_t i = 0 ; i < count ; i++) {
  1848. const sp<Track>& track = tracksToRemove.itemAt(i);
  1849. if (track->isExternalTrack()) {
  1850. AudioSystem::stopOutput(mId, track->streamType(),
  1851. (audio_session_t)track->sessionId());
  1852. #ifdef ADD_BATTERY_DATA
  1853. // to track the speaker usage
  1854. addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
  1855. #endif
  1856. if (track->isTerminated()) {
  1857. AudioSystem::releaseOutput(mId, track->streamType(),
  1858. (audio_session_t)track->sessionId());
  1859. }
  1860. }
  1861. }
  1862. }
  1863. }
  1864. void AudioFlinger::PlaybackThread::checkSilentMode_l()
  1865. {
  1866. if (!mMasterMute) {
  1867. char value[PROPERTY_VALUE_MAX];
  1868. if (property_get("ro.audio.silent", value, "0") > 0) {
  1869. char *endptr;
  1870. unsigned long ul = strtoul(value, &endptr, 0);
  1871. if (*endptr == '\0' && ul != 0) {
  1872. ALOGD("Silence is golden");
  1873. // The setprop command will not allow a property to be changed after
  1874. // the first time it is set, so we don't have to worry about un-muting.
  1875. setMasterMute_l(true);
  1876. }
  1877. }
  1878. }
  1879. }
  1880. // shared by MIXER and DIRECT, overridden by DUPLICATING
  1881. ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
  1882. {
  1883. // FIXME rewrite to reduce number of system calls
  1884. mLastWriteTime = systemTime();
  1885. mInWrite = true;
  1886. ssize_t bytesWritten;
  1887. const size_t offset = mCurrentWriteLength - mBytesRemaining;
  1888. // If an NBAIO sink is present, use it to write the normal mixer's submix
  1889. if (mNormalSink != 0) {
  1890. const size_t count = mBytesRemaining / mFrameSize;
  1891. ATRACE_BEGIN("write");
  1892. // update the setpoint when AudioFlinger::mScreenState changes
  1893. uint32_t screenState = AudioFlinger::mScreenState;
  1894. if (screenState != mScreenState) {
  1895. mScreenState = screenState;
  1896. MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
  1897. if (pipe != NULL) {
  1898. pipe->setAvgFrames((mScreenState & 1) ?
  1899. (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
  1900. }
  1901. }
  1902. ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
  1903. ATRACE_END();
  1904. if (framesWritten > 0) {
  1905. bytesWritten = framesWritten * mFrameSize;
  1906. } else {
  1907. bytesWritten = framesWritten;
  1908. }
  1909. status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
  1910. if (status == NO_ERROR) {
  1911. size_t totalFramesWritten = mNormalSink->framesWritten();
  1912. if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
  1913. mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
  1914. // mLatchD.mFramesReleased is set immediately before D is clocked into Q
  1915. mLatchDValid = true;
  1916. }
  1917. }
  1918. // otherwise use the HAL / AudioStreamOut directly
  1919. } else {
  1920. // Direct output and offload threads
  1921. if (mUseAsyncWrite) {
  1922. ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
  1923. mWriteAckSequence += 2;
  1924. mWriteAckSequence |= 1;
  1925. ALOG_ASSERT(mCallbackThread != 0);
  1926. mCallbackThread->setWriteBlocked(mWriteAckSequence);
  1927. }
  1928. // FIXME We should have an implementation of timestamps for direct output threads.
  1929. // They are used e.g for multichannel PCM playback over HDMI.
  1930. bytesWritten = mOutput->stream->write(mOutput->stream,
  1931. (char *)mSinkBuffer + offset, mBytesRemaining);
  1932. if (mUseAsyncWrite &&
  1933. ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
  1934. // do not wait for async callback in case of error of full write
  1935. mWriteAckSequence &= ~1;
  1936. ALOG_ASSERT(mCallbackThread != 0);
  1937. mCallbackThread->setWriteBlocked(mWriteAckSequence);
  1938. }
  1939. }
  1940. mNumWrites++;
  1941. mInWrite = false;
  1942. mStandby = false;
  1943. return bytesWritten;
  1944. }
  1945. void AudioFlinger::PlaybackThread::threadLoop_drain()
  1946. {
  1947. if (mOutput->stream->drain) {
  1948. ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
  1949. if (mUseAsyncWrite) {
  1950. ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
  1951. mDrainSequence |= 1;
  1952. ALOG_ASSERT(mCallbackThread != 0);
  1953. mCallbackThread->setDraining(mDrainSequence);
  1954. }
  1955. mOutput->stream->drain(mOutput->stream,
  1956. (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
  1957. : AUDIO_DRAIN_ALL);
  1958. }
  1959. }
  1960. void AudioFlinger::PlaybackThread::threadLoop_exit()
  1961. {
  1962. {
  1963. Mutex::Autolock _l(mLock);
  1964. for (size_t i = 0; i < mTracks.size(); i++) {
  1965. sp<Track> track = mTracks[i];
  1966. track->invalidate();
  1967. }
  1968. }
  1969. }
  1970. /*
  1971. The derived values that are cached:
  1972. - mSinkBufferSize from frame count * frame size
  1973. - activeSleepTime from activeSleepTimeUs()
  1974. - idleSleepTime from idleSleepTimeUs()
  1975. - standbyDelay from mActiveSleepTimeUs (DIRECT only)
  1976. - maxPeriod from frame count and sample rate (MIXER only)
  1977. The parameters that affect these derived values are:
  1978. - frame count
  1979. - frame size
  1980. - sample rate
  1981. - device type: A2DP or not
  1982. - device latency
  1983. - format: PCM or not
  1984. - active sleep time
  1985. - idle sleep time
  1986. */
  1987. void AudioFlinger::PlaybackThread::cacheParameters_l()
  1988. {
  1989. mSinkBufferSize = mNormalFrameCount * mFrameSize;
  1990. activeSleepTime = activeSleepTimeUs();
  1991. idleSleepTime = idleSleepTimeUs();
  1992. }
  1993. void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
  1994. {
  1995. ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
  1996. this, streamType, mTracks.size());
  1997. Mutex::Autolock _l(mLock);
  1998. size_t size = mTracks.size();
  1999. for (size_t i = 0; i < size; i++) {
  2000. sp<Track> t = mTracks[i];
  2001. if (t->streamType() == streamType) {
  2002. t->invalidate();
  2003. }
  2004. }
  2005. }
  2006. status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
  2007. {
  2008. int session = chain->sessionId();
  2009. int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
  2010. ? mEffectBuffer : mSinkBuffer);
  2011. bool ownsBuffer = false;
  2012. ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
  2013. if (session > 0) {
  2014. // Only one effect chain can be present in direct output thread and it uses
  2015. // the sink buffer as input
  2016. if (mType != DIRECT) {
  2017. size_t numSamples = mNormalFrameCount * mChannelCount;
  2018. buffer = new int16_t[numSamples];
  2019. memset(buffer, 0, numSamples * sizeof(int16_t));
  2020. ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
  2021. ownsBuffer = true;
  2022. }
  2023. // Attach all tracks with same session ID to this chain.
  2024. for (size_t i = 0; i < mTracks.size(); ++i) {
  2025. sp<Track> track = mTracks[i];
  2026. if (session == track->sessionId()) {
  2027. ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
  2028. buffer);
  2029. track->setMainBuffer(buffer);
  2030. chain->incTrackCnt();
  2031. }
  2032. }
  2033. // indicate all active tracks in the chain
  2034. for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
  2035. sp<Track> track = mActiveTracks[i].promote();
  2036. if (track == 0) {
  2037. continue;
  2038. }
  2039. if (session == track->sessionId()) {
  2040. ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
  2041. chain->incActiveTrackCnt();
  2042. }
  2043. }
  2044. }
  2045. chain->setThread(this);
  2046. chain->setInBuffer(buffer, ownsBuffer);
  2047. chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
  2048. ? mEffectBuffer : mSinkBuffer));
  2049. // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
  2050. // chains list in order to be processed last as it contains output stage effects
  2051. // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
  2052. // session AUDIO_SESSION_OUTPUT_STAGE to be processed
  2053. // after track specific effects and before output stage
  2054. // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
  2055. // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
  2056. // Effect chain for other sessions are inserted at beginning of effect
  2057. // chains list to be processed before output mix effects. Relative order between other
  2058. // sessions is not important
  2059. size_t size = mEffectChains.size();
  2060. size_t i = 0;
  2061. for (i = 0; i < size; i++) {
  2062. if (mEffectChains[i]->sessionId() < session) {
  2063. break;
  2064. }
  2065. }
  2066. mEffectChains.insertAt(chain, i);
  2067. checkSuspendOnAddEffectChain_l(chain);
  2068. return NO_ERROR;
  2069. }
  2070. size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
  2071. {
  2072. int session = chain->sessionId();
  2073. ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
  2074. for (size_t i = 0; i < mEffectChains.size(); i++) {
  2075. if (chain == mEffectChains[i]) {
  2076. mEffectChains.removeAt(i);
  2077. // detach all active tracks from the chain
  2078. for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
  2079. sp<Track> track = mActiveTracks[i].promote();
  2080. if (track == 0) {
  2081. continue;
  2082. }
  2083. if (session == track->sessionId()) {
  2084. ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
  2085. chain.get(), session);
  2086. chain->decActiveTrackCnt();
  2087. }
  2088. }
  2089. // detach all tracks with same session ID from this chain
  2090. for (size_t i = 0; i < mTracks.size(); ++i) {
  2091. sp<Track> track = mTracks[i];
  2092. if (session == track->sessionId()) {
  2093. track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
  2094. chain->decTrackCnt();
  2095. }
  2096. }
  2097. break;
  2098. }
  2099. }
  2100. return mEffectChains.size();
  2101. }
  2102. status_t AudioFlinger::PlaybackThread::attachAuxEffect(
  2103. const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
  2104. {
  2105. Mutex::Autolock _l(mLock);
  2106. return attachAuxEffect_l(track, EffectId);
  2107. }
  2108. status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
  2109. const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
  2110. {
  2111. status_t status = NO_ERROR;
  2112. if (EffectId == 0) {
  2113. track->setAuxBuffer(0, NULL);
  2114. } else {
  2115. // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
  2116. sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
  2117. if (effect != 0) {
  2118. if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
  2119. track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
  2120. } else {
  2121. status = INVALID_OPERATION;
  2122. }
  2123. } else {
  2124. status = BAD_VALUE;
  2125. }
  2126. }
  2127. return status;
  2128. }
  2129. void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
  2130. {
  2131. for (size_t i = 0; i < mTracks.size(); ++i) {
  2132. sp<Track> track = mTracks[i];
  2133. if (track->auxEffectId() == effectId) {
  2134. attachAuxEffect_l(track, 0);
  2135. }
  2136. }
  2137. }
  2138. bool AudioFlinger::PlaybackThread::threadLoop()
  2139. {
  2140. Vector< sp<Track> > tracksToRemove;
  2141. standbyTime = systemTime();
  2142. // MIXER
  2143. nsecs_t lastWarning = 0;
  2144. // DUPLICATING
  2145. // FIXME could this be made local to while loop?
  2146. writeFrames = 0;
  2147. int lastGeneration = 0;
  2148. cacheParameters_l();
  2149. sleepTime = idleSleepTime;
  2150. if (mType == MIXER) {
  2151. sleepTimeShift = 0;
  2152. }
  2153. CpuStats cpuStats;
  2154. const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
  2155. acquireWakeLock();
  2156. // mNBLogWriter->log can only be called while thread mutex mLock is held.
  2157. // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
  2158. // and then that string will be logged at the next convenient opportunity.
  2159. const char *logString = NULL;
  2160. checkSilentMode_l();
  2161. while (!exitPending())
  2162. {
  2163. cpuStats.sample(myName);
  2164. Vector< sp<EffectChain> > effectChains;
  2165. { // scope for mLock
  2166. Mutex::Autolock _l(mLock);
  2167. processConfigEvents_l();
  2168. if (logString != NULL) {
  2169. mNBLogWriter->logTimestamp();
  2170. mNBLogWriter->log(logString);
  2171. logString = NULL;
  2172. }
  2173. // Gather the framesReleased counters for all active tracks,
  2174. // and latch them atomically with the timestamp.
  2175. // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
  2176. mLatchD.mFramesReleased.clear();
  2177. size_t size = mActiveTracks.size();
  2178. for (size_t i = 0; i < size; i++) {
  2179. sp<Track> t = mActiveTracks[i].promote();
  2180. if (t != 0) {
  2181. mLatchD.mFramesReleased.add(t.get(),
  2182. t->mAudioTrackServerProxy->framesReleased());
  2183. }
  2184. }
  2185. if (mLatchDValid) {
  2186. mLatchQ = mLatchD;
  2187. mLatchDValid = false;
  2188. mLatchQValid = true;
  2189. }
  2190. saveOutputTracks();
  2191. if (mSignalPending) {
  2192. // A signal was raised while we were unlocked
  2193. mSignalPending = false;
  2194. } else if (waitingAsyncCallback_l()) {
  2195. if (exitPending()) {
  2196. break;
  2197. }
  2198. releaseWakeLock_l();
  2199. mWakeLockUids.clear();
  2200. mActiveTracksGeneration++;
  2201. ALOGV("wait async completion");
  2202. mWaitWorkCV.wait(mLock);
  2203. ALOGV("async completion/wake");
  2204. acquireWakeLock_l();
  2205. standbyTime = systemTime() + standbyDelay;
  2206. sleepTime = 0;
  2207. continue;
  2208. }
  2209. if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
  2210. isSuspended()) {
  2211. // put audio hardware into standby after short delay
  2212. if (shouldStandby_l()) {
  2213. threadLoop_standby();
  2214. mStandby = true;
  2215. }
  2216. if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
  2217. // we're about to wait, flush the binder command buffer
  2218. IPCThreadState::self()->flushCommands();
  2219. clearOutputTracks();
  2220. if (exitPending()) {
  2221. break;
  2222. }
  2223. releaseWakeLock_l();
  2224. mWakeLockUids.clear();
  2225. mActiveTracksGeneration++;
  2226. // wait until we have something to do...
  2227. ALOGV("%s going to sleep", myName.string());
  2228. mWaitWorkCV.wait(mLock);
  2229. ALOGV("%s waking up", myName.string());
  2230. acquireWakeLock_l();
  2231. mMixerStatus = MIXER_IDLE;
  2232. mMixerStatusIgnoringFastTracks = MIXER_IDLE;
  2233. mBytesWritten = 0;
  2234. mBytesRemaining = 0;
  2235. checkSilentMode_l();
  2236. standbyTime = systemTime() + standbyDelay;
  2237. sleepTime = idleSleepTime;
  2238. if (mType == MIXER) {
  2239. sleepTimeShift = 0;
  2240. }
  2241. continue;
  2242. }
  2243. }
  2244. // mMixerStatusIgnoringFastTracks is also updated internally
  2245. mMixerStatus = prepareTracks_l(&tracksToRemove);
  2246. // compare with previously applied list
  2247. if (lastGeneration != mActiveTracksGeneration) {
  2248. // update wakelock
  2249. updateWakeLockUids_l(mWakeLockUids);
  2250. lastGeneration = mActiveTracksGeneration;
  2251. }
  2252. // prevent any changes in effect chain list and in each effect chain
  2253. // during mixing and effect process as the audio buffers could be deleted
  2254. // or modified if an effect is created or deleted
  2255. lockEffectChains_l(effectChains);
  2256. } // mLock scope ends
  2257. if (mBytesRemaining == 0) {
  2258. mCurrentWriteLength = 0;
  2259. if (mMixerStatus == MIXER_TRACKS_READY) {
  2260. // threadLoop_mix() sets mCurrentWriteLength
  2261. threadLoop_mix();
  2262. } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
  2263. && (mMixerStatus != MIXER_DRAIN_ALL)) {
  2264. // threadLoop_sleepTime sets sleepTime to 0 if data
  2265. // must be written to HAL
  2266. threadLoop_sleepTime();
  2267. if (sleepTime == 0) {
  2268. mCurrentWriteLength = mSinkBufferSize;
  2269. }
  2270. }
  2271. // Either threadLoop_mix() or threadLoop_sleepTime() should have set
  2272. // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
  2273. // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
  2274. // or mSinkBuffer (if there are no effects).
  2275. //
  2276. // This is done pre-effects computation; if effects change to
  2277. // support higher precision, this needs to move.
  2278. //
  2279. // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
  2280. // TODO use sleepTime == 0 as an additional condition.
  2281. if (mMixerBufferValid) {
  2282. void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
  2283. audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
  2284. memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
  2285. mNormalFrameCount * mChannelCount);
  2286. }
  2287. mBytesRemaining = mCurrentWriteLength;
  2288. if (isSuspended()) {
  2289. sleepTime = suspendSleepTimeUs();
  2290. // simulate write to HAL when suspended
  2291. mBytesWritten += mSinkBufferSize;
  2292. mBytesRemaining = 0;
  2293. }
  2294. // only process effects if we're going to write
  2295. if (sleepTime == 0 && mType != OFFLOAD) {
  2296. for (size_t i = 0; i < effectChains.size(); i ++) {
  2297. effectChains[i]->process_l();
  2298. }
  2299. }
  2300. }
  2301. // Process effect chains for offloaded thread even if no audio
  2302. // was read from audio track: process only updates effect state
  2303. // and thus does have to be synchronized with audio writes but may have
  2304. // to be called while waiting for async write callback
  2305. if (mType == OFFLOAD) {
  2306. for (size_t i = 0; i < effectChains.size(); i ++) {
  2307. effectChains[i]->process_l();
  2308. }
  2309. }
  2310. // Only if the Effects buffer is enabled and there is data in the
  2311. // Effects buffer (buffer valid), we need to
  2312. // copy into the sink buffer.
  2313. // TODO use sleepTime == 0 as an additional condition.
  2314. if (mEffectBufferValid) {
  2315. //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
  2316. memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
  2317. mNormalFrameCount * mChannelCount);
  2318. }
  2319. // enable changes in effect chain
  2320. unlockEffectChains(effectChains);
  2321. if (!waitingAsyncCallback()) {
  2322. // sleepTime == 0 means we must write to audio hardware
  2323. if (sleepTime == 0) {
  2324. if (mBytesRemaining) {
  2325. ssize_t ret = threadLoop_write();
  2326. if (ret < 0) {
  2327. mBytesRemaining = 0;
  2328. } else {
  2329. mBytesWritten += ret;
  2330. mBytesRemaining -= ret;
  2331. }
  2332. } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
  2333. (mMixerStatus == MIXER_DRAIN_ALL)) {
  2334. threadLoop_drain();
  2335. }
  2336. if (mType == MIXER) {
  2337. // write blocked detection
  2338. nsecs_t now = systemTime();
  2339. nsecs_t delta = now - mLastWriteTime;
  2340. if (!mStandby && delta > maxPeriod) {
  2341. mNumDelayedWrites++;
  2342. if ((now - lastWarning) > kWarningThrottleNs) {
  2343. ATRACE_NAME("underrun");
  2344. ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
  2345. ns2ms(delta), mNumDelayedWrites, this);
  2346. lastWarning = now;
  2347. }
  2348. }
  2349. }
  2350. } else {
  2351. usleep(sleepTime);
  2352. }
  2353. }
  2354. // Finally let go of removed track(s), without the lock held
  2355. // since we can't guarantee the destructors won't acquire that
  2356. // same lock. This will also mutate and push a new fast mixer state.
  2357. threadLoop_removeTracks(tracksToRemove);
  2358. tracksToRemove.clear();
  2359. // FIXME I don't understand the need for this here;
  2360. // it was in the original code but maybe the
  2361. // assignment in saveOutputTracks() makes this unnecessary?
  2362. clearOutputTracks();
  2363. // Effect chains will be actually deleted here if they were removed from
  2364. // mEffectChains list during mixing or effects processing
  2365. effectChains.clear();
  2366. // FIXME Note that the above .clear() is no longer necessary since effectChains
  2367. // is now local to this block, but will keep it for now (at least until merge done).
  2368. }
  2369. threadLoop_exit();
  2370. if (!mStandby) {
  2371. threadLoop_standby();
  2372. mStandby = true;
  2373. }
  2374. releaseWakeLock();
  2375. mWakeLockUids.clear();
  2376. mActiveTracksGeneration++;
  2377. ALOGV("Thread %p type %d exiting", this, mType);
  2378. return false;
  2379. }
  2380. // removeTracks_l() must be called with ThreadBase::mLock held
  2381. void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
  2382. {
  2383. size_t count = tracksToRemove.size();
  2384. if (count > 0) {
  2385. for (size_t i=0 ; i<count ; i++) {
  2386. const sp<Track>& track = tracksToRemove.itemAt(i);
  2387. mActiveTracks.remove(track);
  2388. mWakeLockUids.remove(track->uid());
  2389. mActiveTracksGeneration++;
  2390. ALOGV("removeTracks_l removing track on session %d", track->sessionId());
  2391. sp<EffectChain> chain = getEffectChain_l(track->sessionId());
  2392. if (chain != 0) {
  2393. ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
  2394. track->sessionId());
  2395. chain->decActiveTrackCnt();
  2396. }
  2397. if (track->isTerminated()) {
  2398. removeTrack_l(track);
  2399. }
  2400. }
  2401. }
  2402. }
  2403. status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
  2404. {
  2405. if (mNormalSink != 0) {
  2406. return mNormalSink->getTimestamp(timestamp);
  2407. }
  2408. if ((mType == OFFLOAD || mType == DIRECT)
  2409. && mOutput != NULL && mOutput->stream->get_presentation_position) {
  2410. uint64_t position64;
  2411. int ret = mOutput->stream->get_presentation_position(
  2412. mOutput->stream, &position64, &timestamp.mTime);
  2413. if (ret == 0) {
  2414. timestamp.mPosition = (uint32_t)position64;
  2415. return NO_ERROR;
  2416. }
  2417. }
  2418. return INVALID_OPERATION;
  2419. }
  2420. status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
  2421. audio_patch_handle_t *handle)
  2422. {
  2423. status_t status = NO_ERROR;
  2424. if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
  2425. // store new device and send to effects
  2426. audio_devices_t type = AUDIO_DEVICE_NONE;
  2427. for (unsigned int i = 0; i < patch->num_sinks; i++) {
  2428. type |= patch->sinks[i].ext.device.type;
  2429. }
  2430. mOutDevice = type;
  2431. for (size_t i = 0; i < mEffectChains.size(); i++) {
  2432. mEffectChains[i]->setDevice_l(mOutDevice);
  2433. }
  2434. audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
  2435. status = hwDevice->create_audio_patch(hwDevice,
  2436. patch->num_sources,
  2437. patch->sources,
  2438. patch->num_sinks,
  2439. patch->sinks,
  2440. handle);
  2441. } else {
  2442. ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
  2443. }
  2444. return status;
  2445. }
  2446. status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
  2447. {
  2448. status_t status = NO_ERROR;
  2449. if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
  2450. audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
  2451. status = hwDevice->release_audio_patch(hwDevice, handle);
  2452. } else {
  2453. ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
  2454. }
  2455. return status;
  2456. }
  2457. void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
  2458. {
  2459. Mutex::Autolock _l(mLock);
  2460. mTracks.add(track);
  2461. }
  2462. void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
  2463. {
  2464. Mutex::Autolock _l(mLock);
  2465. destroyTrack_l(track);
  2466. }
  2467. void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
  2468. {
  2469. ThreadBase::getAudioPortConfig(config);
  2470. config->role = AUDIO_PORT_ROLE_SOURCE;
  2471. config->ext.mix.hw_module = mOutput->audioHwDev->handle();
  2472. config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
  2473. }
  2474. // ----------------------------------------------------------------------------
  2475. AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
  2476. audio_io_handle_t id, audio_devices_t device, type_t type)
  2477. : PlaybackThread(audioFlinger, output, id, device, type),
  2478. // mAudioMixer below
  2479. // mFastMixer below
  2480. mFastMixerFutex(0)
  2481. // mOutputSink below
  2482. // mPipeSink below
  2483. // mNormalSink below
  2484. {
  2485. ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
  2486. ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
  2487. "mFrameCount=%d, mNormalFrameCount=%d",
  2488. mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
  2489. mNormalFrameCount);
  2490. mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
  2491. // create an NBAIO sink for the HAL output stream, and negotiate
  2492. mOutputSink = new AudioStreamOutSink(output->stream);
  2493. size_t numCounterOffers = 0;
  2494. const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
  2495. ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
  2496. ALOG_ASSERT(index == 0);
  2497. // initialize fast mixer depending on configuration
  2498. bool initFastMixer;
  2499. switch (kUseFastMixer) {
  2500. case FastMixer_Never:
  2501. initFastMixer = false;
  2502. break;
  2503. case FastMixer_Always:
  2504. initFastMixer = true;
  2505. break;
  2506. case FastMixer_Static:
  2507. case FastMixer_Dynamic:
  2508. initFastMixer = mFrameCount < mNormalFrameCount;
  2509. break;
  2510. }
  2511. if (initFastMixer) {
  2512. audio_format_t fastMixerFormat;
  2513. if (mMixerBufferEnabled && mEffectBufferEnabled) {
  2514. fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
  2515. } else {
  2516. fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
  2517. }
  2518. if (mFormat != fastMixerFormat) {
  2519. // change our Sink format to accept our intermediate precision
  2520. mFormat = fastMixerFormat;
  2521. free(mSinkBuffer);
  2522. mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
  2523. const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
  2524. (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
  2525. }
  2526. // create a MonoPipe to connect our submix to FastMixer
  2527. NBAIO_Format format = mOutputSink->format();
  2528. NBAIO_Format origformat = format;
  2529. // adjust format to match that of the Fast Mixer
  2530. format.mFormat = fastMixerFormat;
  2531. format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
  2532. // This pipe depth compensates for scheduling latency of the normal mixer thread.
  2533. // When it wakes up after a maximum latency, it runs a few cycles quickly before
  2534. // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
  2535. MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
  2536. const NBAIO_Format offers[1] = {format};
  2537. size_t numCounterOffers = 0;
  2538. ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
  2539. ALOG_ASSERT(index == 0);
  2540. monoPipe->setAvgFrames((mScreenState & 1) ?
  2541. (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
  2542. mPipeSink = monoPipe;
  2543. #ifdef TEE_SINK
  2544. if (mTeeSinkOutputEnabled) {
  2545. // create a Pipe to archive a copy of FastMixer's output for dumpsys
  2546. Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
  2547. const NBAIO_Format offers2[1] = {origformat};
  2548. numCounterOffers = 0;
  2549. index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
  2550. ALOG_ASSERT(index == 0);
  2551. mTeeSink = teeSink;
  2552. PipeReader *teeSource = new PipeReader(*teeSink);
  2553. numCounterOffers = 0;
  2554. index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
  2555. ALOG_ASSERT(index == 0);
  2556. mTeeSource = teeSource;
  2557. }
  2558. #endif
  2559. // create fast mixer and configure it initially with just one fast track for our submix
  2560. mFastMixer = new FastMixer();
  2561. FastMixerStateQueue *sq = mFastMixer->sq();
  2562. #ifdef STATE_QUEUE_DUMP
  2563. sq->setObserverDump(&mStateQueueObserverDump);
  2564. sq->setMutatorDump(&mStateQueueMutatorDump);
  2565. #endif
  2566. FastMixerState *state = sq->begin();
  2567. FastTrack *fastTrack = &state->mFastTracks[0];
  2568. // wrap the source side of the MonoPipe to make it an AudioBufferProvider
  2569. fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
  2570. fastTrack->mVolumeProvider = NULL;
  2571. fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
  2572. fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
  2573. fastTrack->mGeneration++;
  2574. state->mFastTracksGen++;
  2575. state->mTrackMask = 1;
  2576. // fast mixer will use the HAL output sink
  2577. state->mOutputSink = mOutputSink.get();
  2578. state->mOutputSinkGen++;
  2579. state->mFrameCount = mFrameCount;
  2580. state->mCommand = FastMixerState::COLD_IDLE;
  2581. // already done in constructor initialization list
  2582. //mFastMixerFutex = 0;
  2583. state->mColdFutexAddr = &mFastMixerFutex;
  2584. state->mColdGen++;
  2585. state->mDumpState = &mFastMixerDumpState;
  2586. #ifdef TEE_SINK
  2587. state->mTeeSink = mTeeSink.get();
  2588. #endif
  2589. mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
  2590. state->mNBLogWriter = mFastMixerNBLogWriter.get();
  2591. sq->end();
  2592. sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
  2593. // start the fast mixer
  2594. mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
  2595. pid_t tid = mFastMixer->getTid();
  2596. int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
  2597. if (err != 0) {
  2598. ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
  2599. kPriorityFastMixer, getpid_cached, tid, err);
  2600. }
  2601. #ifdef AUDIO_WATCHDOG
  2602. // create and start the watchdog
  2603. mAudioWatchdog = new AudioWatchdog();
  2604. mAudioWatchdog->setDump(&mAudioWatchdogDump);
  2605. mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
  2606. tid = mAudioWatchdog->getTid();
  2607. err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
  2608. if (err != 0) {
  2609. ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
  2610. kPriorityFastMixer, getpid_cached, tid, err);
  2611. }
  2612. #endif
  2613. }
  2614. switch (kUseFastMixer) {
  2615. case FastMixer_Never:
  2616. case FastMixer_Dynamic:
  2617. mNormalSink = mOutputSink;
  2618. break;
  2619. case FastMixer_Always:
  2620. mNormalSink = mPipeSink;
  2621. break;
  2622. case FastMixer_Static:
  2623. mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
  2624. break;
  2625. }
  2626. }
  2627. AudioFlinger::MixerThread::~MixerThread()
  2628. {
  2629. if (mFastMixer != 0) {
  2630. FastMixerStateQueue *sq = mFastMixer->sq();
  2631. FastMixerState *state = sq->begin();
  2632. if (state->mCommand == FastMixerState::COLD_IDLE) {
  2633. int32_t old = android_atomic_inc(&mFastMixerFutex);
  2634. if (old == -1) {
  2635. (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
  2636. }
  2637. }
  2638. state->mCommand = FastMixerState::EXIT;
  2639. sq->end();
  2640. sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
  2641. mFastMixer->join();
  2642. // Though the fast mixer thread has exited, it's state queue is still valid.
  2643. // We'll use that extract the final state which contains one remaining fast track
  2644. // corresponding to our sub-mix.
  2645. state = sq->begin();
  2646. ALOG_ASSERT(state->mTrackMask == 1);
  2647. FastTrack *fastTrack = &state->mFastTracks[0];
  2648. ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
  2649. delete fastTrack->mBufferProvider;
  2650. sq->end(false /*didModify*/);
  2651. mFastMixer.clear();
  2652. #ifdef AUDIO_WATCHDOG
  2653. if (mAudioWatchdog != 0) {
  2654. mAudioWatchdog->requestExit();
  2655. mAudioWatchdog->requestExitAndWait();
  2656. mAudioWatchdog.clear();
  2657. }
  2658. #endif
  2659. }
  2660. mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
  2661. delete mAudioMixer;
  2662. }
  2663. uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
  2664. {
  2665. if (mFastMixer != 0) {
  2666. MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
  2667. latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
  2668. }
  2669. return latency;
  2670. }
  2671. void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
  2672. {
  2673. PlaybackThread::threadLoop_removeTracks(tracksToRemove);
  2674. }
  2675. ssize_t AudioFlinger::MixerThread::threadLoop_write()
  2676. {
  2677. // FIXME we should only do one push per cycle; confirm this is true
  2678. // Start the fast mixer if it's not already running
  2679. if (mFastMixer != 0) {
  2680. FastMixerStateQueue *sq = mFastMixer->sq();
  2681. FastMixerState *state = sq->begin();
  2682. if (state->mCommand != FastMixerState::MIX_WRITE &&
  2683. (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
  2684. if (state->mCommand == FastMixerState::COLD_IDLE) {
  2685. int32_t old = android_atomic_inc(&mFastMixerFutex);
  2686. if (old == -1) {
  2687. (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
  2688. }
  2689. #ifdef AUDIO_WATCHDOG
  2690. if (mAudioWatchdog != 0) {
  2691. mAudioWatchdog->resume();
  2692. }
  2693. #endif
  2694. }
  2695. state->mCommand = FastMixerState::MIX_WRITE;
  2696. mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
  2697. FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
  2698. sq->end();
  2699. sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
  2700. if (kUseFastMixer == FastMixer_Dynamic) {
  2701. mNormalSink = mPipeSink;
  2702. }
  2703. } else {
  2704. sq->end(false /*didModify*/);
  2705. }
  2706. }
  2707. return PlaybackThread::threadLoop_write();
  2708. }
  2709. void AudioFlinger::MixerThread::threadLoop_standby()
  2710. {
  2711. // Idle the fast mixer if it's currently running
  2712. if (mFastMixer != 0) {
  2713. FastMixerStateQueue *sq = mFastMixer->sq();
  2714. FastMixerState *state = sq->begin();
  2715. if (!(state->mCommand & FastMixerState::IDLE)) {
  2716. state->mCommand = FastMixerState::COLD_IDLE;
  2717. state->mColdFutexAddr = &mFastMixerFutex;
  2718. state->mColdGen++;
  2719. mFastMixerFutex = 0;
  2720. sq->end();
  2721. // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
  2722. sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
  2723. if (kUseFastMixer == FastMixer_Dynamic) {
  2724. mNormalSink = mOutputSink;
  2725. }
  2726. #ifdef AUDIO_WATCHDOG
  2727. if (mAudioWatchdog != 0) {
  2728. mAudioWatchdog->pause();
  2729. }
  2730. #endif
  2731. } else {
  2732. sq->end(false /*didModify*/);
  2733. }
  2734. }
  2735. PlaybackThread::threadLoop_standby();
  2736. }
  2737. bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
  2738. {
  2739. return false;
  2740. }
  2741. bool AudioFlinger::PlaybackThread::shouldStandby_l()
  2742. {
  2743. return !mStandby;
  2744. }
  2745. bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
  2746. {
  2747. Mutex::Autolock _l(mLock);
  2748. return waitingAsyncCallback_l();
  2749. }
  2750. // shared by MIXER and DIRECT, overridden by DUPLICATING
  2751. void AudioFlinger::PlaybackThread::threadLoop_standby()
  2752. {
  2753. ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
  2754. mOutput->stream->common.standby(&mOutput->stream->common);
  2755. if (mUseAsyncWrite != 0) {
  2756. // discard any pending drain or write ack by incrementing sequence
  2757. mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
  2758. mDrainSequence = (mDrainSequence + 2) & ~1;
  2759. ALOG_ASSERT(mCallbackThread != 0);
  2760. mCallbackThread->setWriteBlocked(mWriteAckSequence);
  2761. mCallbackThread->setDraining(mDrainSequence);
  2762. }
  2763. mHwPaused = false;
  2764. }
  2765. void AudioFlinger::PlaybackThread::onAddNewTrack_l()
  2766. {
  2767. ALOGV("signal playback thread");
  2768. broadcast_l();
  2769. }
  2770. void AudioFlinger::MixerThread::threadLoop_mix()
  2771. {
  2772. // obtain the presentation timestamp of the next output buffer
  2773. int64_t pts;
  2774. status_t status = INVALID_OPERATION;
  2775. if (mNormalSink != 0) {
  2776. status = mNormalSink->getNextWriteTimestamp(&pts);
  2777. } else {
  2778. status = mOutputSink->getNextWriteTimestamp(&pts);
  2779. }
  2780. if (status != NO_ERROR) {
  2781. pts = AudioBufferProvider::kInvalidPTS;
  2782. }
  2783. // mix buffers...
  2784. mAudioMixer->process(pts);
  2785. mCurrentWriteLength = mSinkBufferSize;
  2786. // increase sleep time progressively when application underrun condition clears.
  2787. // Only increase sleep time if the mixer is ready for two consecutive times to avoid
  2788. // that a steady state of alternating ready/not ready conditions keeps the sleep time
  2789. // such that we would underrun the audio HAL.
  2790. if ((sleepTime == 0) && (sleepTimeShift > 0)) {
  2791. sleepTimeShift--;
  2792. }
  2793. sleepTime = 0;
  2794. standbyTime = systemTime() + standbyDelay;
  2795. //TODO: delay standby when effects have a tail
  2796. }
  2797. void AudioFlinger::MixerThread::threadLoop_sleepTime()
  2798. {
  2799. // If no tracks are ready, sleep once for the duration of an output
  2800. // buffer size, then write 0s to the output
  2801. if (sleepTime == 0) {
  2802. if (mMixerStatus == MIXER_TRACKS_ENABLED) {
  2803. sleepTime = activeSleepTime >> sleepTimeShift;
  2804. if (sleepTime < kMinThreadSleepTimeUs) {
  2805. sleepTime = kMinThreadSleepTimeUs;
  2806. }
  2807. // reduce sleep time in case of consecutive application underruns to avoid
  2808. // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
  2809. // duration we would end up writing less data than needed by the audio HAL if
  2810. // the condition persists.
  2811. if (sleepTimeShift < kMaxThreadSleepTimeShift) {
  2812. sleepTimeShift++;
  2813. }
  2814. } else {
  2815. sleepTime = idleSleepTime;
  2816. }
  2817. } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
  2818. // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
  2819. // before effects processing or output.
  2820. if (mMixerBufferValid) {
  2821. memset(mMixerBuffer, 0, mMixerBufferSize);
  2822. } else {
  2823. memset(mSinkBuffer, 0, mSinkBufferSize);
  2824. }
  2825. sleepTime = 0;
  2826. ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
  2827. "anticipated start");
  2828. }
  2829. // TODO add standby time extension fct of effect tail
  2830. }
  2831. // prepareTracks_l() must be called with ThreadBase::mLock held
  2832. AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
  2833. Vector< sp<Track> > *tracksToRemove)
  2834. {
  2835. mixer_state mixerStatus = MIXER_IDLE;
  2836. // find out which tracks need to be processed
  2837. size_t count = mActiveTracks.size();
  2838. size_t mixedTracks = 0;
  2839. size_t tracksWithEffect = 0;
  2840. // counts only _active_ fast tracks
  2841. size_t fastTracks = 0;
  2842. uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
  2843. float masterVolume = mMasterVolume;
  2844. bool masterMute = mMasterMute;
  2845. if (masterMute) {
  2846. masterVolume = 0;
  2847. }
  2848. // Delegate master volume control to effect in output mix effect chain if needed
  2849. sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
  2850. if (chain != 0) {
  2851. uint32_t v = (uint32_t)(masterVolume * (1 << 24));
  2852. chain->setVolume_l(&v, &v);
  2853. masterVolume = (float)((v + (1 << 23)) >> 24);
  2854. chain.clear();
  2855. }
  2856. // prepare a new state to push
  2857. FastMixerStateQueue *sq = NULL;
  2858. FastMixerState *state = NULL;
  2859. bool didModify = false;
  2860. FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
  2861. if (mFastMixer != 0) {
  2862. sq = mFastMixer->sq();
  2863. state = sq->begin();
  2864. }
  2865. mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
  2866. mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
  2867. for (size_t i=0 ; i<count ; i++) {
  2868. const sp<Track> t = mActiveTracks[i].promote();
  2869. if (t == 0) {
  2870. continue;
  2871. }
  2872. // this const just means the local variable doesn't change
  2873. Track* const track = t.get();
  2874. // process fast tracks
  2875. if (track->isFastTrack()) {
  2876. // It's theoretically possible (though unlikely) for a fast track to be created
  2877. // and then removed within the same normal mix cycle. This is not a problem, as
  2878. // the track never becomes active so it's fast mixer slot is never touched.
  2879. // The converse, of removing an (active) track and then creating a new track
  2880. // at the identical fast mixer slot within the same normal mix cycle,
  2881. // is impossible because the slot isn't marked available until the end of each cycle.
  2882. int j = track->mFastIndex;
  2883. ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
  2884. ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
  2885. FastTrack *fastTrack = &state->mFastTracks[j];
  2886. // Determine whether the track is currently in underrun condition,
  2887. // and whether it had a recent underrun.
  2888. FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
  2889. FastTrackUnderruns underruns = ftDump->mUnderruns;
  2890. uint32_t recentFull = (underruns.mBitFields.mFull -
  2891. track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
  2892. uint32_t recentPartial = (underruns.mBitFields.mPartial -
  2893. track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
  2894. uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
  2895. track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
  2896. uint32_t recentUnderruns = recentPartial + recentEmpty;
  2897. track->mObservedUnderruns = underruns;
  2898. // don't count underruns that occur while stopping or pausing
  2899. // or stopped which can occur when flush() is called while active
  2900. if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
  2901. recentUnderruns > 0) {
  2902. // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
  2903. track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
  2904. }
  2905. // This is similar to the state machine for normal tracks,
  2906. // with a few modifications for fast tracks.
  2907. bool isActive = true;
  2908. switch (track->mState) {
  2909. case TrackBase::STOPPING_1:
  2910. // track stays active in STOPPING_1 state until first underrun
  2911. if (recentUnderruns > 0 || track->isTerminated()) {
  2912. track->mState = TrackBase::STOPPING_2;
  2913. }
  2914. break;
  2915. case TrackBase::PAUSING:
  2916. // ramp down is not yet implemented
  2917. track->setPaused();
  2918. break;
  2919. case TrackBase::RESUMING:
  2920. // ramp up is not yet implemented
  2921. track->mState = TrackBase::ACTIVE;
  2922. break;
  2923. case TrackBase::ACTIVE:
  2924. if (recentFull > 0 || recentPartial > 0) {
  2925. // track has provided at least some frames recently: reset retry count
  2926. track->mRetryCount = kMaxTrackRetries;
  2927. }
  2928. if (recentUnderruns == 0) {
  2929. // no recent underruns: stay active
  2930. break;
  2931. }
  2932. // there has recently been an underrun of some kind
  2933. if (track->sharedBuffer() == 0) {
  2934. // were any of the recent underruns "empty" (no frames available)?
  2935. if (recentEmpty == 0) {
  2936. // no, then ignore the partial underruns as they are allowed indefinitely
  2937. break;
  2938. }
  2939. // there has recently been an "empty" underrun: decrement the retry counter
  2940. if (--(track->mRetryCount) > 0) {
  2941. break;
  2942. }
  2943. // indicate to client process that the track was disabled because of underrun;
  2944. // it will then automatically call start() when data is available
  2945. android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
  2946. // remove from active list, but state remains ACTIVE [confusing but true]
  2947. isActive = false;
  2948. break;
  2949. }
  2950. // fall through
  2951. case TrackBase::STOPPING_2:
  2952. case TrackBase::PAUSED:
  2953. case TrackBase::STOPPED:
  2954. case TrackBase::FLUSHED: // flush() while active
  2955. // Check for presentation complete if track is inactive
  2956. // We have consumed all the buffers of this track.
  2957. // This would be incomplete if we auto-paused on underrun
  2958. {
  2959. size_t audioHALFrames =
  2960. (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
  2961. size_t framesWritten = mBytesWritten / mFrameSize;
  2962. if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
  2963. // track stays in active list until presentation is complete
  2964. break;
  2965. }
  2966. }
  2967. if (track->isStopping_2()) {
  2968. track->mState = TrackBase::STOPPED;
  2969. }
  2970. if (track->isStopped()) {
  2971. // Can't reset directly, as fast mixer is still polling this track
  2972. // track->reset();
  2973. // So instead mark this track as needing to be reset after push with ack
  2974. resetMask |= 1 << i;
  2975. }
  2976. isActive = false;
  2977. break;
  2978. case TrackBase::IDLE:
  2979. default:
  2980. LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
  2981. }
  2982. if (isActive) {
  2983. // was it previously inactive?
  2984. if (!(state->mTrackMask & (1 << j))) {
  2985. ExtendedAudioBufferProvider *eabp = track;
  2986. VolumeProvider *vp = track;
  2987. fastTrack->mBufferProvider = eabp;
  2988. fastTrack->mVolumeProvider = vp;
  2989. fastTrack->mChannelMask = track->mChannelMask;
  2990. fastTrack->mFormat = track->mFormat;
  2991. fastTrack->mGeneration++;
  2992. state->mTrackMask |= 1 << j;
  2993. didModify = true;
  2994. // no acknowledgement required for newly active tracks
  2995. }
  2996. // cache the combined master volume and stream type volume for fast mixer; this
  2997. // lacks any synchronization or barrier so VolumeProvider may read a stale value
  2998. track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
  2999. ++fastTracks;
  3000. } else {
  3001. // was it previously active?
  3002. if (state->mTrackMask & (1 << j)) {
  3003. fastTrack->mBufferProvider = NULL;
  3004. fastTrack->mGeneration++;
  3005. state->mTrackMask &= ~(1 << j);
  3006. didModify = true;
  3007. // If any fast tracks were removed, we must wait for acknowledgement
  3008. // because we're about to decrement the last sp<> on those tracks.
  3009. block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
  3010. } else {
  3011. LOG_ALWAYS_FATAL("fast track %d should have been active", j);
  3012. }
  3013. tracksToRemove->add(track);
  3014. // Avoids a misleading display in dumpsys
  3015. track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
  3016. }
  3017. continue;
  3018. }
  3019. { // local variable scope to avoid goto warning
  3020. audio_track_cblk_t* cblk = track->cblk();
  3021. // The first time a track is added we wait
  3022. // for all its buffers to be filled before processing it
  3023. int name = track->name();
  3024. // make sure that we have enough frames to mix one full buffer.
  3025. // enforce this condition only once to enable draining the buffer in case the client
  3026. // app does not call stop() and relies on underrun to stop:
  3027. // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
  3028. // during last round
  3029. size_t desiredFrames;
  3030. uint32_t sr = track->sampleRate();
  3031. if (sr == mSampleRate) {
  3032. desiredFrames = mNormalFrameCount;
  3033. } else {
  3034. // +1 for rounding and +1 for additional sample needed for interpolation
  3035. desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
  3036. // add frames already consumed but not yet released by the resampler
  3037. // because mAudioTrackServerProxy->framesReady() will include these frames
  3038. desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
  3039. #if 0
  3040. // the minimum track buffer size is normally twice the number of frames necessary
  3041. // to fill one buffer and the resampler should not leave more than one buffer worth
  3042. // of unreleased frames after each pass, but just in case...
  3043. ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
  3044. #endif
  3045. }
  3046. uint32_t minFrames = 1;
  3047. if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
  3048. (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
  3049. minFrames = desiredFrames;
  3050. }
  3051. size_t framesReady = track->framesReady();
  3052. if ((framesReady >= minFrames) && track->isReady() &&
  3053. !track->isPaused() && !track->isTerminated())
  3054. {
  3055. ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
  3056. mixedTracks++;
  3057. // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
  3058. // there is an effect chain connected to the track
  3059. chain.clear();
  3060. if (track->mainBuffer() != mSinkBuffer &&
  3061. track->mainBuffer() != mMixerBuffer) {
  3062. if (mEffectBufferEnabled) {
  3063. mEffectBufferValid = true; // Later can set directly.
  3064. }
  3065. chain = getEffectChain_l(track->sessionId());
  3066. // Delegate volume control to effect in track effect chain if needed
  3067. if (chain != 0) {
  3068. tracksWithEffect++;
  3069. } else {
  3070. ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
  3071. "session %d",
  3072. name, track->sessionId());
  3073. }
  3074. }
  3075. int param = AudioMixer::VOLUME;
  3076. if (track->mFillingUpStatus == Track::FS_FILLED) {
  3077. // no ramp for the first volume setting
  3078. track->mFillingUpStatus = Track::FS_ACTIVE;
  3079. if (track->mState == TrackBase::RESUMING) {
  3080. track->mState = TrackBase::ACTIVE;
  3081. param = AudioMixer::RAMP_VOLUME;
  3082. }
  3083. mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
  3084. // FIXME should not make a decision based on mServer
  3085. } else if (cblk->mServer != 0) {
  3086. // If the track is stopped before the first frame was mixed,
  3087. // do not apply ramp
  3088. param = AudioMixer::RAMP_VOLUME;
  3089. }
  3090. // compute volume for this track
  3091. uint32_t vl, vr; // in U8.24 integer format
  3092. float vlf, vrf, vaf; // in [0.0, 1.0] float format
  3093. if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
  3094. vl = vr = 0;
  3095. vlf = vrf = vaf = 0.;
  3096. if (track->isPausing()) {
  3097. track->setPaused();
  3098. }
  3099. } else {
  3100. // read original volumes with volume control
  3101. float typeVolume = mStreamTypes[track->streamType()].volume;
  3102. float v = masterVolume * typeVolume;
  3103. AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
  3104. gain_minifloat_packed_t vlr = proxy->getVolumeLR();
  3105. vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
  3106. vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
  3107. // track volumes come from shared memory, so can't be trusted and must be clamped
  3108. if (vlf > GAIN_FLOAT_UNITY) {
  3109. ALOGV("Track left volume out of range: %.3g", vlf);
  3110. vlf = GAIN_FLOAT_UNITY;
  3111. }
  3112. if (vrf > GAIN_FLOAT_UNITY) {
  3113. ALOGV("Track right volume out of range: %.3g", vrf);
  3114. vrf = GAIN_FLOAT_UNITY;
  3115. }
  3116. // now apply the master volume and stream type volume
  3117. vlf *= v;
  3118. vrf *= v;
  3119. // assuming master volume and stream type volume each go up to 1.0,
  3120. // then derive vl and vr as U8.24 versions for the effect chain
  3121. const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
  3122. vl = (uint32_t) (scaleto8_24 * vlf);
  3123. vr = (uint32_t) (scaleto8_24 * vrf);
  3124. // vl and vr are now in U8.24 format
  3125. uint16_t sendLevel = proxy->getSendLevel_U4_12();
  3126. // send level comes from shared memory and so may be corrupt
  3127. if (sendLevel > MAX_GAIN_INT) {
  3128. ALOGV("Track send level out of range: %04X", sendLevel);
  3129. sendLevel = MAX_GAIN_INT;
  3130. }
  3131. // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
  3132. vaf = v * sendLevel * (1. / MAX_GAIN_INT);
  3133. }
  3134. // Delegate volume control to effect in track effect chain if needed
  3135. if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
  3136. // Do not ramp volume if volume is controlled by effect
  3137. param = AudioMixer::VOLUME;
  3138. // Update remaining floating point volume levels
  3139. vlf = (float)vl / (1 << 24);
  3140. vrf = (float)vr / (1 << 24);
  3141. track->mHasVolumeController = true;
  3142. } else {
  3143. // force no volume ramp when volume controller was just disabled or removed
  3144. // from effect chain to avoid volume spike
  3145. if (track->mHasVolumeController) {
  3146. param = AudioMixer::VOLUME;
  3147. }
  3148. track->mHasVolumeController = false;
  3149. }
  3150. // XXX: these things DON'T need to be done each time
  3151. mAudioMixer->setBufferProvider(name, track);
  3152. mAudioMixer->enable(name);
  3153. mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
  3154. mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
  3155. mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
  3156. mAudioMixer->setParameter(
  3157. name,
  3158. AudioMixer::TRACK,
  3159. AudioMixer::FORMAT, (void *)track->format());
  3160. mAudioMixer->setParameter(
  3161. name,
  3162. AudioMixer::TRACK,
  3163. AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
  3164. mAudioMixer->setParameter(
  3165. name,
  3166. AudioMixer::TRACK,
  3167. AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
  3168. // limit track sample rate to 2 x output sample rate, which changes at re-configuration
  3169. uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
  3170. uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
  3171. if (reqSampleRate == 0) {
  3172. reqSampleRate = mSampleRate;
  3173. } else if (reqSampleRate > maxSampleRate) {
  3174. reqSampleRate = maxSampleRate;
  3175. }
  3176. mAudioMixer->setParameter(
  3177. name,
  3178. AudioMixer::RESAMPLE,
  3179. AudioMixer::SAMPLE_RATE,
  3180. (void *)(uintptr_t)reqSampleRate);
  3181. /*
  3182. * Select the appropriate output buffer for the track.
  3183. *
  3184. * Tracks with effects go into their own effects chain buffer
  3185. * and from there into either mEffectBuffer or mSinkBuffer.
  3186. *
  3187. * Other tracks can use mMixerBuffer for higher precision
  3188. * channel accumulation. If this buffer is enabled
  3189. * (mMixerBufferEnabled true), then selected tracks will accumulate
  3190. * into it.
  3191. *
  3192. */
  3193. if (mMixerBufferEnabled
  3194. && (track->mainBuffer() == mSinkBuffer
  3195. || track->mainBuffer() == mMixerBuffer)) {
  3196. mAudioMixer->setParameter(
  3197. name,
  3198. AudioMixer::TRACK,
  3199. AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
  3200. mAudioMixer->setParameter(
  3201. name,
  3202. AudioMixer::TRACK,
  3203. AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
  3204. // TODO: override track->mainBuffer()?
  3205. mMixerBufferValid = true;
  3206. } else {
  3207. mAudioMixer->setParameter(
  3208. name,
  3209. AudioMixer::TRACK,
  3210. AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
  3211. mAudioMixer->setParameter(
  3212. name,
  3213. AudioMixer::TRACK,
  3214. AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
  3215. }
  3216. mAudioMixer->setParameter(
  3217. name,
  3218. AudioMixer::TRACK,
  3219. AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
  3220. // reset retry count
  3221. track->mRetryCount = kMaxTrackRetries;
  3222. // If one track is ready, set the mixer ready if:
  3223. // - the mixer was not ready during previous round OR
  3224. // - no other track is not ready
  3225. if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
  3226. mixerStatus != MIXER_TRACKS_ENABLED) {
  3227. mixerStatus = MIXER_TRACKS_READY;
  3228. }
  3229. } else {
  3230. if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
  3231. track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
  3232. }
  3233. // clear effect chain input buffer if an active track underruns to avoid sending
  3234. // previous audio buffer again to effects
  3235. chain = getEffectChain_l(track->sessionId());
  3236. if (chain != 0) {
  3237. chain->clearInputBuffer();
  3238. }
  3239. ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
  3240. if ((track->sharedBuffer() != 0) || track->isTerminated() ||
  3241. track->isStopped() || track->isPaused()) {
  3242. // We have consumed all the buffers of this track.
  3243. // Remove it from the list of active tracks.
  3244. // TODO: use actual buffer filling status instead of latency when available from
  3245. // audio HAL
  3246. size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
  3247. size_t framesWritten = mBytesWritten / mFrameSize;
  3248. if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
  3249. if (track->isStopped()) {
  3250. track->reset();
  3251. }
  3252. tracksToRemove->add(track);
  3253. }
  3254. } else {
  3255. // No buffers for this track. Give it a few chances to
  3256. // fill a buffer, then remove it from active list.
  3257. if (--(track->mRetryCount) <= 0) {
  3258. ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
  3259. tracksToRemove->add(track);
  3260. // indicate to client process that the track was disabled because of underrun;
  3261. // it will then automatically call start() when data is available
  3262. android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
  3263. // If one track is not ready, mark the mixer also not ready if:
  3264. // - the mixer was ready during previous round OR
  3265. // - no other track is ready
  3266. } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
  3267. mixerStatus != MIXER_TRACKS_READY) {
  3268. mixerStatus = MIXER_TRACKS_ENABLED;
  3269. }
  3270. }
  3271. mAudioMixer->disable(name);
  3272. }
  3273. } // local variable scope to avoid goto warning
  3274. track_is_ready: ;
  3275. }
  3276. // Push the new FastMixer state if necessary
  3277. bool pauseAudioWatchdog = false;
  3278. if (didModify) {
  3279. state->mFastTracksGen++;
  3280. // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
  3281. if (kUseFastMixer == FastMixer_Dynamic &&
  3282. state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
  3283. state->mCommand = FastMixerState::COLD_IDLE;
  3284. state->mColdFutexAddr = &mFastMixerFutex;
  3285. state->mColdGen++;
  3286. mFastMixerFutex = 0;
  3287. if (kUseFastMixer == FastMixer_Dynamic) {
  3288. mNormalSink = mOutputSink;
  3289. }
  3290. // If we go into cold idle, need to wait for acknowledgement
  3291. // so that fast mixer stops doing I/O.
  3292. block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
  3293. pauseAudioWatchdog = true;
  3294. }
  3295. }
  3296. if (sq != NULL) {
  3297. sq->end(didModify);
  3298. sq->push(block);
  3299. }
  3300. #ifdef AUDIO_WATCHDOG
  3301. if (pauseAudioWatchdog && mAudioWatchdog != 0) {
  3302. mAudioWatchdog->pause();
  3303. }
  3304. #endif
  3305. // Now perform the deferred reset on fast tracks that have stopped
  3306. while (resetMask != 0) {
  3307. size_t i = __builtin_ctz(resetMask);
  3308. ALOG_ASSERT(i < count);
  3309. resetMask &= ~(1 << i);
  3310. sp<Track> t = mActiveTracks[i].promote();
  3311. if (t == 0) {
  3312. continue;
  3313. }
  3314. Track* track = t.get();
  3315. ALOG_ASSERT(track->isFastTrack() && track->isStopped());
  3316. track->reset();
  3317. }
  3318. // remove all the tracks that need to be...
  3319. removeTracks_l(*tracksToRemove);
  3320. if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
  3321. mEffectBufferValid = true;
  3322. }
  3323. if (mEffectBufferValid) {
  3324. // as long as there are effects we should clear the effects buffer, to avoid
  3325. // passing a non-clean buffer to the effect chain
  3326. memset(mEffectBuffer, 0, mEffectBufferSize);
  3327. }
  3328. // sink or mix buffer must be cleared if all tracks are connected to an
  3329. // effect chain as in this case the mixer will not write to the sink or mix buffer
  3330. // and track effects will accumulate into it
  3331. if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
  3332. (mixedTracks == 0 && fastTracks > 0))) {
  3333. // FIXME as a performance optimization, should remember previous zero status
  3334. if (mMixerBufferValid) {
  3335. memset(mMixerBuffer, 0, mMixerBufferSize);
  3336. // TODO: In testing, mSinkBuffer below need not be cleared because
  3337. // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
  3338. // after mixing.
  3339. //
  3340. // To enforce this guarantee:
  3341. // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
  3342. // (mixedTracks == 0 && fastTracks > 0))
  3343. // must imply MIXER_TRACKS_READY.
  3344. // Later, we may clear buffers regardless, and skip much of this logic.
  3345. }
  3346. // FIXME as a performance optimization, should remember previous zero status
  3347. memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
  3348. }
  3349. // if any fast tracks, then status is ready
  3350. mMixerStatusIgnoringFastTracks = mixerStatus;
  3351. if (fastTracks > 0) {
  3352. mixerStatus = MIXER_TRACKS_READY;
  3353. }
  3354. return mixerStatus;
  3355. }
  3356. // getTrackName_l() must be called with ThreadBase::mLock held
  3357. int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
  3358. audio_format_t format, int sessionId)
  3359. {
  3360. return mAudioMixer->getTrackName(channelMask, format, sessionId);
  3361. }
  3362. // deleteTrackName_l() must be called with ThreadBase::mLock held
  3363. void AudioFlinger::MixerThread::deleteTrackName_l(int name)
  3364. {
  3365. ALOGV("remove track (%d) and delete from mixer", name);
  3366. mAudioMixer->deleteTrackName(name);
  3367. }
  3368. // checkForNewParameter_l() must be called with ThreadBase::mLock held
  3369. bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
  3370. status_t& status)
  3371. {
  3372. bool reconfig = false;
  3373. status = NO_ERROR;
  3374. // if !&IDLE, holds the FastMixer state to restore after new parameters processed
  3375. FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
  3376. if (mFastMixer != 0) {
  3377. FastMixerStateQueue *sq = mFastMixer->sq();
  3378. FastMixerState *state = sq->begin();
  3379. if (!(state->mCommand & FastMixerState::IDLE)) {
  3380. previousCommand = state->mCommand;
  3381. state->mCommand = FastMixerState::HOT_IDLE;
  3382. sq->end();
  3383. sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
  3384. } else {
  3385. sq->end(false /*didModify*/);
  3386. }
  3387. }
  3388. AudioParameter param = AudioParameter(keyValuePair);
  3389. int value;
  3390. if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
  3391. reconfig = true;
  3392. }
  3393. if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
  3394. if (!isValidPcmSinkFormat((audio_format_t) value)) {
  3395. status = BAD_VALUE;
  3396. } else {
  3397. // no need to save value, since it's constant
  3398. reconfig = true;
  3399. }
  3400. }
  3401. if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
  3402. if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
  3403. status = BAD_VALUE;
  3404. } else {
  3405. // no need to save value, since it's constant
  3406. reconfig = true;
  3407. }
  3408. }
  3409. if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
  3410. // do not accept frame count changes if tracks are open as the track buffer
  3411. // size depends on frame count and correct behavior would not be guaranteed
  3412. // if frame count is changed after track creation
  3413. if (!mTracks.isEmpty()) {
  3414. status = INVALID_OPERATION;
  3415. } else {
  3416. reconfig = true;
  3417. }
  3418. }
  3419. if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
  3420. #ifdef ADD_BATTERY_DATA
  3421. // when changing the audio output device, call addBatteryData to notify
  3422. // the change
  3423. if (mOutDevice != value) {
  3424. uint32_t params = 0;
  3425. // check whether speaker is on
  3426. if (value & AUDIO_DEVICE_OUT_SPEAKER) {
  3427. params |= IMediaPlayerService::kBatteryDataSpeakerOn;
  3428. }
  3429. audio_devices_t deviceWithoutSpeaker
  3430. = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
  3431. // check if any other device (except speaker) is on
  3432. if (value & deviceWithoutSpeaker ) {
  3433. params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
  3434. }
  3435. if (params != 0) {
  3436. addBatteryData(params);
  3437. }
  3438. }
  3439. #endif
  3440. // forward device change to effects that have requested to be
  3441. // aware of attached audio device.
  3442. if (value != AUDIO_DEVICE_NONE) {
  3443. mOutDevice = value;
  3444. for (size_t i = 0; i < mEffectChains.size(); i++) {
  3445. mEffectChains[i]->setDevice_l(mOutDevice);
  3446. }
  3447. }
  3448. }
  3449. if (status == NO_ERROR) {
  3450. status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
  3451. keyValuePair.string());
  3452. if (!mStandby && status == INVALID_OPERATION) {
  3453. mOutput->stream->common.standby(&mOutput->stream->common);
  3454. mStandby = true;
  3455. mBytesWritten = 0;
  3456. status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
  3457. keyValuePair.string());
  3458. }
  3459. if (status == NO_ERROR && reconfig) {
  3460. readOutputParameters_l();
  3461. delete mAudioMixer;
  3462. mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
  3463. for (size_t i = 0; i < mTracks.size() ; i++) {
  3464. int name = getTrackName_l(mTracks[i]->mChannelMask,
  3465. mTracks[i]->mFormat, mTracks[i]->mSessionId);
  3466. if (name < 0) {
  3467. break;
  3468. }
  3469. mTracks[i]->mName = name;
  3470. }
  3471. sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
  3472. }
  3473. }
  3474. if (!(previousCommand & FastMixerState::IDLE)) {
  3475. ALOG_ASSERT(mFastMixer != 0);
  3476. FastMixerStateQueue *sq = mFastMixer->sq();
  3477. FastMixerState *state = sq->begin();
  3478. ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
  3479. state->mCommand = previousCommand;
  3480. sq->end();
  3481. sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
  3482. }
  3483. return reconfig;
  3484. }
  3485. void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
  3486. {
  3487. const size_t SIZE = 256;
  3488. char buffer[SIZE];
  3489. String8 result;
  3490. PlaybackThread::dumpInternals(fd, args);
  3491. dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
  3492. // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
  3493. const FastMixerDumpState copy(mFastMixerDumpState);
  3494. copy.dump(fd);
  3495. #ifdef STATE_QUEUE_DUMP
  3496. // Similar for state queue
  3497. StateQueueObserverDump observerCopy = mStateQueueObserverDump;
  3498. observerCopy.dump(fd);
  3499. StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
  3500. mutatorCopy.dump(fd);
  3501. #endif
  3502. #ifdef TEE_SINK
  3503. // Write the tee output to a .wav file
  3504. dumpTee(fd, mTeeSource, mId);
  3505. #endif
  3506. #ifdef AUDIO_WATCHDOG
  3507. if (mAudioWatchdog != 0) {
  3508. // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
  3509. AudioWatchdogDump wdCopy = mAudioWatchdogDump;
  3510. wdCopy.dump(fd);
  3511. }
  3512. #endif
  3513. }
  3514. uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
  3515. {
  3516. return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
  3517. }
  3518. uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
  3519. {
  3520. return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
  3521. }
  3522. void AudioFlinger::MixerThread::cacheParameters_l()
  3523. {
  3524. PlaybackThread::cacheParameters_l();
  3525. // FIXME: Relaxed timing because of a certain device that can't meet latency
  3526. // Should be reduced to 2x after the vendor fixes the driver issue
  3527. // increase threshold again due to low power audio mode. The way this warning
  3528. // threshold is calculated and its usefulness should be reconsidered anyway.
  3529. maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
  3530. }
  3531. // ----------------------------------------------------------------------------
  3532. AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
  3533. AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
  3534. : PlaybackThread(audioFlinger, output, id, device, DIRECT)
  3535. // mLeftVolFloat, mRightVolFloat
  3536. {
  3537. }
  3538. AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
  3539. AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
  3540. ThreadBase::type_t type)
  3541. : PlaybackThread(audioFlinger, output, id, device, type)
  3542. // mLeftVolFloat, mRightVolFloat
  3543. {
  3544. }
  3545. AudioFlinger::DirectOutputThread::~DirectOutputThread()
  3546. {
  3547. }
  3548. void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
  3549. {
  3550. audio_track_cblk_t* cblk = track->cblk();
  3551. float left, right;
  3552. if (mMasterMute || mStreamTypes[track->streamType()].mute) {
  3553. left = right = 0;
  3554. } else {
  3555. float typeVolume = mStreamTypes[track->streamType()].volume;
  3556. float v = mMasterVolume * typeVolume;
  3557. AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
  3558. gain_minifloat_packed_t vlr = proxy->getVolumeLR();
  3559. left = float_from_gain(gain_minifloat_unpack_left(vlr));
  3560. if (left > GAIN_FLOAT_UNITY) {
  3561. left = GAIN_FLOAT_UNITY;
  3562. }
  3563. left *= v;
  3564. right = float_from_gain(gain_minifloat_unpack_right(vlr));
  3565. if (right > GAIN_FLOAT_UNITY) {
  3566. right = GAIN_FLOAT_UNITY;
  3567. }
  3568. right *= v;
  3569. }
  3570. if (lastTrack) {
  3571. if (left != mLeftVolFloat || right != mRightVolFloat) {
  3572. mLeftVolFloat = left;
  3573. mRightVolFloat = right;
  3574. // Convert volumes from float to 8.24
  3575. uint32_t vl = (uint32_t)(left * (1 << 24));
  3576. uint32_t vr = (uint32_t)(right * (1 << 24));
  3577. // Delegate volume control to effect in track effect chain if needed
  3578. // only one effect chain can be present on DirectOutputThread, so if
  3579. // there is one, the track is connected to it
  3580. if (!mEffectChains.isEmpty()) {
  3581. mEffectChains[0]->setVolume_l(&vl, &vr);
  3582. left = (float)vl / (1 << 24);
  3583. right = (float)vr / (1 << 24);
  3584. }
  3585. if (mOutput->stream->set_volume) {
  3586. mOutput->stream->set_volume(mOutput->stream, left, right);
  3587. }
  3588. }
  3589. }
  3590. }
  3591. AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
  3592. Vector< sp<Track> > *tracksToRemove
  3593. )
  3594. {
  3595. size_t count = mActiveTracks.size();
  3596. mixer_state mixerStatus = MIXER_IDLE;
  3597. bool doHwPause = false;
  3598. bool doHwResume = false;
  3599. bool flushPending = false;
  3600. // find out which tracks need to be processed
  3601. for (size_t i = 0; i < count; i++) {
  3602. sp<Track> t = mActiveTracks[i].promote();
  3603. // The track died recently
  3604. if (t == 0) {
  3605. continue;
  3606. }
  3607. Track* const track = t.get();
  3608. audio_track_cblk_t* cblk = track->cblk();
  3609. // Only consider last track started for volume and mixer state control.
  3610. // In theory an older track could underrun and restart after the new one starts
  3611. // but as we only care about the transition phase between two tracks on a
  3612. // direct output, it is not a problem to ignore the underrun case.
  3613. sp<Track> l = mLatestActiveTrack.promote();
  3614. bool last = l.get() == track;
  3615. if (mHwSupportsPause && track->isPausing()) {
  3616. track->setPaused();
  3617. if (last && !mHwPaused) {
  3618. doHwPause = true;
  3619. mHwPaused = true;
  3620. }
  3621. tracksToRemove->add(track);
  3622. } else if (track->isFlushPending()) {
  3623. track->flushAck();
  3624. if (last) {
  3625. flushPending = true;
  3626. }
  3627. } else if (mHwSupportsPause && track->isResumePending()){
  3628. track->resumeAck();
  3629. if (last) {
  3630. if (mHwPaused) {
  3631. doHwResume = true;
  3632. mHwPaused = false;
  3633. }
  3634. }
  3635. }
  3636. // The first time a track is added we wait
  3637. // for all its buffers to be filled before processing it.
  3638. // Allow draining the buffer in case the client
  3639. // app does not call stop() and relies on underrun to stop:
  3640. // hence the test on (track->mRetryCount > 1).
  3641. // If retryCount<=1 then track is about to underrun and be removed.
  3642. uint32_t minFrames;
  3643. if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
  3644. && (track->mRetryCount > 1)) {
  3645. minFrames = mNormalFrameCount;
  3646. } else {
  3647. minFrames = 1;
  3648. }
  3649. if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
  3650. !track->isStopping_2() && !track->isStopped())
  3651. {
  3652. ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
  3653. if (track->mFillingUpStatus == Track::FS_FILLED) {
  3654. track->mFillingUpStatus = Track::FS_ACTIVE;
  3655. // make sure processVolume_l() will apply new volume even if 0
  3656. mLeftVolFloat = mRightVolFloat = -1.0;
  3657. if (!mHwSupportsPause) {
  3658. track->resumeAck();
  3659. }
  3660. }
  3661. // compute volume for this track
  3662. processVolume_l(track, last);
  3663. if (last) {
  3664. // reset retry count
  3665. track->mRetryCount = kMaxTrackRetriesDirect;
  3666. mActiveTrack = t;
  3667. mixerStatus = MIXER_TRACKS_READY;
  3668. if (usesHwAvSync() && mHwPaused) {
  3669. doHwResume = true;
  3670. mHwPaused = false;
  3671. }
  3672. }
  3673. } else {
  3674. // clear effect chain input buffer if the last active track started underruns
  3675. // to avoid sending previous audio buffer again to effects
  3676. if (!mEffectChains.isEmpty() && last) {
  3677. mEffectChains[0]->clearInputBuffer();
  3678. }
  3679. if (track->isStopping_1()) {
  3680. track->mState = TrackBase::STOPPING_2;
  3681. }
  3682. if ((track->sharedBuffer() != 0) || track->isStopped() ||
  3683. track->isStopping_2() || track->isPaused()) {
  3684. // We have consumed all the buffers of this track.
  3685. // Remove it from the list of active tracks.
  3686. size_t audioHALFrames;
  3687. if (audio_is_linear_pcm(mFormat)) {
  3688. audioHALFrames = (latency_l() * mSampleRate) / 1000;
  3689. } else {
  3690. audioHALFrames = 0;
  3691. }
  3692. size_t framesWritten = mBytesWritten / mFrameSize;
  3693. if (mStandby || !last ||
  3694. track->presentationComplete(framesWritten, audioHALFrames)) {
  3695. if (track->isStopping_2()) {
  3696. track->mState = TrackBase::STOPPED;
  3697. }
  3698. if (track->isStopped()) {
  3699. track->reset();
  3700. }
  3701. tracksToRemove->add(track);
  3702. }
  3703. } else {
  3704. // No buffers for this track. Give it a few chances to
  3705. // fill a buffer, then remove it from active list.
  3706. // Only consider last track started for mixer state control
  3707. if (--(track->mRetryCount) <= 0) {
  3708. ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
  3709. tracksToRemove->add(track);
  3710. // indicate to client process that the track was disabled because of underrun;
  3711. // it will then automatically call start() when data is available
  3712. android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
  3713. } else if (last) {
  3714. mixerStatus = MIXER_TRACKS_ENABLED;
  3715. if (usesHwAvSync() && !mHwPaused && !mStandby) {
  3716. doHwPause = true;
  3717. mHwPaused = true;
  3718. }
  3719. }
  3720. }
  3721. }
  3722. }
  3723. // if an active track did not command a flush, check for pending flush on stopped tracks
  3724. if (!flushPending) {
  3725. for (size_t i = 0; i < mTracks.size(); i++) {
  3726. if (mTracks[i]->isFlushPending()) {
  3727. mTracks[i]->flushAck();
  3728. flushPending = true;
  3729. }
  3730. }
  3731. }
  3732. // make sure the pause/flush/resume sequence is executed in the right order.
  3733. // If a flush is pending and a track is active but the HW is not paused, force a HW pause
  3734. // before flush and then resume HW. This can happen in case of pause/flush/resume
  3735. // if resume is received before pause is executed.
  3736. if (mHwSupportsPause && !mStandby &&
  3737. (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
  3738. mOutput->stream->pause(mOutput->stream);
  3739. }
  3740. if (flushPending) {
  3741. flushHw_l();
  3742. }
  3743. if (mHwSupportsPause && !mStandby && doHwResume) {
  3744. mOutput->stream->resume(mOutput->stream);
  3745. }
  3746. // remove all the tracks that need to be...
  3747. removeTracks_l(*tracksToRemove);
  3748. return mixerStatus;
  3749. }
  3750. void AudioFlinger::DirectOutputThread::threadLoop_mix()
  3751. {
  3752. size_t frameCount = mFrameCount;
  3753. int8_t *curBuf = (int8_t *)mSinkBuffer;
  3754. // output audio to hardware
  3755. while (frameCount) {
  3756. AudioBufferProvider::Buffer buffer;
  3757. buffer.frameCount = frameCount;
  3758. mActiveTrack->getNextBuffer(&buffer);
  3759. if (buffer.raw == NULL) {
  3760. memset(curBuf, 0, frameCount * mFrameSize);
  3761. break;
  3762. }
  3763. memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
  3764. frameCount -= buffer.frameCount;
  3765. curBuf += buffer.frameCount * mFrameSize;
  3766. mActiveTrack->releaseBuffer(&buffer);
  3767. }
  3768. mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
  3769. sleepTime = 0;
  3770. standbyTime = systemTime() + standbyDelay;
  3771. mActiveTrack.clear();
  3772. }
  3773. void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
  3774. {
  3775. // do not write to HAL when paused
  3776. if (mHwPaused || (usesHwAvSync() && mStandby)) {
  3777. sleepTime = idleSleepTime;
  3778. return;
  3779. }
  3780. if (sleepTime == 0) {
  3781. if (mMixerStatus == MIXER_TRACKS_ENABLED) {
  3782. sleepTime = activeSleepTime;
  3783. } else {
  3784. sleepTime = idleSleepTime;
  3785. }
  3786. } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
  3787. memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
  3788. sleepTime = 0;
  3789. }
  3790. }
  3791. void AudioFlinger::DirectOutputThread::threadLoop_exit()
  3792. {
  3793. {
  3794. Mutex::Autolock _l(mLock);
  3795. bool flushPending = false;
  3796. for (size_t i = 0; i < mTracks.size(); i++) {
  3797. if (mTracks[i]->isFlushPending()) {
  3798. mTracks[i]->flushAck();
  3799. flushPending = true;
  3800. }
  3801. }
  3802. if (flushPending) {
  3803. flushHw_l();
  3804. }
  3805. }
  3806. PlaybackThread::threadLoop_exit();
  3807. }
  3808. // must be called with thread mutex locked
  3809. bool AudioFlinger::DirectOutputThread::shouldStandby_l()
  3810. {
  3811. bool trackPaused = false;
  3812. // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
  3813. // after a timeout and we will enter standby then.
  3814. if (mTracks.size() > 0) {
  3815. trackPaused = mTracks[mTracks.size() - 1]->isPaused();
  3816. }
  3817. return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
  3818. }
  3819. // getTrackName_l() must be called with ThreadBase::mLock held
  3820. int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
  3821. audio_format_t format __unused, int sessionId __unused)
  3822. {
  3823. return 0;
  3824. }
  3825. // deleteTrackName_l() must be called with ThreadBase::mLock held
  3826. void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
  3827. {
  3828. }
  3829. // checkForNewParameter_l() must be called with ThreadBase::mLock held
  3830. bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
  3831. status_t& status)
  3832. {
  3833. bool reconfig = false;
  3834. status = NO_ERROR;
  3835. AudioParameter param = AudioParameter(keyValuePair);
  3836. int value;
  3837. if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
  3838. // forward device change to effects that have requested to be
  3839. // aware of attached audio device.
  3840. if (value != AUDIO_DEVICE_NONE) {
  3841. mOutDevice = value;
  3842. for (size_t i = 0; i < mEffectChains.size(); i++) {
  3843. mEffectChains[i]->setDevice_l(mOutDevice);
  3844. }
  3845. }
  3846. }
  3847. if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
  3848. // do not accept frame count changes if tracks are open as the track buffer
  3849. // size depends on frame count and correct behavior would not be garantied
  3850. // if frame count is changed after track creation
  3851. if (!mTracks.isEmpty()) {
  3852. status = INVALID_OPERATION;
  3853. } else {
  3854. reconfig = true;
  3855. }
  3856. }
  3857. if (status == NO_ERROR) {
  3858. status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
  3859. keyValuePair.string());
  3860. if (!mStandby && status == INVALID_OPERATION) {
  3861. mOutput->stream->common.standby(&mOutput->stream->common);
  3862. mStandby = true;
  3863. mBytesWritten = 0;
  3864. status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
  3865. keyValuePair.string());
  3866. }
  3867. if (status == NO_ERROR && reconfig) {
  3868. readOutputParameters_l();
  3869. sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
  3870. }
  3871. }
  3872. return reconfig;
  3873. }
  3874. uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
  3875. {
  3876. uint32_t time;
  3877. if (audio_is_linear_pcm(mFormat)) {
  3878. time = PlaybackThread::activeSleepTimeUs();
  3879. } else {
  3880. time = 10000;
  3881. }
  3882. return time;
  3883. }
  3884. uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
  3885. {
  3886. uint32_t time;
  3887. if (audio_is_linear_pcm(mFormat)) {
  3888. time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
  3889. } else {
  3890. time = 10000;
  3891. }
  3892. return time;
  3893. }
  3894. uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
  3895. {
  3896. uint32_t time;
  3897. if (audio_is_linear_pcm(mFormat)) {
  3898. time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
  3899. } else {
  3900. time = 10000;
  3901. }
  3902. return time;
  3903. }
  3904. void AudioFlinger::DirectOutputThread::cacheParameters_l()
  3905. {
  3906. PlaybackThread::cacheParameters_l();
  3907. // use shorter standby delay as on normal output to release
  3908. // hardware resources as soon as possible
  3909. if (audio_is_linear_pcm(mFormat)) {
  3910. standbyDelay = microseconds(activeSleepTime*2);
  3911. } else {
  3912. standbyDelay = kOffloadStandbyDelayNs;
  3913. }
  3914. }
  3915. void AudioFlinger::DirectOutputThread::flushHw_l()
  3916. {
  3917. if (mOutput->stream->flush != NULL) {
  3918. mOutput->stream->flush(mOutput->stream);
  3919. }
  3920. mHwPaused = false;
  3921. }
  3922. // ----------------------------------------------------------------------------
  3923. AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
  3924. const wp<AudioFlinger::PlaybackThread>& playbackThread)
  3925. : Thread(false /*canCallJava*/),
  3926. mPlaybackThread(playbackThread),
  3927. mWriteAckSequence(0),
  3928. mDrainSequence(0)
  3929. {
  3930. }
  3931. AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
  3932. {
  3933. }
  3934. void AudioFlinger::AsyncCallbackThread::onFirstRef()
  3935. {
  3936. run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
  3937. }
  3938. bool AudioFlinger::AsyncCallbackThread::threadLoop()
  3939. {
  3940. while (!exitPending()) {
  3941. uint32_t writeAckSequence;
  3942. uint32_t drainSequence;
  3943. {
  3944. Mutex::Autolock _l(mLock);
  3945. while (!((mWriteAckSequence & 1) ||
  3946. (mDrainSequence & 1) ||
  3947. exitPending())) {
  3948. mWaitWorkCV.wait(mLock);
  3949. }
  3950. if (exitPending()) {
  3951. break;
  3952. }
  3953. ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
  3954. mWriteAckSequence, mDrainSequence);
  3955. writeAckSequence = mWriteAckSequence;
  3956. mWriteAckSequence &= ~1;
  3957. drainSequence = mDrainSequence;
  3958. mDrainSequence &= ~1;
  3959. }
  3960. {
  3961. sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
  3962. if (playbackThread != 0) {
  3963. if (writeAckSequence & 1) {
  3964. playbackThread->resetWriteBlocked(writeAckSequence >> 1);
  3965. }
  3966. if (drainSequence & 1) {
  3967. playbackThread->resetDraining(drainSequence >> 1);
  3968. }
  3969. }
  3970. }
  3971. }
  3972. return false;
  3973. }
  3974. void AudioFlinger::AsyncCallbackThread::exit()
  3975. {
  3976. ALOGV("AsyncCallbackThread::exit");
  3977. Mutex::Autolock _l(mLock);
  3978. requestExit();
  3979. mWaitWorkCV.broadcast();
  3980. }
  3981. void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
  3982. {
  3983. Mutex::Autolock _l(mLock);
  3984. // bit 0 is cleared
  3985. mWriteAckSequence = sequence << 1;
  3986. }
  3987. void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
  3988. {
  3989. Mutex::Autolock _l(mLock);
  3990. // ignore unexpected callbacks
  3991. if (mWriteAckSequence & 2) {
  3992. mWriteAckSequence |= 1;
  3993. mWaitWorkCV.signal();
  3994. }
  3995. }
  3996. void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
  3997. {
  3998. Mutex::Autolock _l(mLock);
  3999. // bit 0 is cleared
  4000. mDrainSequence = sequence << 1;
  4001. }
  4002. void AudioFlinger::AsyncCallbackThread::resetDraining()
  4003. {
  4004. Mutex::Autolock _l(mLock);
  4005. // ignore unexpected callbacks
  4006. if (mDrainSequence & 2) {
  4007. mDrainSequence |= 1;
  4008. mWaitWorkCV.signal();
  4009. }
  4010. }
  4011. // ----------------------------------------------------------------------------
  4012. AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
  4013. AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
  4014. : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
  4015. mPausedBytesRemaining(0)
  4016. {
  4017. //FIXME: mStandby should be set to true by ThreadBase constructor
  4018. mStandby = true;
  4019. }
  4020. void AudioFlinger::OffloadThread::threadLoop_exit()
  4021. {
  4022. if (mFlushPending || mHwPaused) {
  4023. // If a flush is pending or track was paused, just discard buffered data
  4024. flushHw_l();
  4025. } else {
  4026. mMixerStatus = MIXER_DRAIN_ALL;
  4027. threadLoop_drain();
  4028. }
  4029. if (mUseAsyncWrite) {
  4030. ALOG_ASSERT(mCallbackThread != 0);
  4031. mCallbackThread->exit();
  4032. }
  4033. PlaybackThread::threadLoop_exit();
  4034. }
  4035. AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
  4036. Vector< sp<Track> > *tracksToRemove
  4037. )
  4038. {
  4039. size_t count = mActiveTracks.size();
  4040. mixer_state mixerStatus = MIXER_IDLE;
  4041. bool doHwPause = false;
  4042. bool doHwResume = false;
  4043. ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
  4044. // find out which tracks need to be processed
  4045. for (size_t i = 0; i < count; i++) {
  4046. sp<Track> t = mActiveTracks[i].promote();
  4047. // The track died recently
  4048. if (t == 0) {
  4049. continue;
  4050. }
  4051. Track* const track = t.get();
  4052. audio_track_cblk_t* cblk = track->cblk();
  4053. // Only consider last track started for volume and mixer state control.
  4054. // In theory an older track could underrun and restart after the new one starts
  4055. // but as we only care about the transition phase between two tracks on a
  4056. // direct output, it is not a problem to ignore the underrun case.
  4057. sp<Track> l = mLatestActiveTrack.promote();
  4058. bool last = l.get() == track;
  4059. if (track->isInvalid()) {
  4060. ALOGW("An invalidated track shouldn't be in active list");
  4061. tracksToRemove->add(track);
  4062. continue;
  4063. }
  4064. if (track->mState == TrackBase::IDLE) {
  4065. ALOGW("An idle track shouldn't be in active list");
  4066. continue;
  4067. }
  4068. if (track->isPausing()) {
  4069. track->setPaused();
  4070. if (last) {
  4071. if (!mHwPaused) {
  4072. doHwPause = true;
  4073. mHwPaused = true;
  4074. }
  4075. // If we were part way through writing the mixbuffer to
  4076. // the HAL we must save this until we resume
  4077. // BUG - this will be wrong if a different track is made active,
  4078. // in that case we want to discard the pending data in the
  4079. // mixbuffer and tell the client to present it again when the
  4080. // track is resumed
  4081. mPausedWriteLength = mCurrentWriteLength;
  4082. mPausedBytesRemaining = mBytesRemaining;
  4083. mBytesRemaining = 0; // stop writing
  4084. }
  4085. tracksToRemove->add(track);
  4086. } else if (track->isFlushPending()) {
  4087. track->flushAck();
  4088. if (last) {
  4089. mFlushPending = true;
  4090. }
  4091. } else if (track->isResumePending()){
  4092. track->resumeAck();
  4093. if (last) {
  4094. if (mPausedBytesRemaining) {
  4095. // Need to continue write that was interrupted
  4096. mCurrentWriteLength = mPausedWriteLength;
  4097. mBytesRemaining = mPausedBytesRemaining;
  4098. mPausedBytesRemaining = 0;
  4099. }
  4100. if (mHwPaused) {
  4101. doHwResume = true;
  4102. mHwPaused = false;
  4103. // threadLoop_mix() will handle the case that we need to
  4104. // resume an interrupted write
  4105. }
  4106. // enable write to audio HAL
  4107. sleepTime = 0;
  4108. // Do not handle new data in this iteration even if track->framesReady()
  4109. mixerStatus = MIXER_TRACKS_ENABLED;
  4110. }
  4111. } else if (track->framesReady() && track->isReady() &&
  4112. !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
  4113. ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
  4114. if (track->mFillingUpStatus == Track::FS_FILLED) {
  4115. track->mFillingUpStatus = Track::FS_ACTIVE;
  4116. // make sure processVolume_l() will apply new volume even if 0
  4117. mLeftVolFloat = mRightVolFloat = -1.0;
  4118. }
  4119. if (last) {
  4120. sp<Track> previousTrack = mPreviousTrack.promote();
  4121. if (previousTrack != 0) {
  4122. if (track != previousTrack.get()) {
  4123. // Flush any data still being written from last track
  4124. mBytesRemaining = 0;
  4125. if (mPausedBytesRemaining) {
  4126. // Last track was paused so we also need to flush saved
  4127. // mixbuffer state and invalidate track so that it will
  4128. // re-submit that unwritten data when it is next resumed
  4129. mPausedBytesRemaining = 0;
  4130. // Invalidate is a bit drastic - would be more efficient
  4131. // to have a flag to tell client that some of the
  4132. // previously written data was lost
  4133. previousTrack->invalidate();
  4134. }
  4135. // flush data already sent to the DSP if changing audio session as audio
  4136. // comes from a different source. Also invalidate previous track to force a
  4137. // seek when resuming.
  4138. if (previousTrack->sessionId() != track->sessionId()) {
  4139. previousTrack->invalidate();
  4140. }
  4141. }
  4142. }
  4143. mPreviousTrack = track;
  4144. // reset retry count
  4145. track->mRetryCount = kMaxTrackRetriesOffload;
  4146. mActiveTrack = t;
  4147. mixerStatus = MIXER_TRACKS_READY;
  4148. }
  4149. } else {
  4150. ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
  4151. if (track->isStopping_1()) {
  4152. // Hardware buffer can hold a large amount of audio so we must
  4153. // wait for all current track's data to drain before we say
  4154. // that the track is stopped.
  4155. if (mBytesRemaining == 0) {
  4156. // Only start draining when all data in mixbuffer
  4157. // has been written
  4158. ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
  4159. track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
  4160. // do not drain if no data was ever sent to HAL (mStandby == true)
  4161. if (last && !mStandby) {
  4162. // do not modify drain sequence if we are already draining. This happens
  4163. // when resuming from pause after drain.
  4164. if ((mDrainSequence & 1) == 0) {
  4165. sleepTime = 0;
  4166. standbyTime = systemTime() + standbyDelay;
  4167. mixerStatus = MIXER_DRAIN_TRACK;
  4168. mDrainSequence += 2;
  4169. }
  4170. if (mHwPaused) {
  4171. // It is possible to move from PAUSED to STOPPING_1 without
  4172. // a resume so we must ensure hardware is running
  4173. doHwResume = true;
  4174. mHwPaused = false;
  4175. }
  4176. }
  4177. }
  4178. } else if (track->isStopping_2()) {
  4179. // Drain has completed or we are in standby, signal presentation complete
  4180. if (!(mDrainSequence & 1) || !last || mStandby) {
  4181. track->mState = TrackBase::STOPPED;
  4182. size_t audioHALFrames =
  4183. (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
  4184. size_t framesWritten =
  4185. mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
  4186. track->presentationComplete(framesWritten, audioHALFrames);
  4187. track->reset();
  4188. tracksToRemove->add(track);
  4189. }
  4190. } else {
  4191. // No buffers for this track. Give it a few chances to
  4192. // fill a buffer, then remove it from active list.
  4193. if (--(track->mRetryCount) <= 0) {
  4194. ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
  4195. track->name());
  4196. tracksToRemove->add(track);
  4197. // indicate to client process that the track was disabled because of underrun;
  4198. // it will then automatically call start() when data is available
  4199. android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
  4200. } else if (last){
  4201. mixerStatus = MIXER_TRACKS_ENABLED;
  4202. }
  4203. }
  4204. }
  4205. // compute volume for this track
  4206. processVolume_l(track, last);
  4207. }
  4208. // make sure the pause/flush/resume sequence is executed in the right order.
  4209. // If a flush is pending and a track is active but the HW is not paused, force a HW pause
  4210. // before flush and then resume HW. This can happen in case of pause/flush/resume
  4211. // if resume is received before pause is executed.
  4212. if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
  4213. mOutput->stream->pause(mOutput->stream);
  4214. }
  4215. if (mFlushPending) {
  4216. flushHw_l();
  4217. mFlushPending = false;
  4218. }
  4219. if (!mStandby && doHwResume) {
  4220. mOutput->stream->resume(mOutput->stream);
  4221. }
  4222. // remove all the tracks that need to be...
  4223. removeTracks_l(*tracksToRemove);
  4224. return mixerStatus;
  4225. }
  4226. // must be called with thread mutex locked
  4227. bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
  4228. {
  4229. ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
  4230. mWriteAckSequence, mDrainSequence);
  4231. if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
  4232. return true;
  4233. }
  4234. return false;
  4235. }
  4236. bool AudioFlinger::OffloadThread::waitingAsyncCallback()
  4237. {
  4238. Mutex::Autolock _l(mLock);
  4239. return waitingAsyncCallback_l();
  4240. }
  4241. void AudioFlinger::OffloadThread::flushHw_l()
  4242. {
  4243. DirectOutputThread::flushHw_l();
  4244. // Flush anything still waiting in the mixbuffer
  4245. mCurrentWriteLength = 0;
  4246. mBytesRemaining = 0;
  4247. mPausedWriteLength = 0;
  4248. mPausedBytesRemaining = 0;
  4249. if (mUseAsyncWrite) {
  4250. // discard any pending drain or write ack by incrementing sequence
  4251. mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
  4252. mDrainSequence = (mDrainSequence + 2) & ~1;
  4253. ALOG_ASSERT(mCallbackThread != 0);
  4254. mCallbackThread->setWriteBlocked(mWriteAckSequence);
  4255. mCallbackThread->setDraining(mDrainSequence);
  4256. }
  4257. }
  4258. void AudioFlinger::OffloadThread::onAddNewTrack_l()
  4259. {
  4260. sp<Track> previousTrack = mPreviousTrack.promote();
  4261. sp<Track> latestTrack = mLatestActiveTrack.promote();
  4262. if (previousTrack != 0 && latestTrack != 0 &&
  4263. (previousTrack->sessionId() != latestTrack->sessionId())) {
  4264. mFlushPending = true;
  4265. }
  4266. PlaybackThread::onAddNewTrack_l();
  4267. }
  4268. // ----------------------------------------------------------------------------
  4269. AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
  4270. AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
  4271. : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
  4272. DUPLICATING),
  4273. mWaitTimeMs(UINT_MAX)
  4274. {
  4275. addOutputTrack(mainThread);
  4276. }
  4277. AudioFlinger::DuplicatingThread::~DuplicatingThread()
  4278. {
  4279. for (size_t i = 0; i < mOutputTracks.size(); i++) {
  4280. mOutputTracks[i]->destroy();
  4281. }
  4282. }
  4283. void AudioFlinger::DuplicatingThread::threadLoop_mix()
  4284. {
  4285. // mix buffers...
  4286. if (outputsReady(outputTracks)) {
  4287. mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
  4288. } else {
  4289. if (mMixerBufferValid) {
  4290. memset(mMixerBuffer, 0, mMixerBufferSize);
  4291. } else {
  4292. memset(mSinkBuffer, 0, mSinkBufferSize);
  4293. }
  4294. }
  4295. sleepTime = 0;
  4296. writeFrames = mNormalFrameCount;
  4297. mCurrentWriteLength = mSinkBufferSize;
  4298. standbyTime = systemTime() + standbyDelay;
  4299. }
  4300. void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
  4301. {
  4302. if (sleepTime == 0) {
  4303. if (mMixerStatus == MIXER_TRACKS_ENABLED) {
  4304. sleepTime = activeSleepTime;
  4305. } else {
  4306. sleepTime = idleSleepTime;
  4307. }
  4308. } else if (mBytesWritten != 0) {
  4309. if (mMixerStatus == MIXER_TRACKS_ENABLED) {
  4310. writeFrames = mNormalFrameCount;
  4311. memset(mSinkBuffer, 0, mSinkBufferSize);
  4312. } else {
  4313. // flush remaining overflow buffers in output tracks
  4314. writeFrames = 0;
  4315. }
  4316. sleepTime = 0;
  4317. }
  4318. }
  4319. ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
  4320. {
  4321. // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
  4322. // for delivery downstream as needed. This in-place conversion is safe as
  4323. // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
  4324. // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
  4325. if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
  4326. memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
  4327. mSinkBuffer, mFormat, writeFrames * mChannelCount);
  4328. }
  4329. for (size_t i = 0; i < outputTracks.size(); i++) {
  4330. outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
  4331. }
  4332. mStandby = false;
  4333. return (ssize_t)mSinkBufferSize;
  4334. }
  4335. void AudioFlinger::DuplicatingThread::threadLoop_standby()
  4336. {
  4337. // DuplicatingThread implements standby by stopping all tracks
  4338. for (size_t i = 0; i < outputTracks.size(); i++) {
  4339. outputTracks[i]->stop();
  4340. }
  4341. }
  4342. void AudioFlinger::DuplicatingThread::saveOutputTracks()
  4343. {
  4344. outputTracks = mOutputTracks;
  4345. }
  4346. void AudioFlinger::DuplicatingThread::clearOutputTracks()
  4347. {
  4348. outputTracks.clear();
  4349. }
  4350. void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
  4351. {
  4352. Mutex::Autolock _l(mLock);
  4353. // FIXME explain this formula
  4354. size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
  4355. // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
  4356. // due to current usage case and restrictions on the AudioBufferProvider.
  4357. // Actual buffer conversion is done in threadLoop_write().
  4358. //
  4359. // TODO: This may change in the future, depending on multichannel
  4360. // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
  4361. OutputTrack *outputTrack = new OutputTrack(thread,
  4362. this,
  4363. mSampleRate,
  4364. AUDIO_FORMAT_PCM_16_BIT,
  4365. mChannelMask,
  4366. frameCount,
  4367. IPCThreadState::self()->getCallingUid());
  4368. if (outputTrack->cblk() != NULL) {
  4369. thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
  4370. mOutputTracks.add(outputTrack);
  4371. ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
  4372. updateWaitTime_l();
  4373. }
  4374. }
  4375. void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
  4376. {
  4377. Mutex::Autolock _l(mLock);
  4378. for (size_t i = 0; i < mOutputTracks.size(); i++) {
  4379. if (mOutputTracks[i]->thread() == thread) {
  4380. mOutputTracks[i]->destroy();
  4381. mOutputTracks.removeAt(i);
  4382. updateWaitTime_l();
  4383. return;
  4384. }
  4385. }
  4386. ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
  4387. }
  4388. // caller must hold mLock
  4389. void AudioFlinger::DuplicatingThread::updateWaitTime_l()
  4390. {
  4391. mWaitTimeMs = UINT_MAX;
  4392. for (size_t i = 0; i < mOutputTracks.size(); i++) {
  4393. sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
  4394. if (strong != 0) {
  4395. uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
  4396. if (waitTimeMs < mWaitTimeMs) {
  4397. mWaitTimeMs = waitTimeMs;
  4398. }
  4399. }
  4400. }
  4401. }
  4402. bool AudioFlinger::DuplicatingThread::outputsReady(
  4403. const SortedVector< sp<OutputTrack> > &outputTracks)
  4404. {
  4405. for (size_t i = 0; i < outputTracks.size(); i++) {
  4406. sp<ThreadBase> thread = outputTracks[i]->thread().promote();
  4407. if (thread == 0) {
  4408. ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
  4409. outputTracks[i].get());
  4410. return false;
  4411. }
  4412. PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
  4413. // see note at standby() declaration
  4414. if (playbackThread->standby() && !playbackThread->isSuspended()) {
  4415. ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
  4416. thread.get());
  4417. return false;
  4418. }
  4419. }
  4420. return true;
  4421. }
  4422. uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
  4423. {
  4424. return (mWaitTimeMs * 1000) / 2;
  4425. }
  4426. void AudioFlinger::DuplicatingThread::cacheParameters_l()
  4427. {
  4428. // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
  4429. updateWaitTime_l();
  4430. MixerThread::cacheParameters_l();
  4431. }
  4432. // ----------------------------------------------------------------------------
  4433. // Record
  4434. // ----------------------------------------------------------------------------
  4435. AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
  4436. AudioStreamIn *input,
  4437. audio_io_handle_t id,
  4438. audio_devices_t outDevice,
  4439. audio_devices_t inDevice
  4440. #ifdef TEE_SINK
  4441. , const sp<NBAIO_Sink>& teeSink
  4442. #endif
  4443. ) :
  4444. ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
  4445. mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
  4446. // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
  4447. mRsmpInRear(0)
  4448. #ifdef TEE_SINK
  4449. , mTeeSink(teeSink)
  4450. #endif
  4451. , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
  4452. "RecordThreadRO", MemoryHeapBase::READ_ONLY))
  4453. // mFastCapture below
  4454. , mFastCaptureFutex(0)
  4455. // mInputSource
  4456. // mPipeSink
  4457. // mPipeSource
  4458. , mPipeFramesP2(0)
  4459. // mPipeMemory
  4460. // mFastCaptureNBLogWriter
  4461. , mFastTrackAvail(false)
  4462. {
  4463. snprintf(mName, kNameLength, "AudioIn_%X", id);
  4464. mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
  4465. readInputParameters_l();
  4466. // create an NBAIO source for the HAL input stream, and negotiate
  4467. mInputSource = new AudioStreamInSource(input->stream);
  4468. size_t numCounterOffers = 0;
  4469. const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
  4470. ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
  4471. ALOG_ASSERT(index == 0);
  4472. // initialize fast capture depending on configuration
  4473. bool initFastCapture;
  4474. switch (kUseFastCapture) {
  4475. case FastCapture_Never:
  4476. initFastCapture = false;
  4477. break;
  4478. case FastCapture_Always:
  4479. initFastCapture = true;
  4480. break;
  4481. case FastCapture_Static:
  4482. uint32_t primaryOutputSampleRate;
  4483. {
  4484. AutoMutex _l(audioFlinger->mHardwareLock);
  4485. primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
  4486. }
  4487. initFastCapture =
  4488. // either capture sample rate is same as (a reasonable) primary output sample rate
  4489. (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
  4490. (mSampleRate == primaryOutputSampleRate)) ||
  4491. // or primary output sample rate is unknown, and capture sample rate is reasonable
  4492. ((primaryOutputSampleRate == 0) &&
  4493. ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
  4494. // and the buffer size is < 12 ms
  4495. (mFrameCount * 1000) / mSampleRate < 12;
  4496. break;
  4497. // case FastCapture_Dynamic:
  4498. }
  4499. if (initFastCapture) {
  4500. // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
  4501. NBAIO_Format format = mInputSource->format();
  4502. size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
  4503. size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
  4504. void *pipeBuffer;
  4505. const sp<MemoryDealer> roHeap(readOnlyHeap());
  4506. sp<IMemory> pipeMemory;
  4507. if ((roHeap == 0) ||
  4508. (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
  4509. (pipeBuffer = pipeMemory->pointer()) == NULL) {
  4510. ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
  4511. goto failed;
  4512. }
  4513. // pipe will be shared directly with fast clients, so clear to avoid leaking old information
  4514. memset(pipeBuffer, 0, pipeSize);
  4515. Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
  4516. const NBAIO_Format offers[1] = {format};
  4517. size_t numCounterOffers = 0;
  4518. ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
  4519. ALOG_ASSERT(index == 0);
  4520. mPipeSink = pipe;
  4521. PipeReader *pipeReader = new PipeReader(*pipe);
  4522. numCounterOffers = 0;
  4523. index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
  4524. ALOG_ASSERT(index == 0);
  4525. mPipeSource = pipeReader;
  4526. mPipeFramesP2 = pipeFramesP2;
  4527. mPipeMemory = pipeMemory;
  4528. // create fast capture
  4529. mFastCapture = new FastCapture();
  4530. FastCaptureStateQueue *sq = mFastCapture->sq();
  4531. #ifdef STATE_QUEUE_DUMP
  4532. // FIXME
  4533. #endif
  4534. FastCaptureState *state = sq->begin();
  4535. state->mCblk = NULL;
  4536. state->mInputSource = mInputSource.get();
  4537. state->mInputSourceGen++;
  4538. state->mPipeSink = pipe;
  4539. state->mPipeSinkGen++;
  4540. state->mFrameCount = mFrameCount;
  4541. state->mCommand = FastCaptureState::COLD_IDLE;
  4542. // already done in constructor initialization list
  4543. //mFastCaptureFutex = 0;
  4544. state->mColdFutexAddr = &mFastCaptureFutex;
  4545. state->mColdGen++;
  4546. state->mDumpState = &mFastCaptureDumpState;
  4547. #ifdef TEE_SINK
  4548. // FIXME
  4549. #endif
  4550. mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
  4551. state->mNBLogWriter = mFastCaptureNBLogWriter.get();
  4552. sq->end();
  4553. sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
  4554. // start the fast capture
  4555. mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
  4556. pid_t tid = mFastCapture->getTid();
  4557. int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
  4558. if (err != 0) {
  4559. ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
  4560. kPriorityFastCapture, getpid_cached, tid, err);
  4561. }
  4562. #ifdef AUDIO_WATCHDOG
  4563. // FIXME
  4564. #endif
  4565. mFastTrackAvail = true;
  4566. }
  4567. failed: ;
  4568. // FIXME mNormalSource
  4569. }
  4570. AudioFlinger::RecordThread::~RecordThread()
  4571. {
  4572. if (mFastCapture != 0) {
  4573. FastCaptureStateQueue *sq = mFastCapture->sq();
  4574. FastCaptureState *state = sq->begin();
  4575. if (state->mCommand == FastCaptureState::COLD_IDLE) {
  4576. int32_t old = android_atomic_inc(&mFastCaptureFutex);
  4577. if (old == -1) {
  4578. (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
  4579. }
  4580. }
  4581. state->mCommand = FastCaptureState::EXIT;
  4582. sq->end();
  4583. sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
  4584. mFastCapture->join();
  4585. mFastCapture.clear();
  4586. }
  4587. mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
  4588. mAudioFlinger->unregisterWriter(mNBLogWriter);
  4589. delete[] mRsmpInBuffer;
  4590. }
  4591. void AudioFlinger::RecordThread::onFirstRef()
  4592. {
  4593. run(mName, PRIORITY_URGENT_AUDIO);
  4594. }
  4595. bool AudioFlinger::RecordThread::threadLoop()
  4596. {
  4597. nsecs_t lastWarning = 0;
  4598. inputStandBy();
  4599. reacquire_wakelock:
  4600. sp<RecordTrack> activeTrack;
  4601. int activeTracksGen;
  4602. {
  4603. Mutex::Autolock _l(mLock);
  4604. size_t size = mActiveTracks.size();
  4605. activeTracksGen = mActiveTracksGen;
  4606. if (size > 0) {
  4607. // FIXME an arbitrary choice
  4608. activeTrack = mActiveTracks[0];
  4609. acquireWakeLock_l(activeTrack->uid());
  4610. if (size > 1) {
  4611. SortedVector<int> tmp;
  4612. for (size_t i = 0; i < size; i++) {
  4613. tmp.add(mActiveTracks[i]->uid());
  4614. }
  4615. updateWakeLockUids_l(tmp);
  4616. }
  4617. } else {
  4618. acquireWakeLock_l(-1);
  4619. }
  4620. }
  4621. // used to request a deferred sleep, to be executed later while mutex is unlocked
  4622. uint32_t sleepUs = 0;
  4623. // loop while there is work to do
  4624. for (;;) {
  4625. Vector< sp<EffectChain> > effectChains;
  4626. // sleep with mutex unlocked
  4627. if (sleepUs > 0) {
  4628. usleep(sleepUs);
  4629. sleepUs = 0;
  4630. }
  4631. // activeTracks accumulates a copy of a subset of mActiveTracks
  4632. Vector< sp<RecordTrack> > activeTracks;
  4633. // reference to the (first and only) active fast track
  4634. sp<RecordTrack> fastTrack;
  4635. // reference to a fast track which is about to be removed
  4636. sp<RecordTrack> fastTrackToRemove;
  4637. { // scope for mLock
  4638. Mutex::Autolock _l(mLock);
  4639. processConfigEvents_l();
  4640. // check exitPending here because checkForNewParameters_l() and
  4641. // checkForNewParameters_l() can temporarily release mLock
  4642. if (exitPending()) {
  4643. break;
  4644. }
  4645. // if no active track(s), then standby and release wakelock
  4646. size_t size = mActiveTracks.size();
  4647. if (size == 0) {
  4648. standbyIfNotAlreadyInStandby();
  4649. // exitPending() can't become true here
  4650. releaseWakeLock_l();
  4651. ALOGV("RecordThread: loop stopping");
  4652. // go to sleep
  4653. mWaitWorkCV.wait(mLock);
  4654. ALOGV("RecordThread: loop starting");
  4655. goto reacquire_wakelock;
  4656. }
  4657. if (mActiveTracksGen != activeTracksGen) {
  4658. activeTracksGen = mActiveTracksGen;
  4659. SortedVector<int> tmp;
  4660. for (size_t i = 0; i < size; i++) {
  4661. tmp.add(mActiveTracks[i]->uid());
  4662. }
  4663. updateWakeLockUids_l(tmp);
  4664. }
  4665. bool doBroadcast = false;
  4666. for (size_t i = 0; i < size; ) {
  4667. activeTrack = mActiveTracks[i];
  4668. if (activeTrack->isTerminated()) {
  4669. if (activeTrack->isFastTrack()) {
  4670. ALOG_ASSERT(fastTrackToRemove == 0);
  4671. fastTrackToRemove = activeTrack;
  4672. }
  4673. removeTrack_l(activeTrack);
  4674. mActiveTracks.remove(activeTrack);
  4675. mActiveTracksGen++;
  4676. size--;
  4677. continue;
  4678. }
  4679. TrackBase::track_state activeTrackState = activeTrack->mState;
  4680. switch (activeTrackState) {
  4681. case TrackBase::PAUSING:
  4682. mActiveTracks.remove(activeTrack);
  4683. mActiveTracksGen++;
  4684. doBroadcast = true;
  4685. size--;
  4686. continue;
  4687. case TrackBase::STARTING_1:
  4688. sleepUs = 10000;
  4689. i++;
  4690. continue;
  4691. case TrackBase::STARTING_2:
  4692. doBroadcast = true;
  4693. mStandby = false;
  4694. activeTrack->mState = TrackBase::ACTIVE;
  4695. break;
  4696. case TrackBase::ACTIVE:
  4697. break;
  4698. case TrackBase::IDLE:
  4699. i++;
  4700. continue;
  4701. default:
  4702. LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
  4703. }
  4704. activeTracks.add(activeTrack);
  4705. i++;
  4706. if (activeTrack->isFastTrack()) {
  4707. ALOG_ASSERT(!mFastTrackAvail);
  4708. ALOG_ASSERT(fastTrack == 0);
  4709. fastTrack = activeTrack;
  4710. }
  4711. }
  4712. if (doBroadcast) {
  4713. mStartStopCond.broadcast();
  4714. }
  4715. // sleep if there are no active tracks to process
  4716. if (activeTracks.size() == 0) {
  4717. if (sleepUs == 0) {
  4718. sleepUs = kRecordThreadSleepUs;
  4719. }
  4720. continue;
  4721. }
  4722. sleepUs = 0;
  4723. lockEffectChains_l(effectChains);
  4724. }
  4725. // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
  4726. size_t size = effectChains.size();
  4727. for (size_t i = 0; i < size; i++) {
  4728. // thread mutex is not locked, but effect chain is locked
  4729. effectChains[i]->process_l();
  4730. }
  4731. // Push a new fast capture state if fast capture is not already running, or cblk change
  4732. if (mFastCapture != 0) {
  4733. FastCaptureStateQueue *sq = mFastCapture->sq();
  4734. FastCaptureState *state = sq->begin();
  4735. bool didModify = false;
  4736. FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
  4737. if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
  4738. (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
  4739. if (state->mCommand == FastCaptureState::COLD_IDLE) {
  4740. int32_t old = android_atomic_inc(&mFastCaptureFutex);
  4741. if (old == -1) {
  4742. (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
  4743. }
  4744. }
  4745. state->mCommand = FastCaptureState::READ_WRITE;
  4746. #if 0 // FIXME
  4747. mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
  4748. FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
  4749. #endif
  4750. didModify = true;
  4751. }
  4752. audio_track_cblk_t *cblkOld = state->mCblk;
  4753. audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
  4754. if (cblkNew != cblkOld) {
  4755. state->mCblk = cblkNew;
  4756. // block until acked if removing a fast track
  4757. if (cblkOld != NULL) {
  4758. block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
  4759. }
  4760. didModify = true;
  4761. }
  4762. sq->end(didModify);
  4763. if (didModify) {
  4764. sq->push(block);
  4765. #if 0
  4766. if (kUseFastCapture == FastCapture_Dynamic) {
  4767. mNormalSource = mPipeSource;
  4768. }
  4769. #endif
  4770. }
  4771. }
  4772. // now run the fast track destructor with thread mutex unlocked
  4773. fastTrackToRemove.clear();
  4774. // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
  4775. // Only the client(s) that are too slow will overrun. But if even the fastest client is too
  4776. // slow, then this RecordThread will overrun by not calling HAL read often enough.
  4777. // If destination is non-contiguous, first read past the nominal end of buffer, then
  4778. // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
  4779. int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
  4780. ssize_t framesRead;
  4781. // If an NBAIO source is present, use it to read the normal capture's data
  4782. if (mPipeSource != 0) {
  4783. size_t framesToRead = mBufferSize / mFrameSize;
  4784. framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
  4785. framesToRead, AudioBufferProvider::kInvalidPTS);
  4786. if (framesRead == 0) {
  4787. // since pipe is non-blocking, simulate blocking input
  4788. sleepUs = (framesToRead * 1000000LL) / mSampleRate;
  4789. }
  4790. // otherwise use the HAL / AudioStreamIn directly
  4791. } else {
  4792. ssize_t bytesRead = mInput->stream->read(mInput->stream,
  4793. &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
  4794. if (bytesRead < 0) {
  4795. framesRead = bytesRead;
  4796. } else {
  4797. framesRead = bytesRead / mFrameSize;
  4798. }
  4799. }
  4800. if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
  4801. ALOGE("read failed: framesRead=%d", framesRead);
  4802. // Force input into standby so that it tries to recover at next read attempt
  4803. inputStandBy();
  4804. sleepUs = kRecordThreadSleepUs;
  4805. }
  4806. if (framesRead <= 0) {
  4807. goto unlock;
  4808. }
  4809. ALOG_ASSERT(framesRead > 0);
  4810. if (mTeeSink != 0) {
  4811. (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
  4812. }
  4813. // If destination is non-contiguous, we now correct for reading past end of buffer.
  4814. {
  4815. size_t part1 = mRsmpInFramesP2 - rear;
  4816. if ((size_t) framesRead > part1) {
  4817. memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
  4818. (framesRead - part1) * mFrameSize);
  4819. }
  4820. }
  4821. rear = mRsmpInRear += framesRead;
  4822. size = activeTracks.size();
  4823. // loop over each active track
  4824. for (size_t i = 0; i < size; i++) {
  4825. activeTrack = activeTracks[i];
  4826. // skip fast tracks, as those are handled directly by FastCapture
  4827. if (activeTrack->isFastTrack()) {
  4828. continue;
  4829. }
  4830. enum {
  4831. OVERRUN_UNKNOWN,
  4832. OVERRUN_TRUE,
  4833. OVERRUN_FALSE
  4834. } overrun = OVERRUN_UNKNOWN;
  4835. // loop over getNextBuffer to handle circular sink
  4836. for (;;) {
  4837. activeTrack->mSink.frameCount = ~0;
  4838. status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
  4839. size_t framesOut = activeTrack->mSink.frameCount;
  4840. LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
  4841. int32_t front = activeTrack->mRsmpInFront;
  4842. ssize_t filled = rear - front;
  4843. size_t framesIn;
  4844. if (filled < 0) {
  4845. // should not happen, but treat like a massive overrun and re-sync
  4846. framesIn = 0;
  4847. activeTrack->mRsmpInFront = rear;
  4848. overrun = OVERRUN_TRUE;
  4849. } else if ((size_t) filled <= mRsmpInFrames) {
  4850. framesIn = (size_t) filled;
  4851. } else {
  4852. // client is not keeping up with server, but give it latest data
  4853. framesIn = mRsmpInFrames;
  4854. activeTrack->mRsmpInFront = front = rear - framesIn;
  4855. overrun = OVERRUN_TRUE;
  4856. }
  4857. if (framesOut == 0 || framesIn == 0) {
  4858. break;
  4859. }
  4860. if (activeTrack->mResampler == NULL) {
  4861. // no resampling
  4862. if (framesIn > framesOut) {
  4863. framesIn = framesOut;
  4864. } else {
  4865. framesOut = framesIn;
  4866. }
  4867. int8_t *dst = activeTrack->mSink.i8;
  4868. while (framesIn > 0) {
  4869. front &= mRsmpInFramesP2 - 1;
  4870. size_t part1 = mRsmpInFramesP2 - front;
  4871. if (part1 > framesIn) {
  4872. part1 = framesIn;
  4873. }
  4874. int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
  4875. if (mChannelCount == activeTrack->mChannelCount) {
  4876. memcpy(dst, src, part1 * mFrameSize);
  4877. } else if (mChannelCount == 1) {
  4878. upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
  4879. part1);
  4880. } else {
  4881. downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
  4882. part1);
  4883. }
  4884. dst += part1 * activeTrack->mFrameSize;
  4885. front += part1;
  4886. framesIn -= part1;
  4887. }
  4888. activeTrack->mRsmpInFront += framesOut;
  4889. } else {
  4890. // resampling
  4891. // FIXME framesInNeeded should really be part of resampler API, and should
  4892. // depend on the SRC ratio
  4893. // to keep mRsmpInBuffer full so resampler always has sufficient input
  4894. size_t framesInNeeded;
  4895. // FIXME only re-calculate when it changes, and optimize for common ratios
  4896. // Do not precompute in/out because floating point is not associative
  4897. // e.g. a*b/c != a*(b/c).
  4898. const double in(mSampleRate);
  4899. const double out(activeTrack->mSampleRate);
  4900. framesInNeeded = ceil(framesOut * in / out) + 1;
  4901. ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
  4902. framesInNeeded, framesOut, in / out);
  4903. // Although we theoretically have framesIn in circular buffer, some of those are
  4904. // unreleased frames, and thus must be discounted for purpose of budgeting.
  4905. size_t unreleased = activeTrack->mRsmpInUnrel;
  4906. framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
  4907. if (framesIn < framesInNeeded) {
  4908. ALOGV("not enough to resample: have %u frames in but need %u in to "
  4909. "produce %u out given in/out ratio of %.4g",
  4910. framesIn, framesInNeeded, framesOut, in / out);
  4911. size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
  4912. LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
  4913. if (newFramesOut == 0) {
  4914. break;
  4915. }
  4916. framesInNeeded = ceil(newFramesOut * in / out) + 1;
  4917. ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
  4918. framesInNeeded, newFramesOut, out / in);
  4919. LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
  4920. ALOGV("success 2: have %u frames in and need %u in to produce %u out "
  4921. "given in/out ratio of %.4g",
  4922. framesIn, framesInNeeded, newFramesOut, in / out);
  4923. framesOut = newFramesOut;
  4924. } else {
  4925. ALOGV("success 1: have %u in and need %u in to produce %u out "
  4926. "given in/out ratio of %.4g",
  4927. framesIn, framesInNeeded, framesOut, in / out);
  4928. }
  4929. // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
  4930. if (activeTrack->mRsmpOutFrameCount < framesOut) {
  4931. // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
  4932. delete[] activeTrack->mRsmpOutBuffer;
  4933. // resampler always outputs stereo
  4934. activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
  4935. activeTrack->mRsmpOutFrameCount = framesOut;
  4936. }
  4937. // resampler accumulates, but we only have one source track
  4938. memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
  4939. activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
  4940. // FIXME how about having activeTrack implement this interface itself?
  4941. activeTrack->mResamplerBufferProvider
  4942. /*this*/ /* AudioBufferProvider* */);
  4943. // ditherAndClamp() works as long as all buffers returned by
  4944. // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
  4945. if (activeTrack->mChannelCount == 1) {
  4946. // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
  4947. ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
  4948. framesOut);
  4949. // the resampler always outputs stereo samples:
  4950. // do post stereo to mono conversion
  4951. downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
  4952. (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
  4953. } else {
  4954. ditherAndClamp((int32_t *)activeTrack->mSink.raw,
  4955. activeTrack->mRsmpOutBuffer, framesOut);
  4956. }
  4957. // now done with mRsmpOutBuffer
  4958. }
  4959. if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
  4960. overrun = OVERRUN_FALSE;
  4961. }
  4962. if (activeTrack->mFramesToDrop == 0) {
  4963. if (framesOut > 0) {
  4964. activeTrack->mSink.frameCount = framesOut;
  4965. activeTrack->releaseBuffer(&activeTrack->mSink);
  4966. }
  4967. } else {
  4968. // FIXME could do a partial drop of framesOut
  4969. if (activeTrack->mFramesToDrop > 0) {
  4970. activeTrack->mFramesToDrop -= framesOut;
  4971. if (activeTrack->mFramesToDrop <= 0) {
  4972. activeTrack->clearSyncStartEvent();
  4973. }
  4974. } else {
  4975. activeTrack->mFramesToDrop += framesOut;
  4976. if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
  4977. activeTrack->mSyncStartEvent->isCancelled()) {
  4978. ALOGW("Synced record %s, session %d, trigger session %d",
  4979. (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
  4980. activeTrack->sessionId(),
  4981. (activeTrack->mSyncStartEvent != 0) ?
  4982. activeTrack->mSyncStartEvent->triggerSession() : 0);
  4983. activeTrack->clearSyncStartEvent();
  4984. }
  4985. }
  4986. }
  4987. if (framesOut == 0) {
  4988. break;
  4989. }
  4990. }
  4991. switch (overrun) {
  4992. case OVERRUN_TRUE:
  4993. // client isn't retrieving buffers fast enough
  4994. if (!activeTrack->setOverflow()) {
  4995. nsecs_t now = systemTime();
  4996. // FIXME should lastWarning per track?
  4997. if ((now - lastWarning) > kWarningThrottleNs) {
  4998. ALOGW("RecordThread: buffer overflow");
  4999. lastWarning = now;
  5000. }
  5001. }
  5002. break;
  5003. case OVERRUN_FALSE:
  5004. activeTrack->clearOverflow();
  5005. break;
  5006. case OVERRUN_UNKNOWN:
  5007. break;
  5008. }
  5009. }
  5010. unlock:
  5011. // enable changes in effect chain
  5012. unlockEffectChains(effectChains);
  5013. // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
  5014. }
  5015. standbyIfNotAlreadyInStandby();
  5016. {
  5017. Mutex::Autolock _l(mLock);
  5018. for (size_t i = 0; i < mTracks.size(); i++) {
  5019. sp<RecordTrack> track = mTracks[i];
  5020. track->invalidate();
  5021. }
  5022. mActiveTracks.clear();
  5023. mActiveTracksGen++;
  5024. mStartStopCond.broadcast();
  5025. }
  5026. releaseWakeLock();
  5027. ALOGV("RecordThread %p exiting", this);
  5028. return false;
  5029. }
  5030. void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
  5031. {
  5032. if (!mStandby) {
  5033. inputStandBy();
  5034. mStandby = true;
  5035. }
  5036. }
  5037. void AudioFlinger::RecordThread::inputStandBy()
  5038. {
  5039. // Idle the fast capture if it's currently running
  5040. if (mFastCapture != 0) {
  5041. FastCaptureStateQueue *sq = mFastCapture->sq();
  5042. FastCaptureState *state = sq->begin();
  5043. if (!(state->mCommand & FastCaptureState::IDLE)) {
  5044. state->mCommand = FastCaptureState::COLD_IDLE;
  5045. state->mColdFutexAddr = &mFastCaptureFutex;
  5046. state->mColdGen++;
  5047. mFastCaptureFutex = 0;
  5048. sq->end();
  5049. // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
  5050. sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
  5051. #if 0
  5052. if (kUseFastCapture == FastCapture_Dynamic) {
  5053. // FIXME
  5054. }
  5055. #endif
  5056. #ifdef AUDIO_WATCHDOG
  5057. // FIXME
  5058. #endif
  5059. } else {
  5060. sq->end(false /*didModify*/);
  5061. }
  5062. }
  5063. mInput->stream->common.standby(&mInput->stream->common);
  5064. }
  5065. // RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
  5066. sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
  5067. const sp<AudioFlinger::Client>& client,
  5068. uint32_t sampleRate,
  5069. audio_format_t format,
  5070. audio_channel_mask_t channelMask,
  5071. size_t *pFrameCount,
  5072. int sessionId,
  5073. size_t *notificationFrames,
  5074. int uid,
  5075. IAudioFlinger::track_flags_t *flags,
  5076. pid_t tid,
  5077. status_t *status)
  5078. {
  5079. size_t frameCount = *pFrameCount;
  5080. sp<RecordTrack> track;
  5081. status_t lStatus;
  5082. // client expresses a preference for FAST, but we get the final say
  5083. if (*flags & IAudioFlinger::TRACK_FAST) {
  5084. if (
  5085. // use case: callback handler
  5086. (tid != -1) &&
  5087. // frame count is not specified, or is exactly the pipe depth
  5088. ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
  5089. // PCM data
  5090. audio_is_linear_pcm(format) &&
  5091. // native format
  5092. (format == mFormat) &&
  5093. // native channel mask
  5094. (channelMask == mChannelMask) &&
  5095. // native hardware sample rate
  5096. (sampleRate == mSampleRate) &&
  5097. // record thread has an associated fast capture
  5098. hasFastCapture() &&
  5099. // there are sufficient fast track slots available
  5100. mFastTrackAvail
  5101. ) {
  5102. ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
  5103. frameCount, mFrameCount);
  5104. } else {
  5105. ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
  5106. "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
  5107. "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
  5108. frameCount, mFrameCount, mPipeFramesP2,
  5109. format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
  5110. hasFastCapture(), tid, mFastTrackAvail);
  5111. *flags &= ~IAudioFlinger::TRACK_FAST;
  5112. }
  5113. }
  5114. // compute track buffer size in frames, and suggest the notification frame count
  5115. if (*flags & IAudioFlinger::TRACK_FAST) {
  5116. // fast track: frame count is exactly the pipe depth
  5117. frameCount = mPipeFramesP2;
  5118. // ignore requested notificationFrames, and always notify exactly once every HAL buffer
  5119. *notificationFrames = mFrameCount;
  5120. } else {
  5121. // not fast track: max notification period is resampled equivalent of one HAL buffer time
  5122. // or 20 ms if there is a fast capture
  5123. // TODO This could be a roundupRatio inline, and const
  5124. size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
  5125. * sampleRate + mSampleRate - 1) / mSampleRate;
  5126. // minimum number of notification periods is at least kMinNotifications,
  5127. // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
  5128. static const size_t kMinNotifications = 3;
  5129. static const uint32_t kMinMs = 30;
  5130. // TODO This could be a roundupRatio inline
  5131. const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
  5132. // TODO This could be a roundupRatio inline
  5133. const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
  5134. maxNotificationFrames;
  5135. const size_t minFrameCount = maxNotificationFrames *
  5136. max(kMinNotifications, minNotificationsByMs);
  5137. frameCount = max(frameCount, minFrameCount);
  5138. if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
  5139. *notificationFrames = maxNotificationFrames;
  5140. }
  5141. }
  5142. *pFrameCount = frameCount;
  5143. lStatus = initCheck();
  5144. if (lStatus != NO_ERROR) {
  5145. ALOGE("createRecordTrack_l() audio driver not initialized");
  5146. goto Exit;
  5147. }
  5148. { // scope for mLock
  5149. Mutex::Autolock _l(mLock);
  5150. track = new RecordTrack(this, client, sampleRate,
  5151. format, channelMask, frameCount, NULL, sessionId, uid,
  5152. *flags, TrackBase::TYPE_DEFAULT);
  5153. lStatus = track->initCheck();
  5154. if (lStatus != NO_ERROR) {
  5155. ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
  5156. // track must be cleared from the caller as the caller has the AF lock
  5157. goto Exit;
  5158. }
  5159. mTracks.add(track);
  5160. // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
  5161. bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
  5162. mAudioFlinger->btNrecIsOff();
  5163. setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
  5164. setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
  5165. if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
  5166. pid_t callingPid = IPCThreadState::self()->getCallingPid();
  5167. // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
  5168. // so ask activity manager to do this on our behalf
  5169. sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
  5170. }
  5171. }
  5172. lStatus = NO_ERROR;
  5173. Exit:
  5174. *status = lStatus;
  5175. return track;
  5176. }
  5177. status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
  5178. AudioSystem::sync_event_t event,
  5179. int triggerSession)
  5180. {
  5181. ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
  5182. sp<ThreadBase> strongMe = this;
  5183. status_t status = NO_ERROR;
  5184. if (event == AudioSystem::SYNC_EVENT_NONE) {
  5185. recordTrack->clearSyncStartEvent();
  5186. } else if (event != AudioSystem::SYNC_EVENT_SAME) {
  5187. recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
  5188. triggerSession,
  5189. recordTrack->sessionId(),
  5190. syncStartEventCallback,
  5191. recordTrack);
  5192. // Sync event can be cancelled by the trigger session if the track is not in a
  5193. // compatible state in which case we start record immediately
  5194. if (recordTrack->mSyncStartEvent->isCancelled()) {
  5195. recordTrack->clearSyncStartEvent();
  5196. } else {
  5197. // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
  5198. recordTrack->mFramesToDrop = -
  5199. ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
  5200. }
  5201. }
  5202. {
  5203. // This section is a rendezvous between binder thread executing start() and RecordThread
  5204. AutoMutex lock(mLock);
  5205. if (mActiveTracks.indexOf(recordTrack) >= 0) {
  5206. if (recordTrack->mState == TrackBase::PAUSING) {
  5207. ALOGV("active record track PAUSING -> ACTIVE");
  5208. recordTrack->mState = TrackBase::ACTIVE;
  5209. } else {
  5210. ALOGV("active record track state %d", recordTrack->mState);
  5211. }
  5212. return status;
  5213. }
  5214. // TODO consider other ways of handling this, such as changing the state to :STARTING and
  5215. // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
  5216. // or using a separate command thread
  5217. recordTrack->mState = TrackBase::STARTING_1;
  5218. mActiveTracks.add(recordTrack);
  5219. mActiveTracksGen++;
  5220. status_t status = NO_ERROR;
  5221. if (recordTrack->isExternalTrack()) {
  5222. mLock.unlock();
  5223. status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
  5224. mLock.lock();
  5225. // FIXME should verify that recordTrack is still in mActiveTracks
  5226. if (status != NO_ERROR) {
  5227. mActiveTracks.remove(recordTrack);
  5228. mActiveTracksGen++;
  5229. recordTrack->clearSyncStartEvent();
  5230. ALOGV("RecordThread::start error %d", status);
  5231. return status;
  5232. }
  5233. }
  5234. // Catch up with current buffer indices if thread is already running.
  5235. // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
  5236. // was initialized to some value closer to the thread's mRsmpInFront, then the track could
  5237. // see previously buffered data before it called start(), but with greater risk of overrun.
  5238. recordTrack->mRsmpInFront = mRsmpInRear;
  5239. recordTrack->mRsmpInUnrel = 0;
  5240. // FIXME why reset?
  5241. if (recordTrack->mResampler != NULL) {
  5242. recordTrack->mResampler->reset();
  5243. }
  5244. recordTrack->mState = TrackBase::STARTING_2;
  5245. // signal thread to start
  5246. mWaitWorkCV.broadcast();
  5247. if (mActiveTracks.indexOf(recordTrack) < 0) {
  5248. ALOGV("Record failed to start");
  5249. status = BAD_VALUE;
  5250. goto startError;
  5251. }
  5252. return status;
  5253. }
  5254. startError:
  5255. if (recordTrack->isExternalTrack()) {
  5256. AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
  5257. }
  5258. recordTrack->clearSyncStartEvent();
  5259. // FIXME I wonder why we do not reset the state here?
  5260. return status;
  5261. }
  5262. void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
  5263. {
  5264. sp<SyncEvent> strongEvent = event.promote();
  5265. if (strongEvent != 0) {
  5266. sp<RefBase> ptr = strongEvent->cookie().promote();
  5267. if (ptr != 0) {
  5268. RecordTrack *recordTrack = (RecordTrack *)ptr.get();
  5269. recordTrack->handleSyncStartEvent(strongEvent);
  5270. }
  5271. }
  5272. }
  5273. bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
  5274. ALOGV("RecordThread::stop");
  5275. AutoMutex _l(mLock);
  5276. if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
  5277. return false;
  5278. }
  5279. // note that threadLoop may still be processing the track at this point [without lock]
  5280. recordTrack->mState = TrackBase::PAUSING;
  5281. // do not wait for mStartStopCond if exiting
  5282. if (exitPending()) {
  5283. return true;
  5284. }
  5285. // FIXME incorrect usage of wait: no explicit predicate or loop
  5286. mStartStopCond.wait(mLock);
  5287. // if we have been restarted, recordTrack is in mActiveTracks here
  5288. if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
  5289. ALOGV("Record stopped OK");
  5290. return true;
  5291. }
  5292. return false;
  5293. }
  5294. bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
  5295. {
  5296. return false;
  5297. }
  5298. status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
  5299. {
  5300. #if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
  5301. if (!isValidSyncEvent(event)) {
  5302. return BAD_VALUE;
  5303. }
  5304. int eventSession = event->triggerSession();
  5305. status_t ret = NAME_NOT_FOUND;
  5306. Mutex::Autolock _l(mLock);
  5307. for (size_t i = 0; i < mTracks.size(); i++) {
  5308. sp<RecordTrack> track = mTracks[i];
  5309. if (eventSession == track->sessionId()) {
  5310. (void) track->setSyncEvent(event);
  5311. ret = NO_ERROR;
  5312. }
  5313. }
  5314. return ret;
  5315. #else
  5316. return BAD_VALUE;
  5317. #endif
  5318. }
  5319. // destroyTrack_l() must be called with ThreadBase::mLock held
  5320. void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
  5321. {
  5322. track->terminate();
  5323. track->mState = TrackBase::STOPPED;
  5324. // active tracks are removed by threadLoop()
  5325. if (mActiveTracks.indexOf(track) < 0) {
  5326. removeTrack_l(track);
  5327. }
  5328. }
  5329. void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
  5330. {
  5331. mTracks.remove(track);
  5332. // need anything related to effects here?
  5333. if (track->isFastTrack()) {
  5334. ALOG_ASSERT(!mFastTrackAvail);
  5335. mFastTrackAvail = true;
  5336. }
  5337. }
  5338. void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
  5339. {
  5340. dumpInternals(fd, args);
  5341. dumpTracks(fd, args);
  5342. dumpEffectChains(fd, args);
  5343. }
  5344. void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
  5345. {
  5346. dprintf(fd, "\nInput thread %p:\n", this);
  5347. if (mActiveTracks.size() > 0) {
  5348. dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
  5349. } else {
  5350. dprintf(fd, " No active record clients\n");
  5351. }
  5352. dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
  5353. dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
  5354. dumpBase(fd, args);
  5355. }
  5356. void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
  5357. {
  5358. const size_t SIZE = 256;
  5359. char buffer[SIZE];
  5360. String8 result;
  5361. size_t numtracks = mTracks.size();
  5362. size_t numactive = mActiveTracks.size();
  5363. size_t numactiveseen = 0;
  5364. dprintf(fd, " %d Tracks", numtracks);
  5365. if (numtracks) {
  5366. dprintf(fd, " of which %d are active\n", numactive);
  5367. RecordTrack::appendDumpHeader(result);
  5368. for (size_t i = 0; i < numtracks ; ++i) {
  5369. sp<RecordTrack> track = mTracks[i];
  5370. if (track != 0) {
  5371. bool active = mActiveTracks.indexOf(track) >= 0;
  5372. if (active) {
  5373. numactiveseen++;
  5374. }
  5375. track->dump(buffer, SIZE, active);
  5376. result.append(buffer);
  5377. }
  5378. }
  5379. } else {
  5380. dprintf(fd, "\n");
  5381. }
  5382. if (numactiveseen != numactive) {
  5383. snprintf(buffer, SIZE, " The following tracks are in the active list but"
  5384. " not in the track list\n");
  5385. result.append(buffer);
  5386. RecordTrack::appendDumpHeader(result);
  5387. for (size_t i = 0; i < numactive; ++i) {
  5388. sp<RecordTrack> track = mActiveTracks[i];
  5389. if (mTracks.indexOf(track) < 0) {
  5390. track->dump(buffer, SIZE, true);
  5391. result.append(buffer);
  5392. }
  5393. }
  5394. }
  5395. write(fd, result.string(), result.size());
  5396. }
  5397. // AudioBufferProvider interface
  5398. status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
  5399. AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
  5400. {
  5401. RecordTrack *activeTrack = mRecordTrack;
  5402. sp<ThreadBase> threadBase = activeTrack->mThread.promote();
  5403. if (threadBase == 0) {
  5404. buffer->frameCount = 0;
  5405. buffer->raw = NULL;
  5406. return NOT_ENOUGH_DATA;
  5407. }
  5408. RecordThread *recordThread = (RecordThread *) threadBase.get();
  5409. int32_t rear = recordThread->mRsmpInRear;
  5410. int32_t front = activeTrack->mRsmpInFront;
  5411. ssize_t filled = rear - front;
  5412. // FIXME should not be P2 (don't want to increase latency)
  5413. // FIXME if client not keeping up, discard
  5414. LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
  5415. // 'filled' may be non-contiguous, so return only the first contiguous chunk
  5416. front &= recordThread->mRsmpInFramesP2 - 1;
  5417. size_t part1 = recordThread->mRsmpInFramesP2 - front;
  5418. if (part1 > (size_t) filled) {
  5419. part1 = filled;
  5420. }
  5421. size_t ask = buffer->frameCount;
  5422. ALOG_ASSERT(ask > 0);
  5423. if (part1 > ask) {
  5424. part1 = ask;
  5425. }
  5426. if (part1 == 0) {
  5427. // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
  5428. LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
  5429. buffer->raw = NULL;
  5430. buffer->frameCount = 0;
  5431. activeTrack->mRsmpInUnrel = 0;
  5432. return NOT_ENOUGH_DATA;
  5433. }
  5434. buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
  5435. buffer->frameCount = part1;
  5436. activeTrack->mRsmpInUnrel = part1;
  5437. return NO_ERROR;
  5438. }
  5439. // AudioBufferProvider interface
  5440. void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
  5441. AudioBufferProvider::Buffer* buffer)
  5442. {
  5443. RecordTrack *activeTrack = mRecordTrack;
  5444. size_t stepCount = buffer->frameCount;
  5445. if (stepCount == 0) {
  5446. return;
  5447. }
  5448. ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
  5449. activeTrack->mRsmpInUnrel -= stepCount;
  5450. activeTrack->mRsmpInFront += stepCount;
  5451. buffer->raw = NULL;
  5452. buffer->frameCount = 0;
  5453. }
  5454. bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
  5455. status_t& status)
  5456. {
  5457. bool reconfig = false;
  5458. status = NO_ERROR;
  5459. audio_format_t reqFormat = mFormat;
  5460. uint32_t samplingRate = mSampleRate;
  5461. audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
  5462. AudioParameter param = AudioParameter(keyValuePair);
  5463. int value;
  5464. // TODO Investigate when this code runs. Check with audio policy when a sample rate and
  5465. // channel count change can be requested. Do we mandate the first client defines the
  5466. // HAL sampling rate and channel count or do we allow changes on the fly?
  5467. if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
  5468. samplingRate = value;
  5469. reconfig = true;
  5470. }
  5471. if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
  5472. if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
  5473. status = BAD_VALUE;
  5474. } else {
  5475. reqFormat = (audio_format_t) value;
  5476. reconfig = true;
  5477. }
  5478. }
  5479. if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
  5480. audio_channel_mask_t mask = (audio_channel_mask_t) value;
  5481. if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
  5482. status = BAD_VALUE;
  5483. } else {
  5484. channelMask = mask;
  5485. reconfig = true;
  5486. }
  5487. }
  5488. if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
  5489. // do not accept frame count changes if tracks are open as the track buffer
  5490. // size depends on frame count and correct behavior would not be guaranteed
  5491. // if frame count is changed after track creation
  5492. if (mActiveTracks.size() > 0) {
  5493. status = INVALID_OPERATION;
  5494. } else {
  5495. reconfig = true;
  5496. }
  5497. }
  5498. if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
  5499. // forward device change to effects that have requested to be
  5500. // aware of attached audio device.
  5501. for (size_t i = 0; i < mEffectChains.size(); i++) {
  5502. mEffectChains[i]->setDevice_l(value);
  5503. }
  5504. // store input device and output device but do not forward output device to audio HAL.
  5505. // Note that status is ignored by the caller for output device
  5506. // (see AudioFlinger::setParameters()
  5507. if (audio_is_output_devices(value)) {
  5508. mOutDevice = value;
  5509. status = BAD_VALUE;
  5510. } else {
  5511. mInDevice = value;
  5512. // disable AEC and NS if the device is a BT SCO headset supporting those
  5513. // pre processings
  5514. if (mTracks.size() > 0) {
  5515. bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
  5516. mAudioFlinger->btNrecIsOff();
  5517. for (size_t i = 0; i < mTracks.size(); i++) {
  5518. sp<RecordTrack> track = mTracks[i];
  5519. setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
  5520. setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
  5521. }
  5522. }
  5523. }
  5524. }
  5525. if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
  5526. mAudioSource != (audio_source_t)value) {
  5527. // forward device change to effects that have requested to be
  5528. // aware of attached audio device.
  5529. for (size_t i = 0; i < mEffectChains.size(); i++) {
  5530. mEffectChains[i]->setAudioSource_l((audio_source_t)value);
  5531. }
  5532. mAudioSource = (audio_source_t)value;
  5533. }
  5534. if (status == NO_ERROR) {
  5535. status = mInput->stream->common.set_parameters(&mInput->stream->common,
  5536. keyValuePair.string());
  5537. if (status == INVALID_OPERATION) {
  5538. inputStandBy();
  5539. status = mInput->stream->common.set_parameters(&mInput->stream->common,
  5540. keyValuePair.string());
  5541. }
  5542. if (reconfig) {
  5543. if (status == BAD_VALUE &&
  5544. reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
  5545. reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
  5546. (mInput->stream->common.get_sample_rate(&mInput->stream->common)
  5547. <= (2 * samplingRate)) &&
  5548. audio_channel_count_from_in_mask(
  5549. mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
  5550. (channelMask == AUDIO_CHANNEL_IN_MONO ||
  5551. channelMask == AUDIO_CHANNEL_IN_STEREO)) {
  5552. status = NO_ERROR;
  5553. }
  5554. if (status == NO_ERROR) {
  5555. readInputParameters_l();
  5556. sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
  5557. }
  5558. }
  5559. }
  5560. return reconfig;
  5561. }
  5562. String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
  5563. {
  5564. Mutex::Autolock _l(mLock);
  5565. if (initCheck() != NO_ERROR) {
  5566. return String8();
  5567. }
  5568. char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
  5569. const String8 out_s8(s);
  5570. free(s);
  5571. return out_s8;
  5572. }
  5573. void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
  5574. AudioSystem::OutputDescriptor desc;
  5575. const void *param2 = NULL;
  5576. switch (event) {
  5577. case AudioSystem::INPUT_OPENED:
  5578. case AudioSystem::INPUT_CONFIG_CHANGED:
  5579. desc.channelMask = mChannelMask;
  5580. desc.samplingRate = mSampleRate;
  5581. desc.format = mFormat;
  5582. desc.frameCount = mFrameCount;
  5583. desc.latency = 0;
  5584. param2 = &desc;
  5585. break;
  5586. case AudioSystem::INPUT_CLOSED:
  5587. default:
  5588. break;
  5589. }
  5590. mAudioFlinger->audioConfigChanged(event, mId, param2);
  5591. }
  5592. void AudioFlinger::RecordThread::readInputParameters_l()
  5593. {
  5594. mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
  5595. mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
  5596. mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
  5597. mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
  5598. mFormat = mHALFormat;
  5599. if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
  5600. ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
  5601. }
  5602. mFrameSize = audio_stream_in_frame_size(mInput->stream);
  5603. mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
  5604. mFrameCount = mBufferSize / mFrameSize;
  5605. // This is the formula for calculating the temporary buffer size.
  5606. // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
  5607. // 1 full output buffer, regardless of the alignment of the available input.
  5608. // The value is somewhat arbitrary, and could probably be even larger.
  5609. // A larger value should allow more old data to be read after a track calls start(),
  5610. // without increasing latency.
  5611. mRsmpInFrames = mFrameCount * 7;
  5612. mRsmpInFramesP2 = roundup(mRsmpInFrames);
  5613. delete[] mRsmpInBuffer;
  5614. // TODO optimize audio capture buffer sizes ...
  5615. // Here we calculate the size of the sliding buffer used as a source
  5616. // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
  5617. // For current HAL frame counts, this is usually 2048 = 40 ms. It would
  5618. // be better to have it derived from the pipe depth in the long term.
  5619. // The current value is higher than necessary. However it should not add to latency.
  5620. // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
  5621. mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
  5622. // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
  5623. // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
  5624. }
  5625. uint32_t AudioFlinger::RecordThread::getInputFramesLost()
  5626. {
  5627. Mutex::Autolock _l(mLock);
  5628. if (initCheck() != NO_ERROR) {
  5629. return 0;
  5630. }
  5631. return mInput->stream->get_input_frames_lost(mInput->stream);
  5632. }
  5633. uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
  5634. {
  5635. Mutex::Autolock _l(mLock);
  5636. uint32_t result = 0;
  5637. if (getEffectChain_l(sessionId) != 0) {
  5638. result = EFFECT_SESSION;
  5639. }
  5640. for (size_t i = 0; i < mTracks.size(); ++i) {
  5641. if (sessionId == mTracks[i]->sessionId()) {
  5642. result |= TRACK_SESSION;
  5643. break;
  5644. }
  5645. }
  5646. return result;
  5647. }
  5648. KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
  5649. {
  5650. KeyedVector<int, bool> ids;
  5651. Mutex::Autolock _l(mLock);
  5652. for (size_t j = 0; j < mTracks.size(); ++j) {
  5653. sp<RecordThread::RecordTrack> track = mTracks[j];
  5654. int sessionId = track->sessionId();
  5655. if (ids.indexOfKey(sessionId) < 0) {
  5656. ids.add(sessionId, true);
  5657. }
  5658. }
  5659. return ids;
  5660. }
  5661. AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
  5662. {
  5663. Mutex::Autolock _l(mLock);
  5664. AudioStreamIn *input = mInput;
  5665. mInput = NULL;
  5666. return input;
  5667. }
  5668. // this method must always be called either with ThreadBase mLock held or inside the thread loop
  5669. audio_stream_t* AudioFlinger::RecordThread::stream() const
  5670. {
  5671. if (mInput == NULL) {
  5672. return NULL;
  5673. }
  5674. return &mInput->stream->common;
  5675. }
  5676. status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
  5677. {
  5678. // only one chain per input thread
  5679. if (mEffectChains.size() != 0) {
  5680. ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
  5681. return INVALID_OPERATION;
  5682. }
  5683. ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
  5684. chain->setThread(this);
  5685. chain->setInBuffer(NULL);
  5686. chain->setOutBuffer(NULL);
  5687. checkSuspendOnAddEffectChain_l(chain);
  5688. // make sure enabled pre processing effects state is communicated to the HAL as we
  5689. // just moved them to a new input stream.
  5690. chain->syncHalEffectsState();
  5691. mEffectChains.add(chain);
  5692. return NO_ERROR;
  5693. }
  5694. size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
  5695. {
  5696. ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
  5697. ALOGW_IF(mEffectChains.size() != 1,
  5698. "removeEffectChain_l() %p invalid chain size %d on thread %p",
  5699. chain.get(), mEffectChains.size(), this);
  5700. if (mEffectChains.size() == 1) {
  5701. mEffectChains.removeAt(0);
  5702. }
  5703. return 0;
  5704. }
  5705. status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
  5706. audio_patch_handle_t *handle)
  5707. {
  5708. status_t status = NO_ERROR;
  5709. if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
  5710. // store new device and send to effects
  5711. mInDevice = patch->sources[0].ext.device.type;
  5712. for (size_t i = 0; i < mEffectChains.size(); i++) {
  5713. mEffectChains[i]->setDevice_l(mInDevice);
  5714. }
  5715. // disable AEC and NS if the device is a BT SCO headset supporting those
  5716. // pre processings
  5717. if (mTracks.size() > 0) {
  5718. bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
  5719. mAudioFlinger->btNrecIsOff();
  5720. for (size_t i = 0; i < mTracks.size(); i++) {
  5721. sp<RecordTrack> track = mTracks[i];
  5722. setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
  5723. setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
  5724. }
  5725. }
  5726. // store new source and send to effects
  5727. if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
  5728. mAudioSource = patch->sinks[0].ext.mix.usecase.source;
  5729. for (size_t i = 0; i < mEffectChains.size(); i++) {
  5730. mEffectChains[i]->setAudioSource_l(mAudioSource);
  5731. }
  5732. }
  5733. audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
  5734. status = hwDevice->create_audio_patch(hwDevice,
  5735. patch->num_sources,
  5736. patch->sources,
  5737. patch->num_sinks,
  5738. patch->sinks,
  5739. handle);
  5740. } else {
  5741. ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
  5742. }
  5743. return status;
  5744. }
  5745. status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
  5746. {
  5747. status_t status = NO_ERROR;
  5748. if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
  5749. audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
  5750. status = hwDevice->release_audio_patch(hwDevice, handle);
  5751. } else {
  5752. ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
  5753. }
  5754. return status;
  5755. }
  5756. void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
  5757. {
  5758. Mutex::Autolock _l(mLock);
  5759. mTracks.add(record);
  5760. }
  5761. void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
  5762. {
  5763. Mutex::Autolock _l(mLock);
  5764. destroyTrack_l(record);
  5765. }
  5766. void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
  5767. {
  5768. ThreadBase::getAudioPortConfig(config);
  5769. config->role = AUDIO_PORT_ROLE_SINK;
  5770. config->ext.mix.hw_module = mInput->audioHwDev->handle();
  5771. config->ext.mix.usecase.source = mAudioSource;
  5772. }
  5773. }; // namespace android