PageRenderTime 45ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/frameworks/av/media/libmedia/AudioTrack.cpp

https://gitlab.com/brian0218/rk3066_r-box_android4.2.2_sdk
C++ | 1581 lines | 1184 code | 238 blank | 159 comment | 304 complexity | 39c70aa738f4feb85cf8cdb2b550c200 MD5 | raw file
  1. /*
  2. **
  3. ** Copyright 2007, 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_NDEBUG 0
  18. #define LOG_TAG "AudioTrack"
  19. #include <stdint.h>
  20. #include <sys/types.h>
  21. #include <limits.h>
  22. #include <sched.h>
  23. #include <sys/resource.h>
  24. #include <private/media/AudioTrackShared.h>
  25. #include <media/AudioSystem.h>
  26. #include <media/AudioTrack.h>
  27. #include <utils/Log.h>
  28. #include <binder/Parcel.h>
  29. #include <binder/IPCThreadState.h>
  30. #include <utils/Timers.h>
  31. #include <utils/Atomic.h>
  32. #include <cutils/bitops.h>
  33. #include <cutils/compiler.h>
  34. #include <system/audio.h>
  35. #include <system/audio_policy.h>
  36. #include <audio_utils/primitives.h>
  37. #include <cutils/properties.h>
  38. namespace android {
  39. // ---------------------------------------------------------------------------
  40. // static
  41. status_t AudioTrack::getMinFrameCount(
  42. int* frameCount,
  43. audio_stream_type_t streamType,
  44. uint32_t sampleRate)
  45. {
  46. if (frameCount == NULL) return BAD_VALUE;
  47. // default to 0 in case of error
  48. *frameCount = 0;
  49. // FIXME merge with similar code in createTrack_l(), except we're missing
  50. // some information here that is available in createTrack_l():
  51. // audio_io_handle_t output
  52. // audio_format_t format
  53. // audio_channel_mask_t channelMask
  54. // audio_output_flags_t flags
  55. int afSampleRate;
  56. if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
  57. return NO_INIT;
  58. }
  59. int afFrameCount;
  60. if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
  61. return NO_INIT;
  62. }
  63. uint32_t afLatency;
  64. if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
  65. return NO_INIT;
  66. }
  67. // Ensure that buffer depth covers at least audio hardware latency
  68. uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
  69. if (minBufCount < 2) minBufCount = 2;
  70. *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
  71. afFrameCount * minBufCount * sampleRate / afSampleRate;
  72. ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d",
  73. *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
  74. return NO_ERROR;
  75. }
  76. // ---------------------------------------------------------------------------
  77. AudioTrack::AudioTrack()
  78. : mStatus(NO_INIT),
  79. mIsTimed(false),
  80. mPreviousPriority(ANDROID_PRIORITY_NORMAL),
  81. mPreviousSchedulingGroup(SP_DEFAULT)
  82. {
  83. }
  84. AudioTrack::AudioTrack(
  85. audio_stream_type_t streamType,
  86. uint32_t sampleRate,
  87. audio_format_t format,
  88. audio_channel_mask_t channelMask,
  89. int frameCount,
  90. audio_output_flags_t flags,
  91. callback_t cbf,
  92. void* user,
  93. int notificationFrames,
  94. int sessionId)
  95. : mStatus(NO_INIT),
  96. mIsTimed(false),
  97. mPreviousPriority(ANDROID_PRIORITY_NORMAL),
  98. mPreviousSchedulingGroup(SP_DEFAULT)
  99. {
  100. mStatus = set(streamType, sampleRate, format, channelMask,
  101. frameCount, flags, cbf, user, notificationFrames,
  102. 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId);
  103. }
  104. // DEPRECATED
  105. AudioTrack::AudioTrack(
  106. int streamType,
  107. uint32_t sampleRate,
  108. int format,
  109. int channelMask,
  110. int frameCount,
  111. uint32_t flags,
  112. callback_t cbf,
  113. void* user,
  114. int notificationFrames,
  115. int sessionId)
  116. : mStatus(NO_INIT),
  117. mIsTimed(false),
  118. mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT)
  119. {
  120. mStatus = set((audio_stream_type_t)streamType, sampleRate, (audio_format_t)format,
  121. (audio_channel_mask_t) channelMask,
  122. frameCount, (audio_output_flags_t)flags, cbf, user, notificationFrames,
  123. 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId);
  124. }
  125. AudioTrack::AudioTrack(
  126. audio_stream_type_t streamType,
  127. uint32_t sampleRate,
  128. audio_format_t format,
  129. audio_channel_mask_t channelMask,
  130. const sp<IMemory>& sharedBuffer,
  131. audio_output_flags_t flags,
  132. callback_t cbf,
  133. void* user,
  134. int notificationFrames,
  135. int sessionId)
  136. : mStatus(NO_INIT),
  137. mIsTimed(false),
  138. mPreviousPriority(ANDROID_PRIORITY_NORMAL),
  139. mPreviousSchedulingGroup(SP_DEFAULT)
  140. {
  141. mStatus = set(streamType, sampleRate, format, channelMask,
  142. 0 /*frameCount*/, flags, cbf, user, notificationFrames,
  143. sharedBuffer, false /*threadCanCallJava*/, sessionId);
  144. }
  145. AudioTrack::~AudioTrack()
  146. {
  147. ALOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
  148. if (mStatus == NO_ERROR) {
  149. // Make sure that callback function exits in the case where
  150. // it is looping on buffer full condition in obtainBuffer().
  151. // Otherwise the callback thread will never exit.
  152. stop();
  153. if (mAudioTrackThread != 0) {
  154. mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
  155. mAudioTrackThread->requestExitAndWait();
  156. mAudioTrackThread.clear();
  157. }
  158. mAudioTrack.clear();
  159. IPCThreadState::self()->flushCommands();
  160. AudioSystem::releaseAudioSessionId(mSessionId);
  161. }
  162. }
  163. status_t AudioTrack::set(
  164. audio_stream_type_t streamType,
  165. uint32_t sampleRate,
  166. audio_format_t format,
  167. audio_channel_mask_t channelMask,
  168. int frameCount,
  169. audio_output_flags_t flags,
  170. callback_t cbf,
  171. void* user,
  172. int notificationFrames,
  173. const sp<IMemory>& sharedBuffer,
  174. bool threadCanCallJava,
  175. int sessionId)
  176. {
  177. ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
  178. ALOGV("set() streamType %d frameCount %d flags %04x", streamType, frameCount, flags);
  179. //ALOGI("set() streamType %d frameCount %d flags %04x channelMask %d sampleRate %d format %d", streamType, frameCount, flags, channelMask, sampleRate, format);
  180. AutoMutex lock(mLock);
  181. if (mAudioTrack != 0) {
  182. ALOGE("Track already in use");
  183. return INVALID_OPERATION;
  184. }
  185. // handle default values first.
  186. if (streamType == AUDIO_STREAM_DEFAULT) {
  187. streamType = AUDIO_STREAM_MUSIC;
  188. }
  189. if (sampleRate == 0) {
  190. int afSampleRate;
  191. if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
  192. return NO_INIT;
  193. }
  194. sampleRate = afSampleRate;
  195. }
  196. // these below should probably come from the audioFlinger too...
  197. if (format == AUDIO_FORMAT_DEFAULT) {
  198. format = AUDIO_FORMAT_PCM_16_BIT;
  199. }
  200. if (channelMask == 0) {
  201. channelMask = AUDIO_CHANNEL_OUT_STEREO;
  202. }
  203. // validate parameters
  204. if (!audio_is_valid_format(format)) {
  205. ALOGE("Invalid format");
  206. return BAD_VALUE;
  207. }
  208. // AudioFlinger does not currently support 8-bit data in shared memory
  209. if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
  210. ALOGE("8-bit data in shared memory is not supported");
  211. return BAD_VALUE;
  212. }
  213. // force direct flag if format is not linear PCM
  214. if (!audio_is_linear_pcm(format)) {
  215. flags = (audio_output_flags_t)
  216. // FIXME why can't we allow direct AND fast?
  217. ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
  218. }
  219. // only allow deep buffering for music stream type
  220. if (streamType != AUDIO_STREAM_MUSIC) {
  221. flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
  222. }
  223. if (!audio_is_output_channel(channelMask)) {
  224. ALOGE("Invalid channel mask %#x", channelMask);
  225. return BAD_VALUE;
  226. }
  227. if( (AUDIO_OUTPUT_FLAG_DIRECT != flags) &&
  228. (AUDIO_CHANNEL_OUT_5POINT1 == channelMask)) {
  229. flags = AUDIO_OUTPUT_FLAG_DIRECT;
  230. } else if( AUDIO_OUTPUT_FLAG_DIRECT == flags){
  231. channelMask = AUDIO_CHANNEL_OUT_STEREO;
  232. }
  233. uint32_t channelCount = popcount(channelMask);
  234. //ALOGI("streamType %d sampleRate %d format %d channelMask %d flags %d", streamType,
  235. // sampleRate,format,channelMask,flags);
  236. audio_io_handle_t output = AudioSystem::getOutput(
  237. streamType,
  238. sampleRate, format, channelMask,
  239. flags);
  240. if (output == 0) {
  241. ALOGE("Could not get audio output for stream type %d", streamType);
  242. return BAD_VALUE;
  243. }
  244. if(2 != output)
  245. property_set("media.cfg.audio.soundeffect", "false");
  246. else
  247. property_set("media.cfg.audio.soundeffect", "true");
  248. mVolume[LEFT] = 1.0f;
  249. mVolume[RIGHT] = 1.0f;
  250. mSendLevel = 0.0f;
  251. mFrameCount = frameCount;
  252. mNotificationFramesReq = notificationFrames;
  253. mSessionId = sessionId;
  254. mAuxEffectId = 0;
  255. mFlags = flags;
  256. mCbf = cbf;
  257. if (cbf != NULL) {
  258. mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
  259. mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
  260. }
  261. // create the IAudioTrack
  262. status_t status = createTrack_l(streamType,
  263. sampleRate,
  264. format,
  265. channelMask,
  266. frameCount,
  267. flags,
  268. sharedBuffer,
  269. output);
  270. if (status != NO_ERROR) {
  271. if (mAudioTrackThread != 0) {
  272. mAudioTrackThread->requestExit();
  273. mAudioTrackThread.clear();
  274. }
  275. return status;
  276. }
  277. mStatus = NO_ERROR;
  278. mStreamType = streamType;
  279. mFormat = format;
  280. mChannelMask = channelMask;
  281. mChannelCount = channelCount;
  282. mSharedBuffer = sharedBuffer;
  283. mMuted = false;
  284. mActive = false;
  285. mUserData = user;
  286. mLoopCount = 0;
  287. mMarkerPosition = 0;
  288. mMarkerReached = false;
  289. mNewPosition = 0;
  290. mUpdatePeriod = 0;
  291. mFlushed = false;
  292. AudioSystem::acquireAudioSessionId(mSessionId);
  293. mRestoreStatus = NO_ERROR;
  294. return NO_ERROR;
  295. }
  296. status_t AudioTrack::initCheck() const
  297. {
  298. return mStatus;
  299. }
  300. // -------------------------------------------------------------------------
  301. uint32_t AudioTrack::latency() const
  302. {
  303. return mLatency;
  304. }
  305. audio_stream_type_t AudioTrack::streamType() const
  306. {
  307. return mStreamType;
  308. }
  309. audio_format_t AudioTrack::format() const
  310. {
  311. return mFormat;
  312. }
  313. int AudioTrack::channelCount() const
  314. {
  315. return mChannelCount;
  316. }
  317. uint32_t AudioTrack::frameCount() const
  318. {
  319. return mCblk->frameCount;
  320. }
  321. size_t AudioTrack::frameSize() const
  322. {
  323. if (audio_is_linear_pcm(mFormat)) {
  324. return channelCount()*audio_bytes_per_sample(mFormat);
  325. } else {
  326. return sizeof(uint8_t);
  327. }
  328. }
  329. sp<IMemory>& AudioTrack::sharedBuffer()
  330. {
  331. return mSharedBuffer;
  332. }
  333. // -------------------------------------------------------------------------
  334. void AudioTrack::start()
  335. {
  336. sp<AudioTrackThread> t = mAudioTrackThread;
  337. ALOGV("start %p", this);
  338. AutoMutex lock(mLock);
  339. // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
  340. // while we are accessing the cblk
  341. sp<IAudioTrack> audioTrack = mAudioTrack;
  342. sp<IMemory> iMem = mCblkMemory;
  343. audio_track_cblk_t* cblk = mCblk;
  344. if (!mActive) {
  345. mFlushed = false;
  346. mActive = true;
  347. mNewPosition = cblk->server + mUpdatePeriod;
  348. cblk->lock.lock();
  349. cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
  350. cblk->waitTimeMs = 0;
  351. android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
  352. if (t != 0) {
  353. t->resume();
  354. } else {
  355. mPreviousPriority = getpriority(PRIO_PROCESS, 0);
  356. get_sched_policy(0, &mPreviousSchedulingGroup);
  357. androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
  358. }
  359. ALOGV("start %p before lock cblk %p", this, mCblk);
  360. status_t status = NO_ERROR;
  361. if (!(cblk->flags & CBLK_INVALID_MSK)) {
  362. cblk->lock.unlock();
  363. ALOGV("mAudioTrack->start()");
  364. status = mAudioTrack->start();
  365. cblk->lock.lock();
  366. if (status == DEAD_OBJECT) {
  367. android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
  368. }
  369. }
  370. if (cblk->flags & CBLK_INVALID_MSK) {
  371. status = restoreTrack_l(cblk, true);
  372. }
  373. cblk->lock.unlock();
  374. if (status != NO_ERROR) {
  375. ALOGV("start() failed");
  376. mActive = false;
  377. if (t != 0) {
  378. t->pause();
  379. } else {
  380. setpriority(PRIO_PROCESS, 0, mPreviousPriority);
  381. set_sched_policy(0, mPreviousSchedulingGroup);
  382. }
  383. }
  384. }
  385. }
  386. void AudioTrack::stop()
  387. {
  388. sp<AudioTrackThread> t = mAudioTrackThread;
  389. ALOGV("stop %p", this);
  390. AutoMutex lock(mLock);
  391. if (mActive) {
  392. mActive = false;
  393. mCblk->cv.signal();
  394. mAudioTrack->stop();
  395. // Cancel loops (If we are in the middle of a loop, playback
  396. // would not stop until loopCount reaches 0).
  397. setLoop_l(0, 0, 0);
  398. // the playback head position will reset to 0, so if a marker is set, we need
  399. // to activate it again
  400. mMarkerReached = false;
  401. // Force flush if a shared buffer is used otherwise audioflinger
  402. // will not stop before end of buffer is reached.
  403. if (mSharedBuffer != 0) {
  404. flush_l();
  405. }
  406. if (t != 0) {
  407. t->pause();
  408. } else {
  409. setpriority(PRIO_PROCESS, 0, mPreviousPriority);
  410. set_sched_policy(0, mPreviousSchedulingGroup);
  411. }
  412. }
  413. }
  414. bool AudioTrack::stopped() const
  415. {
  416. AutoMutex lock(mLock);
  417. return stopped_l();
  418. }
  419. void AudioTrack::flush()
  420. {
  421. AutoMutex lock(mLock);
  422. flush_l();
  423. }
  424. // must be called with mLock held
  425. void AudioTrack::flush_l()
  426. {
  427. ALOGV("flush");
  428. // clear playback marker and periodic update counter
  429. mMarkerPosition = 0;
  430. mMarkerReached = false;
  431. mUpdatePeriod = 0;
  432. if (!mActive) {
  433. mFlushed = true;
  434. mAudioTrack->flush();
  435. // Release AudioTrack callback thread in case it was waiting for new buffers
  436. // in AudioTrack::obtainBuffer()
  437. mCblk->cv.signal();
  438. }
  439. }
  440. void AudioTrack::pause()
  441. {
  442. ALOGV("pause");
  443. AutoMutex lock(mLock);
  444. if (mActive) {
  445. mActive = false;
  446. mCblk->cv.signal();
  447. mAudioTrack->pause();
  448. }
  449. }
  450. void AudioTrack::mute(bool e)
  451. {
  452. mAudioTrack->mute(e);
  453. mMuted = e;
  454. }
  455. bool AudioTrack::muted() const
  456. {
  457. return mMuted;
  458. }
  459. status_t AudioTrack::setVolume(float left, float right)
  460. {
  461. if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
  462. return BAD_VALUE;
  463. }
  464. AutoMutex lock(mLock);
  465. mVolume[LEFT] = left;
  466. mVolume[RIGHT] = right;
  467. mCblk->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
  468. return NO_ERROR;
  469. }
  470. void AudioTrack::getVolume(float* left, float* right) const
  471. {
  472. if (left != NULL) {
  473. *left = mVolume[LEFT];
  474. }
  475. if (right != NULL) {
  476. *right = mVolume[RIGHT];
  477. }
  478. }
  479. status_t AudioTrack::setAuxEffectSendLevel(float level)
  480. {
  481. ALOGV("setAuxEffectSendLevel(%f)", level);
  482. if (level < 0.0f || level > 1.0f) {
  483. return BAD_VALUE;
  484. }
  485. AutoMutex lock(mLock);
  486. mSendLevel = level;
  487. mCblk->setSendLevel(level);
  488. return NO_ERROR;
  489. }
  490. void AudioTrack::getAuxEffectSendLevel(float* level) const
  491. {
  492. if (level != NULL) {
  493. *level = mSendLevel;
  494. }
  495. }
  496. status_t AudioTrack::setSampleRate(int rate)
  497. {
  498. int afSamplingRate;
  499. if (mIsTimed) {
  500. return INVALID_OPERATION;
  501. }
  502. if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
  503. return NO_INIT;
  504. }
  505. // Resampler implementation limits input sampling rate to 2 x output sampling rate.
  506. if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
  507. AutoMutex lock(mLock);
  508. mCblk->sampleRate = rate;
  509. return NO_ERROR;
  510. }
  511. uint32_t AudioTrack::getSampleRate() const
  512. {
  513. if (mIsTimed) {
  514. return INVALID_OPERATION;
  515. }
  516. AutoMutex lock(mLock);
  517. return mCblk->sampleRate;
  518. }
  519. status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
  520. {
  521. AutoMutex lock(mLock);
  522. return setLoop_l(loopStart, loopEnd, loopCount);
  523. }
  524. // must be called with mLock held
  525. status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
  526. {
  527. audio_track_cblk_t* cblk = mCblk;
  528. Mutex::Autolock _l(cblk->lock);
  529. if (loopCount == 0) {
  530. cblk->loopStart = UINT_MAX;
  531. cblk->loopEnd = UINT_MAX;
  532. cblk->loopCount = 0;
  533. mLoopCount = 0;
  534. return NO_ERROR;
  535. }
  536. if (mIsTimed) {
  537. return INVALID_OPERATION;
  538. }
  539. if (loopStart >= loopEnd ||
  540. loopEnd - loopStart > cblk->frameCount ||
  541. cblk->server > loopStart) {
  542. ALOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, cblk->frameCount, cblk->user);
  543. return BAD_VALUE;
  544. }
  545. if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
  546. ALOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
  547. loopStart, loopEnd, cblk->frameCount);
  548. return BAD_VALUE;
  549. }
  550. cblk->loopStart = loopStart;
  551. cblk->loopEnd = loopEnd;
  552. cblk->loopCount = loopCount;
  553. mLoopCount = loopCount;
  554. return NO_ERROR;
  555. }
  556. status_t AudioTrack::setMarkerPosition(uint32_t marker)
  557. {
  558. if (mCbf == NULL) return INVALID_OPERATION;
  559. mMarkerPosition = marker;
  560. mMarkerReached = false;
  561. return NO_ERROR;
  562. }
  563. status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
  564. {
  565. if (marker == NULL) return BAD_VALUE;
  566. *marker = mMarkerPosition;
  567. return NO_ERROR;
  568. }
  569. status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
  570. {
  571. if (mCbf == NULL) return INVALID_OPERATION;
  572. uint32_t curPosition;
  573. getPosition(&curPosition);
  574. mNewPosition = curPosition + updatePeriod;
  575. mUpdatePeriod = updatePeriod;
  576. return NO_ERROR;
  577. }
  578. status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
  579. {
  580. if (updatePeriod == NULL) return BAD_VALUE;
  581. *updatePeriod = mUpdatePeriod;
  582. return NO_ERROR;
  583. }
  584. status_t AudioTrack::setPosition(uint32_t position)
  585. {
  586. if (mIsTimed) return INVALID_OPERATION;
  587. AutoMutex lock(mLock);
  588. if (!stopped_l()) return INVALID_OPERATION;
  589. Mutex::Autolock _l(mCblk->lock);
  590. if (position > mCblk->user) return BAD_VALUE;
  591. mCblk->server = position;
  592. android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
  593. return NO_ERROR;
  594. }
  595. status_t AudioTrack::getPosition(uint32_t *position)
  596. {
  597. if (position == NULL) return BAD_VALUE;
  598. AutoMutex lock(mLock);
  599. *position = mFlushed ? 0 : mCblk->server;
  600. return NO_ERROR;
  601. }
  602. status_t AudioTrack::reload()
  603. {
  604. AutoMutex lock(mLock);
  605. if (!stopped_l()) return INVALID_OPERATION;
  606. flush_l();
  607. mCblk->stepUser(mCblk->frameCount);
  608. return NO_ERROR;
  609. }
  610. audio_io_handle_t AudioTrack::getOutput()
  611. {
  612. AutoMutex lock(mLock);
  613. return getOutput_l();
  614. }
  615. // must be called with mLock held
  616. audio_io_handle_t AudioTrack::getOutput_l()
  617. {
  618. return AudioSystem::getOutput(mStreamType,
  619. mCblk->sampleRate, mFormat, mChannelMask, mFlags);
  620. }
  621. int AudioTrack::getSessionId() const
  622. {
  623. return mSessionId;
  624. }
  625. status_t AudioTrack::attachAuxEffect(int effectId)
  626. {
  627. ALOGV("attachAuxEffect(%d)", effectId);
  628. status_t status = mAudioTrack->attachAuxEffect(effectId);
  629. if (status == NO_ERROR) {
  630. mAuxEffectId = effectId;
  631. }
  632. return status;
  633. }
  634. // -------------------------------------------------------------------------
  635. // must be called with mLock held
  636. status_t AudioTrack::createTrack_l(
  637. audio_stream_type_t streamType,
  638. uint32_t sampleRate,
  639. audio_format_t format,
  640. audio_channel_mask_t channelMask,
  641. int frameCount,
  642. audio_output_flags_t flags,
  643. const sp<IMemory>& sharedBuffer,
  644. audio_io_handle_t output)
  645. {
  646. status_t status;
  647. const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
  648. if (audioFlinger == 0) {
  649. ALOGE("Could not get audioflinger");
  650. return NO_INIT;
  651. }
  652. uint32_t afLatency;
  653. if (AudioSystem::getLatency(output, streamType, &afLatency) != NO_ERROR) {
  654. return NO_INIT;
  655. }
  656. // Client decides whether the track is TIMED (see below), but can only express a preference
  657. // for FAST. Server will perform additional tests.
  658. if ((flags & AUDIO_OUTPUT_FLAG_FAST) && !(
  659. // either of these use cases:
  660. // use case 1: shared buffer
  661. (sharedBuffer != 0) ||
  662. // use case 2: callback handler
  663. (mCbf != NULL))) {
  664. ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
  665. // once denied, do not request again if IAudioTrack is re-created
  666. flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
  667. mFlags = flags;
  668. }
  669. ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
  670. mNotificationFramesAct = mNotificationFramesReq;
  671. if (!audio_is_linear_pcm(format)) {
  672. if (sharedBuffer != 0) {
  673. // Same comment as below about ignoring frameCount parameter for set()
  674. frameCount = sharedBuffer->size();
  675. } else if (frameCount == 0) {
  676. int afFrameCount;
  677. if (AudioSystem::getFrameCount(output, streamType, &afFrameCount) != NO_ERROR) {
  678. return NO_INIT;
  679. }
  680. frameCount = afFrameCount;
  681. }
  682. } else if (sharedBuffer != 0) {
  683. // Ensure that buffer alignment matches channelCount
  684. int channelCount = popcount(channelMask);
  685. // 8-bit data in shared memory is not currently supported by AudioFlinger
  686. size_t alignment = /* format == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
  687. if (channelCount > 1) {
  688. // More than 2 channels does not require stronger alignment than stereo
  689. alignment <<= 1;
  690. }
  691. if (((uint32_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
  692. ALOGE("Invalid buffer alignment: address %p, channelCount %d",
  693. sharedBuffer->pointer(), channelCount);
  694. return BAD_VALUE;
  695. }
  696. // When initializing a shared buffer AudioTrack via constructors,
  697. // there's no frameCount parameter.
  698. // But when initializing a shared buffer AudioTrack via set(),
  699. // there _is_ a frameCount parameter. We silently ignore it.
  700. frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
  701. } else if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
  702. // FIXME move these calculations and associated checks to server
  703. int afSampleRate;
  704. if (AudioSystem::getSamplingRate(output, streamType, &afSampleRate) != NO_ERROR) {
  705. return NO_INIT;
  706. }
  707. int afFrameCount;
  708. if (AudioSystem::getFrameCount(output, streamType, &afFrameCount) != NO_ERROR) {
  709. return NO_INIT;
  710. }
  711. // Ensure that buffer depth covers at least audio hardware latency
  712. uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
  713. if (minBufCount < 2) minBufCount = 2;
  714. int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
  715. ALOGV("minFrameCount: %d, afFrameCount=%d, minBufCount=%d, sampleRate=%d, afSampleRate=%d"
  716. ", afLatency=%d",
  717. minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency);
  718. if (frameCount == 0) {
  719. frameCount = minFrameCount;
  720. }
  721. if (mNotificationFramesAct == 0) {
  722. mNotificationFramesAct = frameCount/2;
  723. }
  724. // Make sure that application is notified with sufficient margin
  725. // before underrun
  726. if (mNotificationFramesAct > (uint32_t)frameCount/2) {
  727. mNotificationFramesAct = frameCount/2;
  728. }
  729. if (frameCount < minFrameCount) {
  730. // not ALOGW because it happens all the time when playing key clicks over A2DP
  731. ALOGV("Minimum buffer size corrected from %d to %d",
  732. frameCount, minFrameCount);
  733. frameCount = minFrameCount;
  734. }
  735. } else {
  736. // For fast tracks, the frame count calculations and checks are done by server
  737. }
  738. IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
  739. if (mIsTimed) {
  740. trackFlags |= IAudioFlinger::TRACK_TIMED;
  741. }
  742. pid_t tid = -1;
  743. if (flags & AUDIO_OUTPUT_FLAG_FAST) {
  744. trackFlags |= IAudioFlinger::TRACK_FAST;
  745. if (mAudioTrackThread != 0) {
  746. tid = mAudioTrackThread->getTid();
  747. }
  748. }
  749. sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
  750. streamType,
  751. sampleRate,
  752. format,
  753. channelMask,
  754. frameCount,
  755. trackFlags,
  756. sharedBuffer,
  757. output,
  758. tid,
  759. &mSessionId,
  760. &status);
  761. if (track == 0) {
  762. ALOGE("AudioFlinger could not create track, status: %d", status);
  763. return status;
  764. }
  765. sp<IMemory> cblk = track->getCblk();
  766. if (cblk == 0) {
  767. ALOGE("Could not get control block");
  768. return NO_INIT;
  769. }
  770. mAudioTrack = track;
  771. mCblkMemory = cblk;
  772. mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
  773. // old has the previous value of mCblk->flags before the "or" operation
  774. int32_t old = android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
  775. if (flags & AUDIO_OUTPUT_FLAG_FAST) {
  776. if (old & CBLK_FAST) {
  777. ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", mCblk->frameCount);
  778. } else {
  779. ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", mCblk->frameCount);
  780. // once denied, do not request again if IAudioTrack is re-created
  781. flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
  782. mFlags = flags;
  783. }
  784. if (sharedBuffer == 0) {
  785. mNotificationFramesAct = mCblk->frameCount/2;
  786. }
  787. }
  788. if (sharedBuffer == 0) {
  789. mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
  790. } else {
  791. mCblk->buffers = sharedBuffer->pointer();
  792. // Force buffer full condition as data is already present in shared memory
  793. mCblk->stepUser(mCblk->frameCount);
  794. }
  795. mCblk->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000));
  796. mCblk->setSendLevel(mSendLevel);
  797. mAudioTrack->attachAuxEffect(mAuxEffectId);
  798. mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
  799. mCblk->waitTimeMs = 0;
  800. mRemainingFrames = mNotificationFramesAct;
  801. // FIXME don't believe this lie
  802. mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
  803. // If IAudioTrack is re-created, don't let the requested frameCount
  804. // decrease. This can confuse clients that cache frameCount().
  805. if (mCblk->frameCount > mFrameCount) {
  806. mFrameCount = mCblk->frameCount;
  807. }
  808. return NO_ERROR;
  809. }
  810. status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
  811. {
  812. AutoMutex lock(mLock);
  813. bool active;
  814. status_t result = NO_ERROR;
  815. audio_track_cblk_t* cblk = mCblk;
  816. uint32_t framesReq = audioBuffer->frameCount;
  817. uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
  818. audioBuffer->frameCount = 0;
  819. audioBuffer->size = 0;
  820. uint32_t framesAvail = cblk->framesAvailable();
  821. cblk->lock.lock();
  822. if (cblk->flags & CBLK_INVALID_MSK) {
  823. goto create_new_track;
  824. }
  825. cblk->lock.unlock();
  826. if (framesAvail == 0) {
  827. cblk->lock.lock();
  828. goto start_loop_here;
  829. while (framesAvail == 0) {
  830. active = mActive;
  831. if (CC_UNLIKELY(!active)) {
  832. ALOGV("Not active and NO_MORE_BUFFERS");
  833. cblk->lock.unlock();
  834. return NO_MORE_BUFFERS;
  835. }
  836. if (CC_UNLIKELY(!waitCount)) {
  837. cblk->lock.unlock();
  838. return WOULD_BLOCK;
  839. }
  840. if (!(cblk->flags & CBLK_INVALID_MSK)) {
  841. mLock.unlock();
  842. result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
  843. cblk->lock.unlock();
  844. mLock.lock();
  845. if (!mActive) {
  846. return status_t(STOPPED);
  847. }
  848. cblk->lock.lock();
  849. }
  850. if (cblk->flags & CBLK_INVALID_MSK) {
  851. goto create_new_track;
  852. }
  853. if (CC_UNLIKELY(result != NO_ERROR)) {
  854. cblk->waitTimeMs += waitTimeMs;
  855. if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
  856. // timing out when a loop has been set and we have already written upto loop end
  857. // is a normal condition: no need to wake AudioFlinger up.
  858. if (cblk->user < cblk->loopEnd) {
  859. ALOGW( "obtainBuffer timed out (is the CPU pegged?) %p name=%#x"
  860. "user=%08x, server=%08x", this, cblk->mName, cblk->user, cblk->server);
  861. //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
  862. cblk->lock.unlock();
  863. result = mAudioTrack->start();
  864. cblk->lock.lock();
  865. if (result == DEAD_OBJECT) {
  866. android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
  867. create_new_track:
  868. result = restoreTrack_l(cblk, false);
  869. }
  870. if (result != NO_ERROR) {
  871. ALOGW("obtainBuffer create Track error %d", result);
  872. cblk->lock.unlock();
  873. return result;
  874. }
  875. }
  876. cblk->waitTimeMs = 0;
  877. }
  878. if (--waitCount == 0) {
  879. cblk->lock.unlock();
  880. return TIMED_OUT;
  881. }
  882. }
  883. // read the server count again
  884. start_loop_here:
  885. framesAvail = cblk->framesAvailable_l();
  886. }
  887. cblk->lock.unlock();
  888. }
  889. cblk->waitTimeMs = 0;
  890. if (framesReq > framesAvail) {
  891. framesReq = framesAvail;
  892. }
  893. uint32_t u = cblk->user;
  894. uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
  895. if (framesReq > bufferEnd - u) {
  896. framesReq = bufferEnd - u;
  897. }
  898. audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
  899. audioBuffer->channelCount = mChannelCount;
  900. audioBuffer->frameCount = framesReq;
  901. audioBuffer->size = framesReq * cblk->frameSize;
  902. if (audio_is_linear_pcm(mFormat)) {
  903. audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
  904. } else {
  905. audioBuffer->format = mFormat;
  906. }
  907. audioBuffer->raw = (int8_t *)cblk->buffer(u);
  908. active = mActive;
  909. return active ? status_t(NO_ERROR) : status_t(STOPPED);
  910. }
  911. void AudioTrack::releaseBuffer(Buffer* audioBuffer)
  912. {
  913. AutoMutex lock(mLock);
  914. mCblk->stepUser(audioBuffer->frameCount);
  915. if (audioBuffer->frameCount > 0) {
  916. // restart track if it was disabled by audioflinger due to previous underrun
  917. if (mActive && (mCblk->flags & CBLK_DISABLED_MSK)) {
  918. android_atomic_and(~CBLK_DISABLED_ON, &mCblk->flags);
  919. ALOGW("releaseBuffer() track %p name=%#x disabled, restarting", this, mCblk->mName);
  920. mAudioTrack->start();
  921. }
  922. }
  923. }
  924. // -------------------------------------------------------------------------
  925. ssize_t AudioTrack::write(const void* buffer, size_t userSize)
  926. {
  927. if (mSharedBuffer != 0) return INVALID_OPERATION;
  928. if (mIsTimed) return INVALID_OPERATION;
  929. if (ssize_t(userSize) < 0) {
  930. // Sanity-check: user is most-likely passing an error code, and it would
  931. // make the return value ambiguous (actualSize vs error).
  932. ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
  933. buffer, userSize, userSize);
  934. return BAD_VALUE;
  935. }
  936. ALOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
  937. if (userSize == 0) {
  938. return 0;
  939. }
  940. // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
  941. // while we are accessing the cblk
  942. mLock.lock();
  943. sp<IAudioTrack> audioTrack = mAudioTrack;
  944. sp<IMemory> iMem = mCblkMemory;
  945. mLock.unlock();
  946. ssize_t written = 0;
  947. const int8_t *src = (const int8_t *)buffer;
  948. Buffer audioBuffer;
  949. size_t frameSz = frameSize();
  950. do {
  951. audioBuffer.frameCount = userSize/frameSz;
  952. status_t err = obtainBuffer(&audioBuffer, -1);
  953. if (err < 0) {
  954. // out of buffers, return #bytes written
  955. if (err == status_t(NO_MORE_BUFFERS))
  956. break;
  957. return ssize_t(err);
  958. }
  959. size_t toWrite;
  960. if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
  961. // Divide capacity by 2 to take expansion into account
  962. toWrite = audioBuffer.size>>1;
  963. memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) src, toWrite);
  964. } else {
  965. toWrite = audioBuffer.size;
  966. memcpy(audioBuffer.i8, src, toWrite);
  967. src += toWrite;
  968. }
  969. userSize -= toWrite;
  970. written += toWrite;
  971. releaseBuffer(&audioBuffer);
  972. } while (userSize >= frameSz);
  973. return written;
  974. }
  975. // -------------------------------------------------------------------------
  976. TimedAudioTrack::TimedAudioTrack() {
  977. mIsTimed = true;
  978. }
  979. status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
  980. {
  981. status_t result = UNKNOWN_ERROR;
  982. // If the track is not invalid already, try to allocate a buffer. alloc
  983. // fails indicating that the server is dead, flag the track as invalid so
  984. // we can attempt to restore in just a bit.
  985. if (!(mCblk->flags & CBLK_INVALID_MSK)) {
  986. result = mAudioTrack->allocateTimedBuffer(size, buffer);
  987. if (result == DEAD_OBJECT) {
  988. android_atomic_or(CBLK_INVALID_ON, &mCblk->flags);
  989. }
  990. }
  991. // If the track is invalid at this point, attempt to restore it. and try the
  992. // allocation one more time.
  993. if (mCblk->flags & CBLK_INVALID_MSK) {
  994. mCblk->lock.lock();
  995. result = restoreTrack_l(mCblk, false);
  996. mCblk->lock.unlock();
  997. if (result == OK)
  998. result = mAudioTrack->allocateTimedBuffer(size, buffer);
  999. }
  1000. return result;
  1001. }
  1002. status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
  1003. int64_t pts)
  1004. {
  1005. status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
  1006. {
  1007. AutoMutex lock(mLock);
  1008. // restart track if it was disabled by audioflinger due to previous underrun
  1009. if (buffer->size() != 0 && status == NO_ERROR &&
  1010. mActive && (mCblk->flags & CBLK_DISABLED_MSK)) {
  1011. android_atomic_and(~CBLK_DISABLED_ON, &mCblk->flags);
  1012. ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
  1013. mAudioTrack->start();
  1014. }
  1015. }
  1016. return status;
  1017. }
  1018. status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
  1019. TargetTimeline target)
  1020. {
  1021. return mAudioTrack->setMediaTimeTransform(xform, target);
  1022. }
  1023. // -------------------------------------------------------------------------
  1024. bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
  1025. {
  1026. Buffer audioBuffer;
  1027. uint32_t frames;
  1028. size_t writtenSize;
  1029. mLock.lock();
  1030. // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
  1031. // while we are accessing the cblk
  1032. sp<IAudioTrack> audioTrack = mAudioTrack;
  1033. sp<IMemory> iMem = mCblkMemory;
  1034. audio_track_cblk_t* cblk = mCblk;
  1035. bool active = mActive;
  1036. mLock.unlock();
  1037. // Manage underrun callback
  1038. if (active && (cblk->framesAvailable() == cblk->frameCount)) {
  1039. ALOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
  1040. if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
  1041. mCbf(EVENT_UNDERRUN, mUserData, 0);
  1042. if (cblk->server == cblk->frameCount) {
  1043. mCbf(EVENT_BUFFER_END, mUserData, 0);
  1044. }
  1045. if (mSharedBuffer != 0) return false;
  1046. }
  1047. }
  1048. // Manage loop end callback
  1049. while (mLoopCount > cblk->loopCount) {
  1050. int loopCount = -1;
  1051. mLoopCount--;
  1052. if (mLoopCount >= 0) loopCount = mLoopCount;
  1053. mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
  1054. }
  1055. // Manage marker callback
  1056. if (!mMarkerReached && (mMarkerPosition > 0)) {
  1057. if (cblk->server >= mMarkerPosition) {
  1058. mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
  1059. mMarkerReached = true;
  1060. }
  1061. }
  1062. // Manage new position callback
  1063. if (mUpdatePeriod > 0) {
  1064. while (cblk->server >= mNewPosition) {
  1065. mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
  1066. mNewPosition += mUpdatePeriod;
  1067. }
  1068. }
  1069. // If Shared buffer is used, no data is requested from client.
  1070. if (mSharedBuffer != 0) {
  1071. frames = 0;
  1072. } else {
  1073. frames = mRemainingFrames;
  1074. }
  1075. // See description of waitCount parameter at declaration of obtainBuffer().
  1076. // The logic below prevents us from being stuck below at obtainBuffer()
  1077. // not being able to handle timed events (position, markers, loops).
  1078. int32_t waitCount = -1;
  1079. if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) {
  1080. waitCount = 1;
  1081. }
  1082. do {
  1083. audioBuffer.frameCount = frames;
  1084. status_t err = obtainBuffer(&audioBuffer, waitCount);
  1085. if (err < NO_ERROR) {
  1086. if (err != TIMED_OUT) {
  1087. ALOGE_IF(err != status_t(NO_MORE_BUFFERS), "Error obtaining an audio buffer, giving up.");
  1088. return false;
  1089. }
  1090. break;
  1091. }
  1092. if (err == status_t(STOPPED)) return false;
  1093. // Divide buffer size by 2 to take into account the expansion
  1094. // due to 8 to 16 bit conversion: the callback must fill only half
  1095. // of the destination buffer
  1096. if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
  1097. audioBuffer.size >>= 1;
  1098. }
  1099. size_t reqSize = audioBuffer.size;
  1100. mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
  1101. writtenSize = audioBuffer.size;
  1102. // Sanity check on returned size
  1103. if (ssize_t(writtenSize) <= 0) {
  1104. // The callback is done filling buffers
  1105. // Keep this thread going to handle timed events and
  1106. // still try to get more data in intervals of WAIT_PERIOD_MS
  1107. // but don't just loop and block the CPU, so wait
  1108. usleep(WAIT_PERIOD_MS*1000);
  1109. break;
  1110. }
  1111. if (writtenSize > reqSize) writtenSize = reqSize;
  1112. if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
  1113. // 8 to 16 bit conversion, note that source and destination are the same address
  1114. memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
  1115. writtenSize <<= 1;
  1116. }
  1117. audioBuffer.size = writtenSize;
  1118. // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
  1119. // 8 bit PCM data: in this case, mCblk->frameSize is based on a sample size of
  1120. // 16 bit.
  1121. audioBuffer.frameCount = writtenSize/mCblk->frameSize;
  1122. frames -= audioBuffer.frameCount;
  1123. releaseBuffer(&audioBuffer);
  1124. }
  1125. while (frames);
  1126. if (frames == 0) {
  1127. mRemainingFrames = mNotificationFramesAct;
  1128. } else {
  1129. mRemainingFrames = frames;
  1130. }
  1131. return true;
  1132. }
  1133. // must be called with mLock and cblk.lock held. Callers must also hold strong references on
  1134. // the IAudioTrack and IMemory in case they are recreated here.
  1135. // If the IAudioTrack is successfully restored, the cblk pointer is updated
  1136. status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
  1137. {
  1138. status_t result;
  1139. if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
  1140. ALOGW("dead IAudioTrack, creating a new one from %s TID %d",
  1141. fromStart ? "start()" : "obtainBuffer()", gettid());
  1142. // signal old cblk condition so that other threads waiting for available buffers stop
  1143. // waiting now
  1144. cblk->cv.broadcast();
  1145. cblk->lock.unlock();
  1146. // refresh the audio configuration cache in this process to make sure we get new
  1147. // output parameters in getOutput_l() and createTrack_l()
  1148. AudioSystem::clearAudioConfigCache();
  1149. // if the new IAudioTrack is created, createTrack_l() will modify the
  1150. // following member variables: mAudioTrack, mCblkMemory and mCblk.
  1151. // It will also delete the strong references on previous IAudioTrack and IMemory
  1152. result = createTrack_l(mStreamType,
  1153. cblk->sampleRate,
  1154. mFormat,
  1155. mChannelMask,
  1156. mFrameCount,
  1157. mFlags,
  1158. mSharedBuffer,
  1159. getOutput_l());
  1160. if (result == NO_ERROR) {
  1161. uint32_t user = cblk->user;
  1162. uint32_t server = cblk->server;
  1163. // restore write index and set other indexes to reflect empty buffer status
  1164. mCblk->user = user;
  1165. mCblk->server = user;
  1166. mCblk->userBase = user;
  1167. mCblk->serverBase = user;
  1168. // restore loop: this is not guaranteed to succeed if new frame count is not
  1169. // compatible with loop length
  1170. setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
  1171. if (!fromStart) {
  1172. mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
  1173. // Make sure that a client relying on callback events indicating underrun or
  1174. // the actual amount of audio frames played (e.g SoundPool) receives them.
  1175. if (mSharedBuffer == 0) {
  1176. uint32_t frames = 0;
  1177. if (user > server) {
  1178. frames = ((user - server) > mCblk->frameCount) ?
  1179. mCblk->frameCount : (user - server);
  1180. memset(mCblk->buffers, 0, frames * mCblk->frameSize);
  1181. }
  1182. // restart playback even if buffer is not completely filled.
  1183. android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
  1184. // stepUser() clears CBLK_UNDERRUN_ON flag enabling underrun callbacks to
  1185. // the client
  1186. mCblk->stepUser(frames);
  1187. }
  1188. }
  1189. if (mSharedBuffer != 0) {
  1190. mCblk->stepUser(mCblk->frameCount);
  1191. }
  1192. if (mActive) {
  1193. result = mAudioTrack->start();
  1194. ALOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result);
  1195. }
  1196. if (fromStart && result == NO_ERROR) {
  1197. mNewPosition = mCblk->server + mUpdatePeriod;
  1198. }
  1199. }
  1200. if (result != NO_ERROR) {
  1201. android_atomic_and(~CBLK_RESTORING_ON, &cblk->flags);
  1202. ALOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result);
  1203. }
  1204. mRestoreStatus = result;
  1205. // signal old cblk condition for other threads waiting for restore completion
  1206. android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
  1207. cblk->cv.broadcast();
  1208. } else {
  1209. if (!(cblk->flags & CBLK_RESTORED_MSK)) {
  1210. ALOGW("dead IAudioTrack, waiting for a new one TID %d", gettid());
  1211. mLock.unlock();
  1212. result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
  1213. if (result == NO_ERROR) {
  1214. result = mRestoreStatus;
  1215. }
  1216. cblk->lock.unlock();
  1217. mLock.lock();
  1218. } else {
  1219. ALOGW("dead IAudioTrack, already restored TID %d", gettid());
  1220. result = mRestoreStatus;
  1221. cblk->lock.unlock();
  1222. }
  1223. }
  1224. ALOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
  1225. result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
  1226. if (result == NO_ERROR) {
  1227. // from now on we switch to the newly created cblk
  1228. cblk = mCblk;
  1229. }
  1230. cblk->lock.lock();
  1231. ALOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d TID %d", result, gettid());
  1232. return result;
  1233. }
  1234. status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
  1235. {
  1236. const size_t SIZE = 256;
  1237. char buffer[SIZE];
  1238. String8 result;
  1239. result.append(" AudioTrack::dump\n");
  1240. snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
  1241. result.append(buffer);
  1242. snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mCblk->frameCount);
  1243. result.append(buffer);
  1244. snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted);
  1245. result.append(buffer);
  1246. snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
  1247. result.append(buffer);
  1248. ::write(fd, result.string(), result.size());
  1249. return NO_ERROR;
  1250. }
  1251. // =========================================================================
  1252. AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
  1253. : Thread(bCanCallJava), mReceiver(receiver), mPaused(true)
  1254. {
  1255. }
  1256. AudioTrack::AudioTrackThread::~AudioTrackThread()
  1257. {
  1258. }
  1259. bool AudioTrack::AudioTrackThread::threadLoop()
  1260. {
  1261. {
  1262. AutoMutex _l(mMyLock);
  1263. if (mPaused) {
  1264. mMyCond.wait(mMyLock);
  1265. // caller will check for exitPending()
  1266. return true;
  1267. }
  1268. }
  1269. if (!mReceiver.processAudioBuffer(this)) {
  1270. pause();
  1271. }
  1272. return true;
  1273. }
  1274. void AudioTrack::AudioTrackThread::requestExit()
  1275. {
  1276. // must be in this order to avoid a race condition
  1277. Thread::requestExit();
  1278. resume();
  1279. }
  1280. void AudioTrack::AudioTrackThread::pause()
  1281. {
  1282. AutoMutex _l(mMyLock);
  1283. mPaused = true;
  1284. }
  1285. void AudioTrack::AudioTrackThread::resume()
  1286. {
  1287. AutoMutex _l(mMyLock);
  1288. if (mPaused) {
  1289. mPaused = false;
  1290. mMyCond.signal();
  1291. }
  1292. }
  1293. // =========================================================================
  1294. audio_track_cblk_t::audio_track_cblk_t()
  1295. : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
  1296. userBase(0), serverBase(0), buffers(NULL), frameCount(0),
  1297. loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), mVolumeLR(0x10001000),
  1298. mSendLevel(0), flags(0)
  1299. {
  1300. }
  1301. uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
  1302. {
  1303. ALOGV("stepuser %08x %08x %d", user, server, frameCount);
  1304. uint32_t u = user;
  1305. u += frameCount;
  1306. // Ensure that user is never ahead of server for AudioRecord
  1307. if (flags & CBLK_DIRECTION_MSK) {
  1308. // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
  1309. if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
  1310. bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
  1311. }
  1312. } else if (u > server) {
  1313. ALOGW("stepUser occurred after track reset");
  1314. u = server;
  1315. }
  1316. uint32_t fc = this->frameCount;
  1317. if (u >= fc) {
  1318. // common case, user didn't just wrap
  1319. if (u - fc >= userBase ) {
  1320. userBase += fc;
  1321. }
  1322. } else if (u >= userBase + fc) {
  1323. // user just wrapped
  1324. userBase += fc;
  1325. }
  1326. user = u;
  1327. // Clear flow control error condition as new data has been written/read to/from buffer.
  1328. if (flags & CBLK_UNDERRUN_MSK) {
  1329. android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
  1330. }
  1331. return u;
  1332. }
  1333. bool audio_track_cblk_t::stepServer(uint32_t frameCount)
  1334. {
  1335. ALOGV("stepserver %08x %08x %d", user, server, frameCount);
  1336. if (!tryLock()) {
  1337. ALOGW("stepServer() could not lock cblk");
  1338. return false;
  1339. }
  1340. uint32_t s = server;
  1341. bool flushed = (s == user);
  1342. s += frameCount;
  1343. if (flags & CBLK_DIRECT