blob: 609720060d43c5c75a506de5189f08606e41c776 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/* //device/extlibs/pv/android/AudioTrack.cpp
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
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "AudioTrack"
21
22#include <stdint.h>
23#include <sys/types.h>
24#include <limits.h>
25
26#include <sched.h>
27#include <sys/resource.h>
28
29#include <private/media/AudioTrackShared.h>
30
31#include <media/AudioSystem.h>
32#include <media/AudioTrack.h>
33
34#include <utils/Log.h>
Mathias Agopian75624082009-05-19 19:08:10 -070035#include <binder/Parcel.h>
36#include <binder/IPCThreadState.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080037#include <utils/Timers.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070038#include <utils/Atomic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080039
Dima Zavinfce7a472011-04-19 22:30:36 -070040#include <cutils/bitops.h>
41
Dima Zavin64760242011-05-11 14:15:23 -070042#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070043#include <system/audio_policy.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070044
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080045#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
46#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
47
48namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080049// ---------------------------------------------------------------------------
50
51// static
52status_t AudioTrack::getMinFrameCount(
53 int* frameCount,
54 int streamType,
55 uint32_t sampleRate)
56{
57 int afSampleRate;
58 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
59 return NO_INIT;
60 }
61 int afFrameCount;
62 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
63 return NO_INIT;
64 }
65 uint32_t afLatency;
66 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
67 return NO_INIT;
68 }
69
70 // Ensure that buffer depth covers at least audio hardware latency
71 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
72 if (minBufCount < 2) minBufCount = 2;
73
74 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
75 afFrameCount * minBufCount * sampleRate / afSampleRate;
76 return NO_ERROR;
77}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080078
79// ---------------------------------------------------------------------------
80
81AudioTrack::AudioTrack()
Mike J. Chen500e5102011-08-15 13:28:26 -070082 : mStatus(NO_INIT),
83 mIsTimed(false)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080084{
85}
86
87AudioTrack::AudioTrack(
88 int streamType,
89 uint32_t sampleRate,
90 int format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -070091 int channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080092 int frameCount,
93 uint32_t flags,
94 callback_t cbf,
95 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -070096 int notificationFrames,
97 int sessionId)
Mike J. Chen500e5102011-08-15 13:28:26 -070098 : mStatus(NO_INIT),
99 mIsTimed(false)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800100{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700101 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700102 frameCount, flags, cbf, user, notificationFrames,
103 0, false, sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800104}
105
106AudioTrack::AudioTrack(
107 int streamType,
108 uint32_t sampleRate,
109 int format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700110 int channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800111 const sp<IMemory>& sharedBuffer,
112 uint32_t flags,
113 callback_t cbf,
114 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700115 int notificationFrames,
116 int sessionId)
Mike J. Chen500e5102011-08-15 13:28:26 -0700117 : mStatus(NO_INIT),
118 mIsTimed(false)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800119{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700120 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700121 0, flags, cbf, user, notificationFrames,
122 sharedBuffer, false, sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800123}
124
125AudioTrack::~AudioTrack()
126{
127 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
128
129 if (mStatus == NO_ERROR) {
130 // Make sure that callback function exits in the case where
131 // it is looping on buffer full condition in obtainBuffer().
132 // Otherwise the callback thread will never exit.
133 stop();
134 if (mAudioTrackThread != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800135 mAudioTrackThread->requestExitAndWait();
136 mAudioTrackThread.clear();
137 }
138 mAudioTrack.clear();
139 IPCThreadState::self()->flushCommands();
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700140 AudioSystem::releaseAudioSessionId(mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800141 }
142}
143
144status_t AudioTrack::set(
145 int streamType,
146 uint32_t sampleRate,
147 int format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700148 int channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800149 int frameCount,
150 uint32_t flags,
151 callback_t cbf,
152 void* user,
153 int notificationFrames,
154 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700155 bool threadCanCallJava,
156 int sessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800157{
158
159 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
160
Eric Laurent1703cdf2011-03-07 14:52:59 -0800161 AutoMutex lock(mLock);
Eric Laurent1dd70b92009-04-21 07:56:33 -0700162 if (mAudioTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800163 LOGE("Track already in use");
164 return INVALID_OPERATION;
165 }
166
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800167 int afSampleRate;
168 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
169 return NO_INIT;
170 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800171 uint32_t afLatency;
172 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
173 return NO_INIT;
174 }
175
176 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700177 if (streamType == AUDIO_STREAM_DEFAULT) {
178 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800179 }
180 if (sampleRate == 0) {
181 sampleRate = afSampleRate;
182 }
183 // these below should probably come from the audioFlinger too...
184 if (format == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700185 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800186 }
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700187 if (channelMask == 0) {
188 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800189 }
190
191 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700192 if (!audio_is_valid_format(format)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800193 LOGE("Invalid format");
194 return BAD_VALUE;
195 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700196
197 // force direct flag if format is not linear PCM
Dima Zavinfce7a472011-04-19 22:30:36 -0700198 if (!audio_is_linear_pcm(format)) {
199 flags |= AUDIO_POLICY_OUTPUT_FLAG_DIRECT;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700200 }
201
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700202 if (!audio_is_output_channel(channelMask)) {
Eric Laurentc2f1f072009-07-17 12:17:14 -0700203 LOGE("Invalid channel mask");
204 return BAD_VALUE;
205 }
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700206 uint32_t channelCount = popcount(channelMask);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700207
Dima Zavinfce7a472011-04-19 22:30:36 -0700208 audio_io_handle_t output = AudioSystem::getOutput(
209 (audio_stream_type_t)streamType,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700210 sampleRate,format, channelMask,
Dima Zavinfce7a472011-04-19 22:30:36 -0700211 (audio_policy_output_flags_t)flags);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700212
213 if (output == 0) {
214 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800215 return BAD_VALUE;
216 }
217
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800218 mVolume[LEFT] = 1.0f;
219 mVolume[RIGHT] = 1.0f;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700220 mSendLevel = 0;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700221 mFrameCount = frameCount;
222 mNotificationFramesReq = notificationFrames;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700223 mSessionId = sessionId;
Eric Laurent2beeb502010-07-16 07:43:46 -0700224 mAuxEffectId = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700225
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800226 // create the IAudioTrack
Eric Laurent1703cdf2011-03-07 14:52:59 -0800227 status_t status = createTrack_l(streamType,
228 sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700229 (uint32_t)format,
230 (uint32_t)channelMask,
Eric Laurent1703cdf2011-03-07 14:52:59 -0800231 frameCount,
232 flags,
233 sharedBuffer,
234 output,
235 true);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800236
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800237 if (status != NO_ERROR) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800238 return status;
239 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800240
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241 if (cbf != 0) {
242 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
243 if (mAudioTrackThread == 0) {
244 LOGE("Could not create callback thread");
245 return NO_INIT;
246 }
247 }
248
249 mStatus = NO_ERROR;
250
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251 mStreamType = streamType;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700252 mFormat = (uint32_t)format;
253 mChannelMask = (uint32_t)channelMask;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800254 mChannelCount = channelCount;
255 mSharedBuffer = sharedBuffer;
256 mMuted = false;
257 mActive = 0;
258 mCbf = cbf;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800259 mUserData = user;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800260 mLoopCount = 0;
261 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700262 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800263 mNewPosition = 0;
264 mUpdatePeriod = 0;
Jean-Michel Trivicd075942011-08-25 16:47:23 -0700265 mFlushed = false;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700266 mFlags = flags;
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700267 AudioSystem::acquireAudioSessionId(mSessionId);
Eric Laurentcfe2ba62011-09-13 15:04:17 -0700268 mRestoreStatus = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800269 return NO_ERROR;
270}
271
272status_t AudioTrack::initCheck() const
273{
274 return mStatus;
275}
276
277// -------------------------------------------------------------------------
278
279uint32_t AudioTrack::latency() const
280{
281 return mLatency;
282}
283
284int AudioTrack::streamType() const
285{
286 return mStreamType;
287}
288
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800289int AudioTrack::format() const
290{
291 return mFormat;
292}
293
294int AudioTrack::channelCount() const
295{
296 return mChannelCount;
297}
298
299uint32_t AudioTrack::frameCount() const
300{
Eric Laurentd1b449a2010-05-14 03:26:45 -0700301 return mCblk->frameCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800302}
303
304int AudioTrack::frameSize() const
305{
Dima Zavinfce7a472011-04-19 22:30:36 -0700306 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent671a6362011-06-16 21:30:45 -0700307 return channelCount()*audio_bytes_per_sample(mFormat);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700308 } else {
309 return sizeof(uint8_t);
310 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311}
312
313sp<IMemory>& AudioTrack::sharedBuffer()
314{
315 return mSharedBuffer;
316}
317
318// -------------------------------------------------------------------------
319
320void AudioTrack::start()
321{
322 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kastend0965dd2011-06-22 16:18:04 -0700323 status_t status = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800324
325 LOGV("start %p", this);
326 if (t != 0) {
327 if (t->exitPending()) {
328 if (t->requestExitAndWait() == WOULD_BLOCK) {
329 LOGE("AudioTrack::start called from thread");
330 return;
331 }
332 }
333 t->mLock.lock();
334 }
335
Eric Laurentf5aafb22010-11-18 08:40:16 -0800336 AutoMutex lock(mLock);
Eric Laurent1703cdf2011-03-07 14:52:59 -0800337 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
338 // while we are accessing the cblk
339 sp <IAudioTrack> audioTrack = mAudioTrack;
340 sp <IMemory> iMem = mCblkMemory;
341 audio_track_cblk_t* cblk = mCblk;
342
Eric Laurentf5aafb22010-11-18 08:40:16 -0800343 if (mActive == 0) {
Jean-Michel Trivicd075942011-08-25 16:47:23 -0700344 mFlushed = false;
Eric Laurentf5aafb22010-11-18 08:40:16 -0800345 mActive = 1;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800346 mNewPosition = cblk->server + mUpdatePeriod;
Eric Laurent33797ea2011-03-17 09:36:51 -0700347 cblk->lock.lock();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800348 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
349 cblk->waitTimeMs = 0;
Eric Laurent38ccae22011-03-28 18:37:07 -0700350 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent2b584242009-11-09 23:32:22 -0800351 if (t != 0) {
Glenn Kastenc6854102011-06-01 16:46:29 -0700352 t->run("AudioTrackThread", ANDROID_PRIORITY_AUDIO);
Eric Laurent2b584242009-11-09 23:32:22 -0800353 } else {
Glenn Kastenc6854102011-06-01 16:46:29 -0700354 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
Eric Laurent2b584242009-11-09 23:32:22 -0800355 }
356
Eric Laurent1703cdf2011-03-07 14:52:59 -0800357 LOGV("start %p before lock cblk %p", this, mCblk);
Eric Laurent1703cdf2011-03-07 14:52:59 -0800358 if (!(cblk->flags & CBLK_INVALID_MSK)) {
359 cblk->lock.unlock();
Eric Laurentd1b449a2010-05-14 03:26:45 -0700360 status = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800361 cblk->lock.lock();
362 if (status == DEAD_OBJECT) {
Eric Laurent38ccae22011-03-28 18:37:07 -0700363 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent6100d2d2009-11-19 09:00:56 -0800364 }
Eric Laurent2b584242009-11-09 23:32:22 -0800365 }
Eric Laurent1703cdf2011-03-07 14:52:59 -0800366 if (cblk->flags & CBLK_INVALID_MSK) {
367 status = restoreTrack_l(cblk, true);
368 }
369 cblk->lock.unlock();
Eric Laurent2b584242009-11-09 23:32:22 -0800370 if (status != NO_ERROR) {
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800371 LOGV("start() failed");
Eric Laurentf5aafb22010-11-18 08:40:16 -0800372 mActive = 0;
Eric Laurent2b584242009-11-09 23:32:22 -0800373 if (t != 0) {
374 t->requestExit();
375 } else {
376 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
377 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800378 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800379 }
380
381 if (t != 0) {
382 t->mLock.unlock();
383 }
384}
385
386void AudioTrack::stop()
387{
388 sp<AudioTrackThread> t = mAudioTrackThread;
389
390 LOGV("stop %p", this);
391 if (t != 0) {
392 t->mLock.lock();
393 }
394
Eric Laurentf5aafb22010-11-18 08:40:16 -0800395 AutoMutex lock(mLock);
396 if (mActive == 1) {
397 mActive = 0;
Eric Laurent1dd70b92009-04-21 07:56:33 -0700398 mCblk->cv.signal();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800399 mAudioTrack->stop();
400 // Cancel loops (If we are in the middle of a loop, playback
401 // would not stop until loopCount reaches 0).
Eric Laurent1703cdf2011-03-07 14:52:59 -0800402 setLoop_l(0, 0, 0);
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700403 // the playback head position will reset to 0, so if a marker is set, we need
404 // to activate it again
405 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800406 // Force flush if a shared buffer is used otherwise audioflinger
407 // will not stop before end of buffer is reached.
408 if (mSharedBuffer != 0) {
Eric Laurent1703cdf2011-03-07 14:52:59 -0800409 flush_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800410 }
411 if (t != 0) {
412 t->requestExit();
413 } else {
414 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
415 }
416 }
417
418 if (t != 0) {
419 t->mLock.unlock();
420 }
421}
422
423bool AudioTrack::stopped() const
424{
425 return !mActive;
426}
427
428void AudioTrack::flush()
429{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800430 AutoMutex lock(mLock);
431 flush_l();
432}
433
434// must be called with mLock held
435void AudioTrack::flush_l()
436{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800437 LOGV("flush");
Eric Laurentc2f1f072009-07-17 12:17:14 -0700438
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700439 // clear playback marker and periodic update counter
440 mMarkerPosition = 0;
441 mMarkerReached = false;
442 mUpdatePeriod = 0;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700443
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800444 if (!mActive) {
Jean-Michel Trivicd075942011-08-25 16:47:23 -0700445 mFlushed = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800446 mAudioTrack->flush();
447 // Release AudioTrack callback thread in case it was waiting for new buffers
448 // in AudioTrack::obtainBuffer()
449 mCblk->cv.signal();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800450 }
451}
452
453void AudioTrack::pause()
454{
455 LOGV("pause");
Eric Laurentf5aafb22010-11-18 08:40:16 -0800456 AutoMutex lock(mLock);
457 if (mActive == 1) {
458 mActive = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800459 mAudioTrack->pause();
460 }
461}
462
463void AudioTrack::mute(bool e)
464{
465 mAudioTrack->mute(e);
466 mMuted = e;
467}
468
469bool AudioTrack::muted() const
470{
471 return mMuted;
472}
473
Eric Laurentbe916aa2010-06-01 23:49:17 -0700474status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475{
Eric Laurentbe916aa2010-06-01 23:49:17 -0700476 if (left > 1.0f || right > 1.0f) {
477 return BAD_VALUE;
478 }
479
Eric Laurent1703cdf2011-03-07 14:52:59 -0800480 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800481 mVolume[LEFT] = left;
482 mVolume[RIGHT] = right;
483
484 // write must be atomic
Eric Laurentbe916aa2010-06-01 23:49:17 -0700485 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
486
487 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488}
489
490void AudioTrack::getVolume(float* left, float* right)
491{
Eric Laurentbe916aa2010-06-01 23:49:17 -0700492 if (left != NULL) {
493 *left = mVolume[LEFT];
494 }
495 if (right != NULL) {
496 *right = mVolume[RIGHT];
497 }
498}
499
Eric Laurent2beeb502010-07-16 07:43:46 -0700500status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700501{
Eric Laurent2beeb502010-07-16 07:43:46 -0700502 LOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700503 if (level > 1.0f) {
504 return BAD_VALUE;
505 }
Eric Laurent1703cdf2011-03-07 14:52:59 -0800506 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700507
508 mSendLevel = level;
509
510 mCblk->sendLevel = uint16_t(level * 0x1000);
511
512 return NO_ERROR;
513}
514
Eric Laurent2beeb502010-07-16 07:43:46 -0700515void AudioTrack::getAuxEffectSendLevel(float* level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700516{
517 if (level != NULL) {
518 *level = mSendLevel;
519 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800520}
521
Eric Laurent57326622009-07-07 07:10:45 -0700522status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800523{
524 int afSamplingRate;
525
Mike J. Chen500e5102011-08-15 13:28:26 -0700526 if (mIsTimed) {
527 return INVALID_OPERATION;
528 }
529
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700531 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800532 }
533 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent57326622009-07-07 07:10:45 -0700534 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800535
Eric Laurent1703cdf2011-03-07 14:52:59 -0800536 AutoMutex lock(mLock);
Eric Laurent57326622009-07-07 07:10:45 -0700537 mCblk->sampleRate = rate;
538 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800539}
540
541uint32_t AudioTrack::getSampleRate()
542{
Mike J. Chen500e5102011-08-15 13:28:26 -0700543 if (mIsTimed) {
544 return INVALID_OPERATION;
545 }
546
Eric Laurent1703cdf2011-03-07 14:52:59 -0800547 AutoMutex lock(mLock);
Eric Laurent57326622009-07-07 07:10:45 -0700548 return mCblk->sampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800549}
550
551status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
552{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800553 AutoMutex lock(mLock);
554 return setLoop_l(loopStart, loopEnd, loopCount);
555}
556
557// must be called with mLock held
558status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
559{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800560 audio_track_cblk_t* cblk = mCblk;
561
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800562 Mutex::Autolock _l(cblk->lock);
563
564 if (loopCount == 0) {
565 cblk->loopStart = UINT_MAX;
566 cblk->loopEnd = UINT_MAX;
567 cblk->loopCount = 0;
568 mLoopCount = 0;
569 return NO_ERROR;
570 }
571
Mike J. Chen500e5102011-08-15 13:28:26 -0700572 if (mIsTimed) {
573 return INVALID_OPERATION;
574 }
575
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576 if (loopStart >= loopEnd ||
Eric Laurent9b7d9502011-03-21 11:49:00 -0700577 loopEnd - loopStart > cblk->frameCount ||
578 cblk->server > loopStart) {
Eric Laurentd1b449a2010-05-14 03:26:45 -0700579 LOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, cblk->frameCount, cblk->user);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580 return BAD_VALUE;
581 }
582
Eric Laurent9b7d9502011-03-21 11:49:00 -0700583 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800584 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurentd1b449a2010-05-14 03:26:45 -0700585 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586 return BAD_VALUE;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700587 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588
589 cblk->loopStart = loopStart;
590 cblk->loopEnd = loopEnd;
591 cblk->loopCount = loopCount;
592 mLoopCount = loopCount;
593
594 return NO_ERROR;
595}
596
597status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
598{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800599 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600 if (loopStart != 0) {
601 *loopStart = mCblk->loopStart;
602 }
603 if (loopEnd != 0) {
604 *loopEnd = mCblk->loopEnd;
605 }
606 if (loopCount != 0) {
607 if (mCblk->loopCount < 0) {
608 *loopCount = -1;
609 } else {
610 *loopCount = mCblk->loopCount;
611 }
612 }
613
614 return NO_ERROR;
615}
616
617status_t AudioTrack::setMarkerPosition(uint32_t marker)
618{
619 if (mCbf == 0) return INVALID_OPERATION;
620
621 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700622 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623
624 return NO_ERROR;
625}
626
627status_t AudioTrack::getMarkerPosition(uint32_t *marker)
628{
629 if (marker == 0) return BAD_VALUE;
630
631 *marker = mMarkerPosition;
632
633 return NO_ERROR;
634}
635
636status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
637{
638 if (mCbf == 0) return INVALID_OPERATION;
639
640 uint32_t curPosition;
641 getPosition(&curPosition);
642 mNewPosition = curPosition + updatePeriod;
643 mUpdatePeriod = updatePeriod;
644
645 return NO_ERROR;
646}
647
648status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
649{
650 if (updatePeriod == 0) return BAD_VALUE;
651
652 *updatePeriod = mUpdatePeriod;
653
654 return NO_ERROR;
655}
656
657status_t AudioTrack::setPosition(uint32_t position)
658{
Mike J. Chen500e5102011-08-15 13:28:26 -0700659 if (mIsTimed) return INVALID_OPERATION;
660
Eric Laurent1703cdf2011-03-07 14:52:59 -0800661 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800662 Mutex::Autolock _l(mCblk->lock);
663
664 if (!stopped()) return INVALID_OPERATION;
665
666 if (position > mCblk->user) return BAD_VALUE;
667
668 mCblk->server = position;
Eric Laurent38ccae22011-03-28 18:37:07 -0700669 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700670
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800671 return NO_ERROR;
672}
673
674status_t AudioTrack::getPosition(uint32_t *position)
675{
676 if (position == 0) return BAD_VALUE;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800677 AutoMutex lock(mLock);
Jean-Michel Trivicd075942011-08-25 16:47:23 -0700678 *position = mFlushed ? 0 : mCblk->server;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800679
680 return NO_ERROR;
681}
682
683status_t AudioTrack::reload()
684{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800685 AutoMutex lock(mLock);
686
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800687 if (!stopped()) return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700688
Eric Laurent1703cdf2011-03-07 14:52:59 -0800689 flush_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800690
Eric Laurentd1b449a2010-05-14 03:26:45 -0700691 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800692
693 return NO_ERROR;
694}
695
Eric Laurentc2f1f072009-07-17 12:17:14 -0700696audio_io_handle_t AudioTrack::getOutput()
697{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800698 AutoMutex lock(mLock);
699 return getOutput_l();
700}
701
702// must be called with mLock held
703audio_io_handle_t AudioTrack::getOutput_l()
704{
Dima Zavinfce7a472011-04-19 22:30:36 -0700705 return AudioSystem::getOutput((audio_stream_type_t)mStreamType,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700706 mCblk->sampleRate, mFormat, mChannelMask, (audio_policy_output_flags_t)mFlags);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700707}
708
Eric Laurentbe916aa2010-06-01 23:49:17 -0700709int AudioTrack::getSessionId()
710{
711 return mSessionId;
712}
713
714status_t AudioTrack::attachAuxEffect(int effectId)
715{
Eric Laurent2beeb502010-07-16 07:43:46 -0700716 LOGV("attachAuxEffect(%d)", effectId);
717 status_t status = mAudioTrack->attachAuxEffect(effectId);
718 if (status == NO_ERROR) {
719 mAuxEffectId = effectId;
720 }
721 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700722}
723
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724// -------------------------------------------------------------------------
725
Eric Laurent1703cdf2011-03-07 14:52:59 -0800726// must be called with mLock held
727status_t AudioTrack::createTrack_l(
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800728 int streamType,
729 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700730 uint32_t format,
731 uint32_t channelMask,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800732 int frameCount,
733 uint32_t flags,
734 const sp<IMemory>& sharedBuffer,
Eric Laurentd1b449a2010-05-14 03:26:45 -0700735 audio_io_handle_t output,
736 bool enforceFrameCount)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800737{
738 status_t status;
739 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
740 if (audioFlinger == 0) {
741 LOGE("Could not get audioflinger");
742 return NO_INIT;
743 }
744
Eric Laurentd1b449a2010-05-14 03:26:45 -0700745 int afSampleRate;
746 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
747 return NO_INIT;
748 }
749 int afFrameCount;
750 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
751 return NO_INIT;
752 }
753 uint32_t afLatency;
754 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
755 return NO_INIT;
756 }
757
758 mNotificationFramesAct = mNotificationFramesReq;
Dima Zavinfce7a472011-04-19 22:30:36 -0700759 if (!audio_is_linear_pcm(format)) {
Eric Laurentd1b449a2010-05-14 03:26:45 -0700760 if (sharedBuffer != 0) {
761 frameCount = sharedBuffer->size();
762 }
763 } else {
764 // Ensure that buffer depth covers at least audio hardware latency
765 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
766 if (minBufCount < 2) minBufCount = 2;
767
768 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
769
770 if (sharedBuffer == 0) {
771 if (frameCount == 0) {
772 frameCount = minFrameCount;
773 }
774 if (mNotificationFramesAct == 0) {
775 mNotificationFramesAct = frameCount/2;
776 }
777 // Make sure that application is notified with sufficient margin
778 // before underrun
779 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
780 mNotificationFramesAct = frameCount/2;
781 }
782 if (frameCount < minFrameCount) {
Eric Laurentde61a782012-03-05 17:06:40 -0800783 LOGW_IF(enforceFrameCount, "Minimum buffer size corrected from %d to %d",
784 frameCount, minFrameCount);
785 frameCount = minFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700786 }
787 } else {
788 // Ensure that buffer alignment matches channelcount
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700789 int channelCount = popcount(channelMask);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700790 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
791 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
792 return BAD_VALUE;
793 }
794 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
795 }
796 }
797
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800798 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
799 streamType,
800 sampleRate,
801 format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700802 channelMask,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800803 frameCount,
804 ((uint16_t)flags) << 16,
805 sharedBuffer,
806 output,
Mike J. Chen500e5102011-08-15 13:28:26 -0700807 mIsTimed,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700808 &mSessionId,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800809 &status);
810
811 if (track == 0) {
812 LOGE("AudioFlinger could not create track, status: %d", status);
813 return status;
814 }
815 sp<IMemory> cblk = track->getCblk();
816 if (cblk == 0) {
817 LOGE("Could not get control block");
818 return NO_INIT;
819 }
820 mAudioTrack.clear();
821 mAudioTrack = track;
822 mCblkMemory.clear();
823 mCblkMemory = cblk;
824 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurent38ccae22011-03-28 18:37:07 -0700825 android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800826 if (sharedBuffer == 0) {
827 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
828 } else {
829 mCblk->buffers = sharedBuffer->pointer();
830 // Force buffer full condition as data is already present in shared memory
Eric Laurentd1b449a2010-05-14 03:26:45 -0700831 mCblk->stepUser(mCblk->frameCount);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800832 }
833
Eric Laurentbe916aa2010-06-01 23:49:17 -0700834 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
835 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent2beeb502010-07-16 07:43:46 -0700836 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent6100d2d2009-11-19 09:00:56 -0800837 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
838 mCblk->waitTimeMs = 0;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700839 mRemainingFrames = mNotificationFramesAct;
840 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800841 return NO_ERROR;
842}
843
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800844status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
845{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800846 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800847 int active;
Glenn Kastend0965dd2011-06-22 16:18:04 -0700848 status_t result = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800849 audio_track_cblk_t* cblk = mCblk;
850 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurent1dd70b92009-04-21 07:56:33 -0700851 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800852
853 audioBuffer->frameCount = 0;
854 audioBuffer->size = 0;
855
856 uint32_t framesAvail = cblk->framesAvailable();
857
Eric Laurent9b7d9502011-03-21 11:49:00 -0700858 cblk->lock.lock();
859 if (cblk->flags & CBLK_INVALID_MSK) {
860 goto create_new_track;
861 }
862 cblk->lock.unlock();
863
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800864 if (framesAvail == 0) {
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800865 cblk->lock.lock();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800866 goto start_loop_here;
867 while (framesAvail == 0) {
868 active = mActive;
869 if (UNLIKELY(!active)) {
870 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800871 cblk->lock.unlock();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800872 return NO_MORE_BUFFERS;
873 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800874 if (UNLIKELY(!waitCount)) {
875 cblk->lock.unlock();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800876 return WOULD_BLOCK;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800877 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700878 if (!(cblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent1703cdf2011-03-07 14:52:59 -0800879 mLock.unlock();
Eric Laurentd1b449a2010-05-14 03:26:45 -0700880 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurentd1b449a2010-05-14 03:26:45 -0700881 cblk->lock.unlock();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800882 mLock.lock();
883 if (mActive == 0) {
884 return status_t(STOPPED);
885 }
886 cblk->lock.lock();
887 }
888
889 if (cblk->flags & CBLK_INVALID_MSK) {
Eric Laurentd1b449a2010-05-14 03:26:45 -0700890 goto create_new_track;
891 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700892 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurent1dd70b92009-04-21 07:56:33 -0700893 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800894 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
895 // timing out when a loop has been set and we have already written upto loop end
896 // is a normal condition: no need to wake AudioFlinger up.
897 if (cblk->user < cblk->loopEnd) {
898 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
899 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700900 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800901 cblk->lock.unlock();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800902 result = mAudioTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800903 cblk->lock.lock();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800904 if (result == DEAD_OBJECT) {
Eric Laurent38ccae22011-03-28 18:37:07 -0700905 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent1703cdf2011-03-07 14:52:59 -0800906create_new_track:
907 result = restoreTrack_l(cblk, false);
908 }
909 if (result != NO_ERROR) {
910 LOGW("obtainBuffer create Track error %d", result);
911 cblk->lock.unlock();
912 return result;
913 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800914 }
915 cblk->waitTimeMs = 0;
916 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700917
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800918 if (--waitCount == 0) {
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800919 cblk->lock.unlock();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800920 return TIMED_OUT;
921 }
922 }
923 // read the server count again
924 start_loop_here:
925 framesAvail = cblk->framesAvailable_l();
926 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800927 cblk->lock.unlock();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800928 }
929
Eric Laurent44d98482010-09-30 16:12:31 -0700930 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent1703cdf2011-03-07 14:52:59 -0800931 if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
Eric Laurent38ccae22011-03-28 18:37:07 -0700932 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
933 LOGW("obtainBuffer() track %p disabled, restarting", this);
934 mAudioTrack->start();
Eric Laurent44d98482010-09-30 16:12:31 -0700935 }
936
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800937 cblk->waitTimeMs = 0;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700938
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800939 if (framesReq > framesAvail) {
940 framesReq = framesAvail;
941 }
942
943 uint32_t u = cblk->user;
944 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
945
946 if (u + framesReq > bufferEnd) {
947 framesReq = bufferEnd - u;
948 }
949
Eric Laurentc2f1f072009-07-17 12:17:14 -0700950 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
951 audioBuffer->channelCount = mChannelCount;
952 audioBuffer->frameCount = framesReq;
953 audioBuffer->size = framesReq * cblk->frameSize;
Dima Zavinfce7a472011-04-19 22:30:36 -0700954 if (audio_is_linear_pcm(mFormat)) {
955 audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700956 } else {
957 audioBuffer->format = mFormat;
958 }
959 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800960 active = mActive;
961 return active ? status_t(NO_ERROR) : status_t(STOPPED);
962}
963
964void AudioTrack::releaseBuffer(Buffer* audioBuffer)
965{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800966 AutoMutex lock(mLock);
967 mCblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800968}
969
970// -------------------------------------------------------------------------
971
972ssize_t AudioTrack::write(const void* buffer, size_t userSize)
973{
974
975 if (mSharedBuffer != 0) return INVALID_OPERATION;
Mike J. Chen500e5102011-08-15 13:28:26 -0700976 if (mIsTimed) return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800977
978 if (ssize_t(userSize) < 0) {
979 // sanity-check. user is most-likely passing an error code.
980 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
981 buffer, userSize, userSize);
982 return BAD_VALUE;
983 }
984
985 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
986
Eric Laurent1703cdf2011-03-07 14:52:59 -0800987 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
988 // while we are accessing the cblk
989 mLock.lock();
990 sp <IAudioTrack> audioTrack = mAudioTrack;
991 sp <IMemory> iMem = mCblkMemory;
992 mLock.unlock();
993
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800994 ssize_t written = 0;
995 const int8_t *src = (const int8_t *)buffer;
996 Buffer audioBuffer;
Eric Laurent33797ea2011-03-17 09:36:51 -0700997 size_t frameSz = (size_t)frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800998
999 do {
Eric Laurent33797ea2011-03-17 09:36:51 -07001000 audioBuffer.frameCount = userSize/frameSz;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001001
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001002 // Calling obtainBuffer() with a negative wait count causes
1003 // an (almost) infinite wait time.
1004 status_t err = obtainBuffer(&audioBuffer, -1);
1005 if (err < 0) {
1006 // out of buffers, return #bytes written
1007 if (err == status_t(NO_MORE_BUFFERS))
1008 break;
1009 return ssize_t(err);
1010 }
1011
1012 size_t toWrite;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001013
Dima Zavinfce7a472011-04-19 22:30:36 -07001014 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001015 // Divide capacity by 2 to take expansion into account
1016 toWrite = audioBuffer.size>>1;
1017 // 8 to 16 bit conversion
1018 int count = toWrite;
1019 int16_t *dst = (int16_t *)(audioBuffer.i8);
1020 while(count--) {
1021 *dst++ = (int16_t)(*src++^0x80) << 8;
1022 }
Eric Laurent33025262009-08-04 10:42:26 -07001023 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001024 toWrite = audioBuffer.size;
1025 memcpy(audioBuffer.i8, src, toWrite);
1026 src += toWrite;
1027 }
1028 userSize -= toWrite;
1029 written += toWrite;
1030
1031 releaseBuffer(&audioBuffer);
Eric Laurent33797ea2011-03-17 09:36:51 -07001032 } while (userSize >= frameSz);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001033
1034 return written;
1035}
1036
1037// -------------------------------------------------------------------------
1038
Mike J. Chen500e5102011-08-15 13:28:26 -07001039TimedAudioTrack::TimedAudioTrack() {
1040 mIsTimed = true;
1041}
1042
1043status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1044{
1045 return mAudioTrack->allocateTimedBuffer(size, buffer);
1046}
1047
1048status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1049 int64_t pts)
1050{
1051 // restart track if it was disabled by audioflinger due to previous underrun
1052 if (mActive && (mCblk->flags & CBLK_DISABLED_MSK)) {
1053 mCblk->flags &= ~CBLK_DISABLED_ON;
1054 LOGW("queueTimedBuffer() track %p disabled, restarting", this);
1055 mAudioTrack->start();
1056 }
1057
1058 return mAudioTrack->queueTimedBuffer(buffer, pts);
1059}
1060
1061status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1062 TargetTimeline target)
1063{
1064 return mAudioTrack->setMediaTimeTransform(xform, target);
1065}
1066
1067// -------------------------------------------------------------------------
1068
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001069bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1070{
1071 Buffer audioBuffer;
1072 uint32_t frames;
1073 size_t writtenSize;
1074
Eric Laurent1703cdf2011-03-07 14:52:59 -08001075 mLock.lock();
1076 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1077 // while we are accessing the cblk
1078 sp <IAudioTrack> audioTrack = mAudioTrack;
1079 sp <IMemory> iMem = mCblkMemory;
1080 audio_track_cblk_t* cblk = mCblk;
1081 mLock.unlock();
1082
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001083 // Manage underrun callback
Eric Laurent38ccae22011-03-28 18:37:07 -07001084 if (mActive && (cblk->framesAvailable() == cblk->frameCount)) {
Eric Laurent1703cdf2011-03-07 14:52:59 -08001085 LOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
Eric Laurent38ccae22011-03-28 18:37:07 -07001086 if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001087 mCbf(EVENT_UNDERRUN, mUserData, 0);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001088 if (cblk->server == cblk->frameCount) {
Eric Laurentc2f1f072009-07-17 12:17:14 -07001089 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001090 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001091 if (mSharedBuffer != 0) return false;
1092 }
1093 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001094
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001095 // Manage loop end callback
Eric Laurent1703cdf2011-03-07 14:52:59 -08001096 while (mLoopCount > cblk->loopCount) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001097 int loopCount = -1;
1098 mLoopCount--;
1099 if (mLoopCount >= 0) loopCount = mLoopCount;
1100
1101 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1102 }
1103
1104 // Manage marker callback
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -07001105 if (!mMarkerReached && (mMarkerPosition > 0)) {
Eric Laurent1703cdf2011-03-07 14:52:59 -08001106 if (cblk->server >= mMarkerPosition) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001107 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -07001108 mMarkerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001109 }
1110 }
1111
1112 // Manage new position callback
Eric Laurentc2f1f072009-07-17 12:17:14 -07001113 if (mUpdatePeriod > 0) {
Eric Laurent1703cdf2011-03-07 14:52:59 -08001114 while (cblk->server >= mNewPosition) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001115 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1116 mNewPosition += mUpdatePeriod;
1117 }
1118 }
1119
1120 // If Shared buffer is used, no data is requested from client.
1121 if (mSharedBuffer != 0) {
1122 frames = 0;
1123 } else {
1124 frames = mRemainingFrames;
1125 }
1126
Eric Laurent2267ba12011-09-07 11:13:23 -07001127 int32_t waitCount = -1;
1128 if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) {
1129 waitCount = 1;
1130 }
1131
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001132 do {
1133
1134 audioBuffer.frameCount = frames;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001135
1136 // Calling obtainBuffer() with a wait count of 1
1137 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1138 // stuck here not being able to handle timed events (position, markers, loops).
Eric Laurent2267ba12011-09-07 11:13:23 -07001139 status_t err = obtainBuffer(&audioBuffer, waitCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001140 if (err < NO_ERROR) {
1141 if (err != TIMED_OUT) {
Eric Laurent1dd70b92009-04-21 07:56:33 -07001142 LOGE_IF(err != status_t(NO_MORE_BUFFERS), "Error obtaining an audio buffer, giving up.");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001143 return false;
1144 }
1145 break;
1146 }
1147 if (err == status_t(STOPPED)) return false;
1148
1149 // Divide buffer size by 2 to take into account the expansion
1150 // due to 8 to 16 bit conversion: the callback must fill only half
1151 // of the destination buffer
Dima Zavinfce7a472011-04-19 22:30:36 -07001152 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001153 audioBuffer.size >>= 1;
1154 }
1155
1156 size_t reqSize = audioBuffer.size;
1157 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1158 writtenSize = audioBuffer.size;
1159
1160 // Sanity check on returned size
The Android Open Source Project8555d082009-03-05 14:34:35 -08001161 if (ssize_t(writtenSize) <= 0) {
1162 // The callback is done filling buffers
1163 // Keep this thread going to handle timed events and
1164 // still try to get more data in intervals of WAIT_PERIOD_MS
1165 // but don't just loop and block the CPU, so wait
1166 usleep(WAIT_PERIOD_MS*1000);
1167 break;
1168 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001169 if (writtenSize > reqSize) writtenSize = reqSize;
1170
Dima Zavinfce7a472011-04-19 22:30:36 -07001171 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001172 // 8 to 16 bit conversion
1173 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1174 int count = writtenSize;
1175 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1176 while(count--) {
1177 *dst-- = (int16_t)(*src--^0x80) << 8;
1178 }
1179 writtenSize <<= 1;
1180 }
1181
1182 audioBuffer.size = writtenSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001183 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1184 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1185 // 16 bit.
1186 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1187
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001188 frames -= audioBuffer.frameCount;
1189
1190 releaseBuffer(&audioBuffer);
1191 }
1192 while (frames);
1193
1194 if (frames == 0) {
Eric Laurentd1b449a2010-05-14 03:26:45 -07001195 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001196 } else {
1197 mRemainingFrames = frames;
1198 }
1199 return true;
1200}
1201
Eric Laurent1703cdf2011-03-07 14:52:59 -08001202// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1203// the IAudioTrack and IMemory in case they are recreated here.
1204// If the IAudioTrack is successfully restored, the cblk pointer is updated
1205status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1206{
1207 status_t result;
1208
Eric Laurent38ccae22011-03-28 18:37:07 -07001209 if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
Eric Laurentcfe2ba62011-09-13 15:04:17 -07001210 LOGW("dead IAudioTrack, creating a new one from %s TID %d",
1211 fromStart ? "start()" : "obtainBuffer()", gettid());
Eric Laurent1703cdf2011-03-07 14:52:59 -08001212
Eric Laurent1703cdf2011-03-07 14:52:59 -08001213 // signal old cblk condition so that other threads waiting for available buffers stop
1214 // waiting now
1215 cblk->cv.broadcast();
1216 cblk->lock.unlock();
1217
Eric Laurent9f6530f2011-08-30 10:18:54 -07001218 // refresh the audio configuration cache in this process to make sure we get new
1219 // output parameters in getOutput_l() and createTrack_l()
1220 AudioSystem::clearAudioConfigCache();
1221
Eric Laurent1703cdf2011-03-07 14:52:59 -08001222 // if the new IAudioTrack is created, createTrack_l() will modify the
1223 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1224 // It will also delete the strong references on previous IAudioTrack and IMemory
1225 result = createTrack_l(mStreamType,
1226 cblk->sampleRate,
1227 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001228 mChannelMask,
Eric Laurent1703cdf2011-03-07 14:52:59 -08001229 mFrameCount,
1230 mFlags,
1231 mSharedBuffer,
1232 getOutput_l(),
1233 false);
1234
1235 if (result == NO_ERROR) {
Eric Laurent408b8dc2011-09-06 12:36:15 -07001236 uint32_t user = cblk->user;
1237 uint32_t server = cblk->server;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001238 // restore write index and set other indexes to reflect empty buffer status
Eric Laurent408b8dc2011-09-06 12:36:15 -07001239 mCblk->user = user;
1240 mCblk->server = user;
1241 mCblk->userBase = user;
1242 mCblk->serverBase = user;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001243 // restore loop: this is not guaranteed to succeed if new frame count is not
1244 // compatible with loop length
1245 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001246 if (!fromStart) {
1247 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
Eric Laurent408b8dc2011-09-06 12:36:15 -07001248 // Make sure that a client relying on callback events indicating underrun or
1249 // the actual amount of audio frames played (e.g SoundPool) receives them.
1250 if (mSharedBuffer == 0) {
1251 uint32_t frames = 0;
1252 if (user > server) {
1253 frames = ((user - server) > mCblk->frameCount) ?
1254 mCblk->frameCount : (user - server);
1255 memset(mCblk->buffers, 0, frames * mCblk->frameSize);
1256 }
1257 // restart playback even if buffer is not completely filled.
1258 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
1259 // stepUser() clears CBLK_UNDERRUN_ON flag enabling underrun callbacks to
1260 // the client
1261 mCblk->stepUser(frames);
1262 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001263 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001264 if (mActive) {
1265 result = mAudioTrack->start();
Eric Laurentcfe2ba62011-09-13 15:04:17 -07001266 LOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result);
Eric Laurent9b7d9502011-03-21 11:49:00 -07001267 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001268 if (fromStart && result == NO_ERROR) {
1269 mNewPosition = mCblk->server + mUpdatePeriod;
1270 }
1271 }
1272 if (result != NO_ERROR) {
Eric Laurentcfe2ba62011-09-13 15:04:17 -07001273 android_atomic_and(~CBLK_RESTORING_ON, &cblk->flags);
1274 LOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001275 }
Eric Laurentcfe2ba62011-09-13 15:04:17 -07001276 mRestoreStatus = result;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001277 // signal old cblk condition for other threads waiting for restore completion
Eric Laurent38ccae22011-03-28 18:37:07 -07001278 android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001279 cblk->cv.broadcast();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001280 } else {
1281 if (!(cblk->flags & CBLK_RESTORED_MSK)) {
Eric Laurentcfe2ba62011-09-13 15:04:17 -07001282 LOGW("dead IAudioTrack, waiting for a new one TID %d", gettid());
Eric Laurent1703cdf2011-03-07 14:52:59 -08001283 mLock.unlock();
1284 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
Eric Laurentcfe2ba62011-09-13 15:04:17 -07001285 if (result == NO_ERROR) {
1286 result = mRestoreStatus;
1287 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001288 cblk->lock.unlock();
1289 mLock.lock();
1290 } else {
Eric Laurentcfe2ba62011-09-13 15:04:17 -07001291 LOGW("dead IAudioTrack, already restored TID %d", gettid());
1292 result = mRestoreStatus;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001293 cblk->lock.unlock();
1294 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001295 }
1296 LOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1297 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1298
1299 if (result == NO_ERROR) {
1300 // from now on we switch to the newly created cblk
1301 cblk = mCblk;
1302 }
1303 cblk->lock.lock();
1304
Eric Laurentcfe2ba62011-09-13 15:04:17 -07001305 LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d TID %d", result, gettid());
Eric Laurent1703cdf2011-03-07 14:52:59 -08001306
1307 return result;
1308}
1309
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001310status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1311{
1312
1313 const size_t SIZE = 256;
1314 char buffer[SIZE];
1315 String8 result;
1316
1317 result.append(" AudioTrack::dump\n");
1318 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1319 result.append(buffer);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001320 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mCblk->frameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001321 result.append(buffer);
Eric Laurent57326622009-07-07 07:10:45 -07001322 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001323 result.append(buffer);
1324 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1325 result.append(buffer);
1326 ::write(fd, result.string(), result.size());
1327 return NO_ERROR;
1328}
1329
1330// =========================================================================
1331
1332AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1333 : Thread(bCanCallJava), mReceiver(receiver)
1334{
1335}
1336
1337bool AudioTrack::AudioTrackThread::threadLoop()
1338{
1339 return mReceiver.processAudioBuffer(this);
1340}
1341
1342status_t AudioTrack::AudioTrackThread::readyToRun()
1343{
1344 return NO_ERROR;
1345}
1346
1347void AudioTrack::AudioTrackThread::onFirstRef()
1348{
1349}
1350
1351// =========================================================================
1352
Eric Laurent38ccae22011-03-28 18:37:07 -07001353
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001354audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopian54b1a052010-03-19 16:14:13 -07001355 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1356 userBase(0), serverBase(0), buffers(0), frameCount(0),
1357 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurent38ccae22011-03-28 18:37:07 -07001358 sendLevel(0), flags(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359{
1360}
1361
1362uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1363{
1364 uint32_t u = this->user;
1365
1366 u += frameCount;
1367 // Ensure that user is never ahead of server for AudioRecord
Eric Laurentd1b449a2010-05-14 03:26:45 -07001368 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001369 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1370 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1371 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1372 }
1373 } else if (u > this->server) {
1374 LOGW("stepServer occured after track reset");
1375 u = this->server;
1376 }
1377
1378 if (u >= userBase + this->frameCount) {
1379 userBase += this->frameCount;
1380 }
1381
1382 this->user = u;
1383
1384 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurent33797ea2011-03-17 09:36:51 -07001385 if (flags & CBLK_UNDERRUN_MSK) {
Eric Laurent38ccae22011-03-28 18:37:07 -07001386 android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
Eric Laurent33797ea2011-03-17 09:36:51 -07001387 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388
1389 return u;
1390}
1391
1392bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1393{
Eric Laurent38ccae22011-03-28 18:37:07 -07001394 if (!tryLock()) {
1395 LOGW("stepServer() could not lock cblk");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001396 return false;
1397 }
1398
1399 uint32_t s = this->server;
1400
1401 s += frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001402 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001403 // Mark that we have read the first buffer so that next time stepUser() is called
1404 // we switch to normal obtainBuffer() timeout period
1405 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001406 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001407 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408 // It is possible that we receive a flush()
1409 // while the mixer is processing a block: in this case,
1410 // stepServer() is called After the flush() has reset u & s and
1411 // we have s > u
1412 if (s > this->user) {
1413 LOGW("stepServer occured after track reset");
1414 s = this->user;
1415 }
1416 }
1417
1418 if (s >= loopEnd) {
1419 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1420 s = loopStart;
1421 if (--loopCount == 0) {
1422 loopEnd = UINT_MAX;
1423 loopStart = UINT_MAX;
1424 }
1425 }
1426 if (s >= serverBase + this->frameCount) {
1427 serverBase += this->frameCount;
1428 }
1429
1430 this->server = s;
1431
Eric Laurent1703cdf2011-03-07 14:52:59 -08001432 if (!(flags & CBLK_INVALID_MSK)) {
1433 cv.signal();
1434 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001435 lock.unlock();
1436 return true;
1437}
1438
1439void* audio_track_cblk_t::buffer(uint32_t offset) const
1440{
Eric Laurentc2f1f072009-07-17 12:17:14 -07001441 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001442}
1443
1444uint32_t audio_track_cblk_t::framesAvailable()
1445{
1446 Mutex::Autolock _l(lock);
1447 return framesAvailable_l();
1448}
1449
1450uint32_t audio_track_cblk_t::framesAvailable_l()
1451{
1452 uint32_t u = this->user;
1453 uint32_t s = this->server;
1454
Eric Laurentd1b449a2010-05-14 03:26:45 -07001455 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001456 uint32_t limit = (s < loopStart) ? s : loopStart;
1457 return limit + frameCount - u;
1458 } else {
1459 return frameCount + u - s;
1460 }
1461}
1462
1463uint32_t audio_track_cblk_t::framesReady()
1464{
1465 uint32_t u = this->user;
1466 uint32_t s = this->server;
1467
Eric Laurentd1b449a2010-05-14 03:26:45 -07001468 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001469 if (u < loopEnd) {
1470 return u - s;
1471 } else {
Eric Laurent38ccae22011-03-28 18:37:07 -07001472 // do not block on mutex shared with client on AudioFlinger side
1473 if (!tryLock()) {
1474 LOGW("framesReady() could not lock cblk");
1475 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001476 }
Eric Laurent38ccae22011-03-28 18:37:07 -07001477 uint32_t frames = UINT_MAX;
1478 if (loopCount >= 0) {
1479 frames = (loopEnd - loopStart)*loopCount + u - s;
1480 }
1481 lock.unlock();
1482 return frames;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001483 }
1484 } else {
1485 return s - u;
1486 }
1487}
1488
Eric Laurent38ccae22011-03-28 18:37:07 -07001489bool audio_track_cblk_t::tryLock()
1490{
1491 // the code below simulates lock-with-timeout
1492 // we MUST do this to protect the AudioFlinger server
1493 // as this lock is shared with the client.
1494 status_t err;
1495
1496 err = lock.tryLock();
1497 if (err == -EBUSY) { // just wait a bit
1498 usleep(1000);
1499 err = lock.tryLock();
1500 }
1501 if (err != NO_ERROR) {
1502 // probably, the client just died.
1503 return false;
1504 }
1505 return true;
1506}
1507
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001508// -------------------------------------------------------------------------
1509
1510}; // namespace android