blob: 4bc534bf2b2e2215cfff410ff56680a0b4d0010b [file] [log] [blame]
The Android Open Source Project9066cfe2009-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 Agopian07952722009-05-19 19:08:10 -070035#include <binder/Parcel.h>
36#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037#include <utils/Timers.h>
Eric Laurentae29b762011-03-28 18:37:07 -070038#include <utils/Atomic.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039
Dima Zavin24fc2fb2011-04-19 22:30:36 -070040#include <cutils/bitops.h>
41
Dima Zavin34bb4192011-05-11 14:15:23 -070042#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070043#include <system/audio_policy.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070044
The Android Open Source Project9066cfe2009-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 Yehbd240c22010-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 Project9066cfe2009-03-03 19:31:44 -080078
79// ---------------------------------------------------------------------------
80
81AudioTrack::AudioTrack()
Mike J. Chenc94519c2011-08-15 13:28:26 -070082 : mStatus(NO_INIT),
83 mIsTimed(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084{
85}
86
87AudioTrack::AudioTrack(
88 int streamType,
89 uint32_t sampleRate,
90 int format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -070091 int channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 int frameCount,
93 uint32_t flags,
94 callback_t cbf,
95 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -070096 int notificationFrames,
97 int sessionId)
Mike J. Chenc94519c2011-08-15 13:28:26 -070098 : mStatus(NO_INIT),
99 mIsTimed(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100{
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700101 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurent619346f2010-06-21 09:27:30 -0700102 frameCount, flags, cbf, user, notificationFrames,
103 0, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104}
105
106AudioTrack::AudioTrack(
107 int streamType,
108 uint32_t sampleRate,
109 int format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700110 int channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 const sp<IMemory>& sharedBuffer,
112 uint32_t flags,
113 callback_t cbf,
114 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -0700115 int notificationFrames,
116 int sessionId)
Mike J. Chenc94519c2011-08-15 13:28:26 -0700117 : mStatus(NO_INIT),
118 mIsTimed(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119{
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700120 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurent619346f2010-06-21 09:27:30 -0700121 0, flags, cbf, user, notificationFrames,
122 sharedBuffer, false, sessionId);
The Android Open Source Project9066cfe2009-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 Project9066cfe2009-03-03 19:31:44 -0800135 mAudioTrackThread->requestExitAndWait();
136 mAudioTrackThread.clear();
137 }
138 mAudioTrack.clear();
139 IPCThreadState::self()->flushCommands();
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700140 AudioSystem::releaseAudioSessionId(mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 }
142}
143
144status_t AudioTrack::set(
145 int streamType,
146 uint32_t sampleRate,
147 int format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700148 int channelMask,
The Android Open Source Project9066cfe2009-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 Laurent65b65452010-06-01 23:49:17 -0700155 bool threadCanCallJava,
156 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157{
158
159 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
160
Eric Laurent421ddc02011-03-07 14:52:59 -0800161 AutoMutex lock(mLock);
Eric Laurentef028272009-04-21 07:56:33 -0700162 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 LOGE("Track already in use");
164 return INVALID_OPERATION;
165 }
166
The Android Open Source Project9066cfe2009-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 Project9066cfe2009-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 Zavin24fc2fb2011-04-19 22:30:36 -0700177 if (streamType == AUDIO_STREAM_DEFAULT) {
178 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-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 Zavin24fc2fb2011-04-19 22:30:36 -0700185 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 }
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700187 if (channelMask == 0) {
188 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 }
190
191 // validate parameters
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700192 if (!audio_is_valid_format(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 LOGE("Invalid format");
194 return BAD_VALUE;
195 }
Eric Laurenta553c252009-07-17 12:17:14 -0700196
197 // force direct flag if format is not linear PCM
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700198 if (!audio_is_linear_pcm(format)) {
199 flags |= AUDIO_POLICY_OUTPUT_FLAG_DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -0700200 }
201
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700202 if (!audio_is_output_channel(channelMask)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700203 LOGE("Invalid channel mask");
204 return BAD_VALUE;
205 }
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700206 uint32_t channelCount = popcount(channelMask);
Eric Laurenta553c252009-07-17 12:17:14 -0700207
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700208 audio_io_handle_t output = AudioSystem::getOutput(
209 (audio_stream_type_t)streamType,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700210 sampleRate,format, channelMask,
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700211 (audio_policy_output_flags_t)flags);
Eric Laurenta553c252009-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 Project9066cfe2009-03-03 19:31:44 -0800215 return BAD_VALUE;
216 }
217
Eric Laurentbda74692009-11-04 08:27:26 -0800218 mVolume[LEFT] = 1.0f;
219 mVolume[RIGHT] = 1.0f;
Eric Laurent65b65452010-06-01 23:49:17 -0700220 mSendLevel = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700221 mFrameCount = frameCount;
222 mNotificationFramesReq = notificationFrames;
Eric Laurent65b65452010-06-01 23:49:17 -0700223 mSessionId = sessionId;
Eric Laurent7070b362010-07-16 07:43:46 -0700224 mAuxEffectId = 0;
Eric Laurent65b65452010-06-01 23:49:17 -0700225
Eric Laurentbda74692009-11-04 08:27:26 -0800226 // create the IAudioTrack
Eric Laurent421ddc02011-03-07 14:52:59 -0800227 status_t status = createTrack_l(streamType,
228 sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700229 (uint32_t)format,
230 (uint32_t)channelMask,
Eric Laurent421ddc02011-03-07 14:52:59 -0800231 frameCount,
232 flags,
233 sharedBuffer,
234 output,
235 true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Eric Laurentbda74692009-11-04 08:27:26 -0800237 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 return status;
239 }
Eric Laurentbda74692009-11-04 08:27:26 -0800240
The Android Open Source Project9066cfe2009-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 Project9066cfe2009-03-03 19:31:44 -0800251 mStreamType = streamType;
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700252 mFormat = (uint32_t)format;
253 mChannelMask = (uint32_t)channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 mChannelCount = channelCount;
255 mSharedBuffer = sharedBuffer;
256 mMuted = false;
257 mActive = 0;
258 mCbf = cbf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 mUserData = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 mLoopCount = 0;
261 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700262 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 mNewPosition = 0;
264 mUpdatePeriod = 0;
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700265 mFlushed = false;
Eric Laurenta553c252009-07-17 12:17:14 -0700266 mFlags = flags;
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700267 AudioSystem::acquireAudioSessionId(mSessionId);
Eric Laurent7e8626f2011-09-13 15:04:17 -0700268 mRestoreStatus = NO_ERROR;
The Android Open Source Project9066cfe2009-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 Project9066cfe2009-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 Laurenteb8f850d2010-05-14 03:26:45 -0700301 return mCblk->frameCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302}
303
304int AudioTrack::frameSize() const
305{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700306 if (audio_is_linear_pcm(mFormat)) {
Eric Laurentc310dcb2011-06-16 21:30:45 -0700307 return channelCount()*audio_bytes_per_sample(mFormat);
Eric Laurenta553c252009-07-17 12:17:14 -0700308 } else {
309 return sizeof(uint8_t);
310 }
The Android Open Source Project9066cfe2009-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 Kasten028ab992011-06-22 16:18:04 -0700323 status_t status = NO_ERROR;
The Android Open Source Project9066cfe2009-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 Laurentf3d6dd02010-11-18 08:40:16 -0800336 AutoMutex lock(mLock);
Eric Laurent421ddc02011-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 Laurentf3d6dd02010-11-18 08:40:16 -0800343 if (mActive == 0) {
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700344 mFlushed = false;
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800345 mActive = 1;
Eric Laurent421ddc02011-03-07 14:52:59 -0800346 mNewPosition = cblk->server + mUpdatePeriod;
Eric Laurent913af0b2011-03-17 09:36:51 -0700347 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800348 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
349 cblk->waitTimeMs = 0;
Eric Laurentae29b762011-03-28 18:37:07 -0700350 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -0800351 if (t != 0) {
Glenn Kasten993fcce2011-06-01 16:46:29 -0700352 t->run("AudioTrackThread", ANDROID_PRIORITY_AUDIO);
Eric Laurent059b4be2009-11-09 23:32:22 -0800353 } else {
Glenn Kasten993fcce2011-06-01 16:46:29 -0700354 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
Eric Laurent059b4be2009-11-09 23:32:22 -0800355 }
356
Eric Laurent421ddc02011-03-07 14:52:59 -0800357 LOGV("start %p before lock cblk %p", this, mCblk);
Eric Laurent421ddc02011-03-07 14:52:59 -0800358 if (!(cblk->flags & CBLK_INVALID_MSK)) {
359 cblk->lock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700360 status = mAudioTrack->start();
Eric Laurent421ddc02011-03-07 14:52:59 -0800361 cblk->lock.lock();
362 if (status == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700363 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent49f02be2009-11-19 09:00:56 -0800364 }
Eric Laurent059b4be2009-11-09 23:32:22 -0800365 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800366 if (cblk->flags & CBLK_INVALID_MSK) {
367 status = restoreTrack_l(cblk, true);
368 }
369 cblk->lock.unlock();
Eric Laurent059b4be2009-11-09 23:32:22 -0800370 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800371 LOGV("start() failed");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800372 mActive = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -0800373 if (t != 0) {
374 t->requestExit();
375 } else {
376 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
377 }
Eric Laurentbda74692009-11-04 08:27:26 -0800378 }
The Android Open Source Project9066cfe2009-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 Laurentf3d6dd02010-11-18 08:40:16 -0800395 AutoMutex lock(mLock);
396 if (mActive == 1) {
397 mActive = 0;
Eric Laurentef028272009-04-21 07:56:33 -0700398 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-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 Laurent421ddc02011-03-07 14:52:59 -0800402 setLoop_l(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-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 Project9066cfe2009-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 Laurent421ddc02011-03-07 14:52:59 -0800409 flush_l();
The Android Open Source Project9066cfe2009-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 Laurent421ddc02011-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 Project9066cfe2009-03-03 19:31:44 -0800437 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700438
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700439 // clear playback marker and periodic update counter
440 mMarkerPosition = 0;
441 mMarkerReached = false;
442 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 if (!mActive) {
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700445 mFlushed = true;
The Android Open Source Project9066cfe2009-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 Project9066cfe2009-03-03 19:31:44 -0800450 }
451}
452
453void AudioTrack::pause()
454{
455 LOGV("pause");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800456 AutoMutex lock(mLock);
457 if (mActive == 1) {
458 mActive = 0;
The Android Open Source Project9066cfe2009-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 Laurent65b65452010-06-01 23:49:17 -0700474status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475{
Eric Laurent65b65452010-06-01 23:49:17 -0700476 if (left > 1.0f || right > 1.0f) {
477 return BAD_VALUE;
478 }
479
Eric Laurent421ddc02011-03-07 14:52:59 -0800480 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 mVolume[LEFT] = left;
482 mVolume[RIGHT] = right;
483
484 // write must be atomic
Eric Laurent65b65452010-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 Project9066cfe2009-03-03 19:31:44 -0800488}
489
490void AudioTrack::getVolume(float* left, float* right)
491{
Eric Laurent65b65452010-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 Laurent7070b362010-07-16 07:43:46 -0700500status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurent65b65452010-06-01 23:49:17 -0700501{
Eric Laurent7070b362010-07-16 07:43:46 -0700502 LOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurent65b65452010-06-01 23:49:17 -0700503 if (level > 1.0f) {
504 return BAD_VALUE;
505 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800506 AutoMutex lock(mLock);
Eric Laurent65b65452010-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 Laurent7070b362010-07-16 07:43:46 -0700515void AudioTrack::getAuxEffectSendLevel(float* level)
Eric Laurent65b65452010-06-01 23:49:17 -0700516{
517 if (level != NULL) {
518 *level = mSendLevel;
519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520}
521
Eric Laurent88e209d2009-07-07 07:10:45 -0700522status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523{
524 int afSamplingRate;
525
Mike J. Chenc94519c2011-08-15 13:28:26 -0700526 if (mIsTimed) {
527 return INVALID_OPERATION;
528 }
529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700531 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 }
533 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700534 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
Eric Laurent421ddc02011-03-07 14:52:59 -0800536 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700537 mCblk->sampleRate = rate;
538 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539}
540
541uint32_t AudioTrack::getSampleRate()
542{
Mike J. Chenc94519c2011-08-15 13:28:26 -0700543 if (mIsTimed) {
544 return INVALID_OPERATION;
545 }
546
Eric Laurent421ddc02011-03-07 14:52:59 -0800547 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700548 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549}
550
551status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
552{
Eric Laurent421ddc02011-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 Project9066cfe2009-03-03 19:31:44 -0800560 audio_track_cblk_t* cblk = mCblk;
561
The Android Open Source Project9066cfe2009-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. Chenc94519c2011-08-15 13:28:26 -0700572 if (mIsTimed) {
573 return INVALID_OPERATION;
574 }
575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 if (loopStart >= loopEnd ||
Eric Laurent6667ac32011-03-21 11:49:00 -0700577 loopEnd - loopStart > cblk->frameCount ||
578 cblk->server > loopStart) {
Eric Laurenteb8f850d2010-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 Project9066cfe2009-03-03 19:31:44 -0800580 return BAD_VALUE;
581 }
582
Eric Laurent6667ac32011-03-21 11:49:00 -0700583 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700585 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700587 }
The Android Open Source Project9066cfe2009-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 Laurent421ddc02011-03-07 14:52:59 -0800599 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-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 Trivi4a5c1a72009-03-24 18:11:07 -0700622 mMarkerReached = false;
The Android Open Source Project9066cfe2009-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. Chenc94519c2011-08-15 13:28:26 -0700659 if (mIsTimed) return INVALID_OPERATION;
660
Eric Laurent421ddc02011-03-07 14:52:59 -0800661 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-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 Laurentae29b762011-03-28 18:37:07 -0700669 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -0700670
The Android Open Source Project9066cfe2009-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 Laurent421ddc02011-03-07 14:52:59 -0800677 AutoMutex lock(mLock);
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700678 *position = mFlushed ? 0 : mCblk->server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679
680 return NO_ERROR;
681}
682
683status_t AudioTrack::reload()
684{
Eric Laurent421ddc02011-03-07 14:52:59 -0800685 AutoMutex lock(mLock);
686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700688
Eric Laurent421ddc02011-03-07 14:52:59 -0800689 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700691 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692
693 return NO_ERROR;
694}
695
Eric Laurenta553c252009-07-17 12:17:14 -0700696audio_io_handle_t AudioTrack::getOutput()
697{
Eric Laurent421ddc02011-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 Zavin24fc2fb2011-04-19 22:30:36 -0700705 return AudioSystem::getOutput((audio_stream_type_t)mStreamType,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700706 mCblk->sampleRate, mFormat, mChannelMask, (audio_policy_output_flags_t)mFlags);
Eric Laurenta553c252009-07-17 12:17:14 -0700707}
708
Eric Laurent65b65452010-06-01 23:49:17 -0700709int AudioTrack::getSessionId()
710{
711 return mSessionId;
712}
713
714status_t AudioTrack::attachAuxEffect(int effectId)
715{
Eric Laurent7070b362010-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 Laurent65b65452010-06-01 23:49:17 -0700722}
723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724// -------------------------------------------------------------------------
725
Eric Laurent421ddc02011-03-07 14:52:59 -0800726// must be called with mLock held
727status_t AudioTrack::createTrack_l(
Eric Laurentbda74692009-11-04 08:27:26 -0800728 int streamType,
729 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700730 uint32_t format,
731 uint32_t channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800732 int frameCount,
733 uint32_t flags,
734 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700735 audio_io_handle_t output,
736 bool enforceFrameCount)
Eric Laurentbda74692009-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 Laurenteb8f850d2010-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 Zavin24fc2fb2011-04-19 22:30:36 -0700759 if (!audio_is_linear_pcm(format)) {
Eric Laurenteb8f850d2010-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) {
783 if (enforceFrameCount) {
784 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
785 return BAD_VALUE;
786 } else {
787 frameCount = minFrameCount;
788 }
789 }
790 } else {
791 // Ensure that buffer alignment matches channelcount
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700792 int channelCount = popcount(channelMask);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700793 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
794 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
795 return BAD_VALUE;
796 }
797 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
798 }
799 }
800
Eric Laurentbda74692009-11-04 08:27:26 -0800801 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
802 streamType,
803 sampleRate,
804 format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700805 channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800806 frameCount,
807 ((uint16_t)flags) << 16,
808 sharedBuffer,
809 output,
Mike J. Chenc94519c2011-08-15 13:28:26 -0700810 mIsTimed,
Eric Laurent65b65452010-06-01 23:49:17 -0700811 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800812 &status);
813
814 if (track == 0) {
815 LOGE("AudioFlinger could not create track, status: %d", status);
816 return status;
817 }
818 sp<IMemory> cblk = track->getCblk();
819 if (cblk == 0) {
820 LOGE("Could not get control block");
821 return NO_INIT;
822 }
823 mAudioTrack.clear();
824 mAudioTrack = track;
825 mCblkMemory.clear();
826 mCblkMemory = cblk;
827 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurentae29b762011-03-28 18:37:07 -0700828 android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
Eric Laurentbda74692009-11-04 08:27:26 -0800829 if (sharedBuffer == 0) {
830 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
831 } else {
832 mCblk->buffers = sharedBuffer->pointer();
833 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700834 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800835 }
836
Eric Laurent65b65452010-06-01 23:49:17 -0700837 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
838 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent7070b362010-07-16 07:43:46 -0700839 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent49f02be2009-11-19 09:00:56 -0800840 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
841 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700842 mRemainingFrames = mNotificationFramesAct;
843 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800844 return NO_ERROR;
845}
846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
848{
Eric Laurent421ddc02011-03-07 14:52:59 -0800849 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 int active;
Glenn Kasten028ab992011-06-22 16:18:04 -0700851 status_t result = NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 audio_track_cblk_t* cblk = mCblk;
853 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700854 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855
856 audioBuffer->frameCount = 0;
857 audioBuffer->size = 0;
858
859 uint32_t framesAvail = cblk->framesAvailable();
860
Eric Laurent6667ac32011-03-21 11:49:00 -0700861 cblk->lock.lock();
862 if (cblk->flags & CBLK_INVALID_MSK) {
863 goto create_new_track;
864 }
865 cblk->lock.unlock();
866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800868 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 goto start_loop_here;
870 while (framesAvail == 0) {
871 active = mActive;
872 if (UNLIKELY(!active)) {
873 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800874 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 return NO_MORE_BUFFERS;
876 }
Eric Laurentbda74692009-11-04 08:27:26 -0800877 if (UNLIKELY(!waitCount)) {
878 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800880 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700881 if (!(cblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800882 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700883 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700884 cblk->lock.unlock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800885 mLock.lock();
886 if (mActive == 0) {
887 return status_t(STOPPED);
888 }
889 cblk->lock.lock();
890 }
891
892 if (cblk->flags & CBLK_INVALID_MSK) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700893 goto create_new_track;
894 }
Eric Laurenta553c252009-07-17 12:17:14 -0700895 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700896 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
898 // timing out when a loop has been set and we have already written upto loop end
899 // is a normal condition: no need to wake AudioFlinger up.
900 if (cblk->user < cblk->loopEnd) {
901 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
902 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700903 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800905 result = mAudioTrack->start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800907 if (result == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700908 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -0800909create_new_track:
910 result = restoreTrack_l(cblk, false);
911 }
912 if (result != NO_ERROR) {
913 LOGW("obtainBuffer create Track error %d", result);
914 cblk->lock.unlock();
915 return result;
916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
918 cblk->waitTimeMs = 0;
919 }
Eric Laurenta553c252009-07-17 12:17:14 -0700920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800922 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 return TIMED_OUT;
924 }
925 }
926 // read the server count again
927 start_loop_here:
928 framesAvail = cblk->framesAvailable_l();
929 }
Eric Laurentbda74692009-11-04 08:27:26 -0800930 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
932
Eric Laurent4712baa2010-09-30 16:12:31 -0700933 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent421ddc02011-03-07 14:52:59 -0800934 if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
Eric Laurentae29b762011-03-28 18:37:07 -0700935 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
936 LOGW("obtainBuffer() track %p disabled, restarting", this);
937 mAudioTrack->start();
Eric Laurent4712baa2010-09-30 16:12:31 -0700938 }
939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 if (framesReq > framesAvail) {
943 framesReq = framesAvail;
944 }
945
946 uint32_t u = cblk->user;
947 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
948
949 if (u + framesReq > bufferEnd) {
950 framesReq = bufferEnd - u;
951 }
952
Eric Laurenta553c252009-07-17 12:17:14 -0700953 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
954 audioBuffer->channelCount = mChannelCount;
955 audioBuffer->frameCount = framesReq;
956 audioBuffer->size = framesReq * cblk->frameSize;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700957 if (audio_is_linear_pcm(mFormat)) {
958 audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurenta553c252009-07-17 12:17:14 -0700959 } else {
960 audioBuffer->format = mFormat;
961 }
962 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 active = mActive;
964 return active ? status_t(NO_ERROR) : status_t(STOPPED);
965}
966
967void AudioTrack::releaseBuffer(Buffer* audioBuffer)
968{
Eric Laurent421ddc02011-03-07 14:52:59 -0800969 AutoMutex lock(mLock);
970 mCblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971}
972
973// -------------------------------------------------------------------------
974
975ssize_t AudioTrack::write(const void* buffer, size_t userSize)
976{
977
978 if (mSharedBuffer != 0) return INVALID_OPERATION;
Mike J. Chenc94519c2011-08-15 13:28:26 -0700979 if (mIsTimed) return INVALID_OPERATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980
981 if (ssize_t(userSize) < 0) {
982 // sanity-check. user is most-likely passing an error code.
983 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
984 buffer, userSize, userSize);
985 return BAD_VALUE;
986 }
987
988 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
989
Eric Laurent421ddc02011-03-07 14:52:59 -0800990 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
991 // while we are accessing the cblk
992 mLock.lock();
993 sp <IAudioTrack> audioTrack = mAudioTrack;
994 sp <IMemory> iMem = mCblkMemory;
995 mLock.unlock();
996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 ssize_t written = 0;
998 const int8_t *src = (const int8_t *)buffer;
999 Buffer audioBuffer;
Eric Laurent913af0b2011-03-17 09:36:51 -07001000 size_t frameSz = (size_t)frameSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001
1002 do {
Eric Laurent913af0b2011-03-17 09:36:51 -07001003 audioBuffer.frameCount = userSize/frameSz;
Eric Laurenta553c252009-07-17 12:17:14 -07001004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 // Calling obtainBuffer() with a negative wait count causes
1006 // an (almost) infinite wait time.
1007 status_t err = obtainBuffer(&audioBuffer, -1);
1008 if (err < 0) {
1009 // out of buffers, return #bytes written
1010 if (err == status_t(NO_MORE_BUFFERS))
1011 break;
1012 return ssize_t(err);
1013 }
1014
1015 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -07001016
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001017 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 // Divide capacity by 2 to take expansion into account
1019 toWrite = audioBuffer.size>>1;
1020 // 8 to 16 bit conversion
1021 int count = toWrite;
1022 int16_t *dst = (int16_t *)(audioBuffer.i8);
1023 while(count--) {
1024 *dst++ = (int16_t)(*src++^0x80) << 8;
1025 }
Eric Laurent28ad42b2009-08-04 10:42:26 -07001026 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 toWrite = audioBuffer.size;
1028 memcpy(audioBuffer.i8, src, toWrite);
1029 src += toWrite;
1030 }
1031 userSize -= toWrite;
1032 written += toWrite;
1033
1034 releaseBuffer(&audioBuffer);
Eric Laurent913af0b2011-03-17 09:36:51 -07001035 } while (userSize >= frameSz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036
1037 return written;
1038}
1039
1040// -------------------------------------------------------------------------
1041
Mike J. Chenc94519c2011-08-15 13:28:26 -07001042TimedAudioTrack::TimedAudioTrack() {
1043 mIsTimed = true;
1044}
1045
1046status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1047{
1048 return mAudioTrack->allocateTimedBuffer(size, buffer);
1049}
1050
1051status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1052 int64_t pts)
1053{
1054 // restart track if it was disabled by audioflinger due to previous underrun
1055 if (mActive && (mCblk->flags & CBLK_DISABLED_MSK)) {
1056 mCblk->flags &= ~CBLK_DISABLED_ON;
1057 LOGW("queueTimedBuffer() track %p disabled, restarting", this);
1058 mAudioTrack->start();
1059 }
1060
1061 return mAudioTrack->queueTimedBuffer(buffer, pts);
1062}
1063
1064status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1065 TargetTimeline target)
1066{
1067 return mAudioTrack->setMediaTimeTransform(xform, target);
1068}
1069
1070// -------------------------------------------------------------------------
1071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1073{
1074 Buffer audioBuffer;
1075 uint32_t frames;
1076 size_t writtenSize;
1077
Eric Laurent421ddc02011-03-07 14:52:59 -08001078 mLock.lock();
1079 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1080 // while we are accessing the cblk
1081 sp <IAudioTrack> audioTrack = mAudioTrack;
1082 sp <IMemory> iMem = mCblkMemory;
1083 audio_track_cblk_t* cblk = mCblk;
1084 mLock.unlock();
1085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 // Manage underrun callback
Eric Laurentae29b762011-03-28 18:37:07 -07001087 if (mActive && (cblk->framesAvailable() == cblk->frameCount)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001088 LOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
Eric Laurentae29b762011-03-28 18:37:07 -07001089 if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 mCbf(EVENT_UNDERRUN, mUserData, 0);
Eric Laurent421ddc02011-03-07 14:52:59 -08001091 if (cblk->server == cblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001092 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 if (mSharedBuffer != 0) return false;
1095 }
1096 }
Eric Laurenta553c252009-07-17 12:17:14 -07001097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 // Manage loop end callback
Eric Laurent421ddc02011-03-07 14:52:59 -08001099 while (mLoopCount > cblk->loopCount) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 int loopCount = -1;
1101 mLoopCount--;
1102 if (mLoopCount >= 0) loopCount = mLoopCount;
1103
1104 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1105 }
1106
1107 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001108 if (!mMarkerReached && (mMarkerPosition > 0)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001109 if (cblk->server >= mMarkerPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001111 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 }
1113 }
1114
1115 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -07001116 if (mUpdatePeriod > 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001117 while (cblk->server >= mNewPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1119 mNewPosition += mUpdatePeriod;
1120 }
1121 }
1122
1123 // If Shared buffer is used, no data is requested from client.
1124 if (mSharedBuffer != 0) {
1125 frames = 0;
1126 } else {
1127 frames = mRemainingFrames;
1128 }
1129
Eric Laurentf1d360a2011-09-07 11:13:23 -07001130 int32_t waitCount = -1;
1131 if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) {
1132 waitCount = 1;
1133 }
1134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 do {
1136
1137 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -07001138
1139 // Calling obtainBuffer() with a wait count of 1
1140 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1141 // stuck here not being able to handle timed events (position, markers, loops).
Eric Laurentf1d360a2011-09-07 11:13:23 -07001142 status_t err = obtainBuffer(&audioBuffer, waitCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 if (err < NO_ERROR) {
1144 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -07001145 LOGE_IF(err != status_t(NO_MORE_BUFFERS), "Error obtaining an audio buffer, giving up.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 return false;
1147 }
1148 break;
1149 }
1150 if (err == status_t(STOPPED)) return false;
1151
1152 // Divide buffer size by 2 to take into account the expansion
1153 // due to 8 to 16 bit conversion: the callback must fill only half
1154 // of the destination buffer
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001155 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 audioBuffer.size >>= 1;
1157 }
1158
1159 size_t reqSize = audioBuffer.size;
1160 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1161 writtenSize = audioBuffer.size;
1162
1163 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001164 if (ssize_t(writtenSize) <= 0) {
1165 // The callback is done filling buffers
1166 // Keep this thread going to handle timed events and
1167 // still try to get more data in intervals of WAIT_PERIOD_MS
1168 // but don't just loop and block the CPU, so wait
1169 usleep(WAIT_PERIOD_MS*1000);
1170 break;
1171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 if (writtenSize > reqSize) writtenSize = reqSize;
1173
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001174 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 // 8 to 16 bit conversion
1176 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1177 int count = writtenSize;
1178 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1179 while(count--) {
1180 *dst-- = (int16_t)(*src--^0x80) << 8;
1181 }
1182 writtenSize <<= 1;
1183 }
1184
1185 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001186 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1187 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1188 // 16 bit.
1189 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 frames -= audioBuffer.frameCount;
1192
1193 releaseBuffer(&audioBuffer);
1194 }
1195 while (frames);
1196
1197 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001198 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 } else {
1200 mRemainingFrames = frames;
1201 }
1202 return true;
1203}
1204
Eric Laurent421ddc02011-03-07 14:52:59 -08001205// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1206// the IAudioTrack and IMemory in case they are recreated here.
1207// If the IAudioTrack is successfully restored, the cblk pointer is updated
1208status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1209{
1210 status_t result;
1211
Eric Laurentae29b762011-03-28 18:37:07 -07001212 if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001213 LOGW("dead IAudioTrack, creating a new one from %s TID %d",
1214 fromStart ? "start()" : "obtainBuffer()", gettid());
Eric Laurent421ddc02011-03-07 14:52:59 -08001215
Eric Laurent421ddc02011-03-07 14:52:59 -08001216 // signal old cblk condition so that other threads waiting for available buffers stop
1217 // waiting now
1218 cblk->cv.broadcast();
1219 cblk->lock.unlock();
1220
Eric Laurent05ce0942011-08-30 10:18:54 -07001221 // refresh the audio configuration cache in this process to make sure we get new
1222 // output parameters in getOutput_l() and createTrack_l()
1223 AudioSystem::clearAudioConfigCache();
1224
Eric Laurent421ddc02011-03-07 14:52:59 -08001225 // if the new IAudioTrack is created, createTrack_l() will modify the
1226 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1227 // It will also delete the strong references on previous IAudioTrack and IMemory
1228 result = createTrack_l(mStreamType,
1229 cblk->sampleRate,
1230 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001231 mChannelMask,
Eric Laurent421ddc02011-03-07 14:52:59 -08001232 mFrameCount,
1233 mFlags,
1234 mSharedBuffer,
1235 getOutput_l(),
1236 false);
1237
1238 if (result == NO_ERROR) {
Eric Laurentb0808f92011-09-06 12:36:15 -07001239 uint32_t user = cblk->user;
1240 uint32_t server = cblk->server;
Eric Laurent6667ac32011-03-21 11:49:00 -07001241 // restore write index and set other indexes to reflect empty buffer status
Eric Laurentb0808f92011-09-06 12:36:15 -07001242 mCblk->user = user;
1243 mCblk->server = user;
1244 mCblk->userBase = user;
1245 mCblk->serverBase = user;
Eric Laurent6667ac32011-03-21 11:49:00 -07001246 // restore loop: this is not guaranteed to succeed if new frame count is not
1247 // compatible with loop length
1248 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
Eric Laurent421ddc02011-03-07 14:52:59 -08001249 if (!fromStart) {
1250 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
Eric Laurentb0808f92011-09-06 12:36:15 -07001251 // Make sure that a client relying on callback events indicating underrun or
1252 // the actual amount of audio frames played (e.g SoundPool) receives them.
1253 if (mSharedBuffer == 0) {
1254 uint32_t frames = 0;
1255 if (user > server) {
1256 frames = ((user - server) > mCblk->frameCount) ?
1257 mCblk->frameCount : (user - server);
1258 memset(mCblk->buffers, 0, frames * mCblk->frameSize);
1259 }
1260 // restart playback even if buffer is not completely filled.
1261 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
1262 // stepUser() clears CBLK_UNDERRUN_ON flag enabling underrun callbacks to
1263 // the client
1264 mCblk->stepUser(frames);
1265 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001266 }
Eric Laurent6667ac32011-03-21 11:49:00 -07001267 if (mActive) {
1268 result = mAudioTrack->start();
Eric Laurent7e8626f2011-09-13 15:04:17 -07001269 LOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result);
Eric Laurent6667ac32011-03-21 11:49:00 -07001270 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001271 if (fromStart && result == NO_ERROR) {
1272 mNewPosition = mCblk->server + mUpdatePeriod;
1273 }
1274 }
1275 if (result != NO_ERROR) {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001276 android_atomic_and(~CBLK_RESTORING_ON, &cblk->flags);
1277 LOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result);
Eric Laurent421ddc02011-03-07 14:52:59 -08001278 }
Eric Laurent7e8626f2011-09-13 15:04:17 -07001279 mRestoreStatus = result;
Eric Laurent421ddc02011-03-07 14:52:59 -08001280 // signal old cblk condition for other threads waiting for restore completion
Eric Laurentae29b762011-03-28 18:37:07 -07001281 android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -08001282 cblk->cv.broadcast();
Eric Laurent421ddc02011-03-07 14:52:59 -08001283 } else {
1284 if (!(cblk->flags & CBLK_RESTORED_MSK)) {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001285 LOGW("dead IAudioTrack, waiting for a new one TID %d", gettid());
Eric Laurent421ddc02011-03-07 14:52:59 -08001286 mLock.unlock();
1287 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
Eric Laurent7e8626f2011-09-13 15:04:17 -07001288 if (result == NO_ERROR) {
1289 result = mRestoreStatus;
1290 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001291 cblk->lock.unlock();
1292 mLock.lock();
1293 } else {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001294 LOGW("dead IAudioTrack, already restored TID %d", gettid());
1295 result = mRestoreStatus;
Eric Laurent421ddc02011-03-07 14:52:59 -08001296 cblk->lock.unlock();
1297 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001298 }
1299 LOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1300 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1301
1302 if (result == NO_ERROR) {
1303 // from now on we switch to the newly created cblk
1304 cblk = mCblk;
1305 }
1306 cblk->lock.lock();
1307
Eric Laurent7e8626f2011-09-13 15:04:17 -07001308 LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d TID %d", result, gettid());
Eric Laurent421ddc02011-03-07 14:52:59 -08001309
1310 return result;
1311}
1312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1314{
1315
1316 const size_t SIZE = 256;
1317 char buffer[SIZE];
1318 String8 result;
1319
1320 result.append(" AudioTrack::dump\n");
1321 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1322 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001323 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001325 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 result.append(buffer);
1327 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1328 result.append(buffer);
1329 ::write(fd, result.string(), result.size());
1330 return NO_ERROR;
1331}
1332
1333// =========================================================================
1334
1335AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1336 : Thread(bCanCallJava), mReceiver(receiver)
1337{
1338}
1339
1340bool AudioTrack::AudioTrackThread::threadLoop()
1341{
1342 return mReceiver.processAudioBuffer(this);
1343}
1344
1345status_t AudioTrack::AudioTrackThread::readyToRun()
1346{
1347 return NO_ERROR;
1348}
1349
1350void AudioTrack::AudioTrackThread::onFirstRef()
1351{
1352}
1353
1354// =========================================================================
1355
Eric Laurentae29b762011-03-28 18:37:07 -07001356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001358 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1359 userBase(0), serverBase(0), buffers(0), frameCount(0),
1360 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurentae29b762011-03-28 18:37:07 -07001361 sendLevel(0), flags(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362{
1363}
1364
1365uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1366{
1367 uint32_t u = this->user;
1368
1369 u += frameCount;
1370 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001371 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1373 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1374 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1375 }
1376 } else if (u > this->server) {
1377 LOGW("stepServer occured after track reset");
1378 u = this->server;
1379 }
1380
1381 if (u >= userBase + this->frameCount) {
1382 userBase += this->frameCount;
1383 }
1384
1385 this->user = u;
1386
1387 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurent913af0b2011-03-17 09:36:51 -07001388 if (flags & CBLK_UNDERRUN_MSK) {
Eric Laurentae29b762011-03-28 18:37:07 -07001389 android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
Eric Laurent913af0b2011-03-17 09:36:51 -07001390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391
1392 return u;
1393}
1394
1395bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1396{
Eric Laurentae29b762011-03-28 18:37:07 -07001397 if (!tryLock()) {
1398 LOGW("stepServer() could not lock cblk");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 return false;
1400 }
1401
1402 uint32_t s = this->server;
1403
1404 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001405 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 // Mark that we have read the first buffer so that next time stepUser() is called
1407 // we switch to normal obtainBuffer() timeout period
1408 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001409 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 // It is possible that we receive a flush()
1412 // while the mixer is processing a block: in this case,
1413 // stepServer() is called After the flush() has reset u & s and
1414 // we have s > u
1415 if (s > this->user) {
1416 LOGW("stepServer occured after track reset");
1417 s = this->user;
1418 }
1419 }
1420
1421 if (s >= loopEnd) {
1422 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1423 s = loopStart;
1424 if (--loopCount == 0) {
1425 loopEnd = UINT_MAX;
1426 loopStart = UINT_MAX;
1427 }
1428 }
1429 if (s >= serverBase + this->frameCount) {
1430 serverBase += this->frameCount;
1431 }
1432
1433 this->server = s;
1434
Eric Laurent421ddc02011-03-07 14:52:59 -08001435 if (!(flags & CBLK_INVALID_MSK)) {
1436 cv.signal();
1437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 lock.unlock();
1439 return true;
1440}
1441
1442void* audio_track_cblk_t::buffer(uint32_t offset) const
1443{
Eric Laurenta553c252009-07-17 12:17:14 -07001444 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445}
1446
1447uint32_t audio_track_cblk_t::framesAvailable()
1448{
1449 Mutex::Autolock _l(lock);
1450 return framesAvailable_l();
1451}
1452
1453uint32_t audio_track_cblk_t::framesAvailable_l()
1454{
1455 uint32_t u = this->user;
1456 uint32_t s = this->server;
1457
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001458 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 uint32_t limit = (s < loopStart) ? s : loopStart;
1460 return limit + frameCount - u;
1461 } else {
1462 return frameCount + u - s;
1463 }
1464}
1465
1466uint32_t audio_track_cblk_t::framesReady()
1467{
1468 uint32_t u = this->user;
1469 uint32_t s = this->server;
1470
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001471 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 if (u < loopEnd) {
1473 return u - s;
1474 } else {
Eric Laurentae29b762011-03-28 18:37:07 -07001475 // do not block on mutex shared with client on AudioFlinger side
1476 if (!tryLock()) {
1477 LOGW("framesReady() could not lock cblk");
1478 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
Eric Laurentae29b762011-03-28 18:37:07 -07001480 uint32_t frames = UINT_MAX;
1481 if (loopCount >= 0) {
1482 frames = (loopEnd - loopStart)*loopCount + u - s;
1483 }
1484 lock.unlock();
1485 return frames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
1487 } else {
1488 return s - u;
1489 }
1490}
1491
Eric Laurentae29b762011-03-28 18:37:07 -07001492bool audio_track_cblk_t::tryLock()
1493{
1494 // the code below simulates lock-with-timeout
1495 // we MUST do this to protect the AudioFlinger server
1496 // as this lock is shared with the client.
1497 status_t err;
1498
1499 err = lock.tryLock();
1500 if (err == -EBUSY) { // just wait a bit
1501 usleep(1000);
1502 err = lock.tryLock();
1503 }
1504 if (err != NO_ERROR) {
1505 // probably, the client just died.
1506 return false;
1507 }
1508 return true;
1509}
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511// -------------------------------------------------------------------------
1512
1513}; // namespace android