blob: 607ca5b49f4aa9e2e90b62469cae70ad492db3b3 [file] [log] [blame]
Glenn Kastene5fb2632011-12-14 10:28:06 -08001/* frameworks/base/media/libmedia/AudioTrack.cpp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002**
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>
Glenn Kastene80a4cc2011-12-15 09:51:17 -080041#include <cutils/compiler.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070042
Dima Zavin34bb4192011-05-11 14:15:23 -070043#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070044#include <system/audio_policy.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046namespace android {
Chia-chi Yehbd240c22010-06-16 06:33:13 +080047// ---------------------------------------------------------------------------
48
49// static
50status_t AudioTrack::getMinFrameCount(
51 int* frameCount,
52 int streamType,
53 uint32_t sampleRate)
54{
55 int afSampleRate;
56 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
57 return NO_INIT;
58 }
59 int afFrameCount;
60 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
61 return NO_INIT;
62 }
63 uint32_t afLatency;
64 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
65 return NO_INIT;
66 }
67
68 // Ensure that buffer depth covers at least audio hardware latency
69 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
70 if (minBufCount < 2) minBufCount = 2;
71
72 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
73 afFrameCount * minBufCount * sampleRate / afSampleRate;
74 return NO_ERROR;
75}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77// ---------------------------------------------------------------------------
78
79AudioTrack::AudioTrack()
Glenn Kasten99d54432011-06-22 16:15:25 -070080 : mStatus(NO_INIT),
81 mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082{
83}
84
85AudioTrack::AudioTrack(
86 int streamType,
87 uint32_t sampleRate,
Glenn Kasten1c5a89d2012-01-04 09:36:37 -080088 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -070089 int channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 int frameCount,
91 uint32_t flags,
92 callback_t cbf,
93 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -070094 int notificationFrames,
95 int sessionId)
Glenn Kasten99d54432011-06-22 16:15:25 -070096 : mStatus(NO_INIT),
97 mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098{
Jean-Michel Trivi54392232011-05-24 15:53:33 -070099 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurent619346f2010-06-21 09:27:30 -0700100 frameCount, flags, cbf, user, notificationFrames,
101 0, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102}
103
104AudioTrack::AudioTrack(
105 int streamType,
106 uint32_t sampleRate,
Glenn Kasten1c5a89d2012-01-04 09:36:37 -0800107 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700108 int channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 const sp<IMemory>& sharedBuffer,
110 uint32_t flags,
111 callback_t cbf,
112 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -0700113 int notificationFrames,
114 int sessionId)
Glenn Kasten99d54432011-06-22 16:15:25 -0700115 : mStatus(NO_INIT),
116 mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117{
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700118 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurent619346f2010-06-21 09:27:30 -0700119 0, flags, cbf, user, notificationFrames,
120 sharedBuffer, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121}
122
123AudioTrack::~AudioTrack()
124{
Steve Block71f2cf12011-10-20 11:56:00 +0100125 ALOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126
127 if (mStatus == NO_ERROR) {
128 // Make sure that callback function exits in the case where
129 // it is looping on buffer full condition in obtainBuffer().
130 // Otherwise the callback thread will never exit.
131 stop();
132 if (mAudioTrackThread != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 mAudioTrackThread->requestExitAndWait();
134 mAudioTrackThread.clear();
135 }
136 mAudioTrack.clear();
137 IPCThreadState::self()->flushCommands();
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700138 AudioSystem::releaseAudioSessionId(mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 }
140}
141
142status_t AudioTrack::set(
143 int streamType,
144 uint32_t sampleRate,
Glenn Kasten1c5a89d2012-01-04 09:36:37 -0800145 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700146 int channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 int frameCount,
148 uint32_t flags,
149 callback_t cbf,
150 void* user,
151 int notificationFrames,
152 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -0700153 bool threadCanCallJava,
154 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155{
156
Steve Block71f2cf12011-10-20 11:56:00 +0100157 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Eric Laurent421ddc02011-03-07 14:52:59 -0800159 AutoMutex lock(mLock);
Eric Laurentef028272009-04-21 07:56:33 -0700160 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 LOGE("Track already in use");
162 return INVALID_OPERATION;
163 }
164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 int afSampleRate;
166 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
167 return NO_INIT;
168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 uint32_t afLatency;
170 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
171 return NO_INIT;
172 }
173
174 // handle default values first.
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700175 if (streamType == AUDIO_STREAM_DEFAULT) {
176 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 }
178 if (sampleRate == 0) {
179 sampleRate = afSampleRate;
180 }
181 // these below should probably come from the audioFlinger too...
Glenn Kasten1c5a89d2012-01-04 09:36:37 -0800182 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700183 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 }
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700185 if (channelMask == 0) {
186 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 }
188
189 // validate parameters
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700190 if (!audio_is_valid_format(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 LOGE("Invalid format");
192 return BAD_VALUE;
193 }
Eric Laurenta553c252009-07-17 12:17:14 -0700194
195 // force direct flag if format is not linear PCM
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700196 if (!audio_is_linear_pcm(format)) {
197 flags |= AUDIO_POLICY_OUTPUT_FLAG_DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -0700198 }
199
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700200 if (!audio_is_output_channel(channelMask)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700201 LOGE("Invalid channel mask");
202 return BAD_VALUE;
203 }
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700204 uint32_t channelCount = popcount(channelMask);
Eric Laurenta553c252009-07-17 12:17:14 -0700205
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700206 audio_io_handle_t output = AudioSystem::getOutput(
207 (audio_stream_type_t)streamType,
Glenn Kasten1c5a89d2012-01-04 09:36:37 -0800208 sampleRate, format, channelMask,
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700209 (audio_policy_output_flags_t)flags);
Eric Laurenta553c252009-07-17 12:17:14 -0700210
211 if (output == 0) {
212 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 return BAD_VALUE;
214 }
215
Eric Laurentbda74692009-11-04 08:27:26 -0800216 mVolume[LEFT] = 1.0f;
217 mVolume[RIGHT] = 1.0f;
Eric Laurent65b65452010-06-01 23:49:17 -0700218 mSendLevel = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700219 mFrameCount = frameCount;
220 mNotificationFramesReq = notificationFrames;
Eric Laurent65b65452010-06-01 23:49:17 -0700221 mSessionId = sessionId;
Eric Laurent7070b362010-07-16 07:43:46 -0700222 mAuxEffectId = 0;
Eric Laurent65b65452010-06-01 23:49:17 -0700223
Eric Laurentbda74692009-11-04 08:27:26 -0800224 // create the IAudioTrack
Eric Laurent421ddc02011-03-07 14:52:59 -0800225 status_t status = createTrack_l(streamType,
226 sampleRate,
Glenn Kasten1c5a89d2012-01-04 09:36:37 -0800227 format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700228 (uint32_t)channelMask,
Eric Laurent421ddc02011-03-07 14:52:59 -0800229 frameCount,
230 flags,
231 sharedBuffer,
232 output,
233 true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
Eric Laurentbda74692009-11-04 08:27:26 -0800235 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 return status;
237 }
Eric Laurentbda74692009-11-04 08:27:26 -0800238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 if (cbf != 0) {
240 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
241 if (mAudioTrackThread == 0) {
242 LOGE("Could not create callback thread");
243 return NO_INIT;
244 }
245 }
246
247 mStatus = NO_ERROR;
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 mStreamType = streamType;
Glenn Kasten1c5a89d2012-01-04 09:36:37 -0800250 mFormat = format;
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700251 mChannelMask = (uint32_t)channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 mChannelCount = channelCount;
253 mSharedBuffer = sharedBuffer;
254 mMuted = false;
255 mActive = 0;
256 mCbf = cbf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 mUserData = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 mLoopCount = 0;
259 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700260 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 mNewPosition = 0;
262 mUpdatePeriod = 0;
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700263 mFlushed = false;
Eric Laurenta553c252009-07-17 12:17:14 -0700264 mFlags = flags;
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700265 AudioSystem::acquireAudioSessionId(mSessionId);
Eric Laurent7e8626f2011-09-13 15:04:17 -0700266 mRestoreStatus = NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 return NO_ERROR;
268}
269
270status_t AudioTrack::initCheck() const
271{
272 return mStatus;
273}
274
275// -------------------------------------------------------------------------
276
277uint32_t AudioTrack::latency() const
278{
279 return mLatency;
280}
281
282int AudioTrack::streamType() const
283{
284 return mStreamType;
285}
286
Glenn Kasten1c5a89d2012-01-04 09:36:37 -0800287audio_format_t AudioTrack::format() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288{
289 return mFormat;
290}
291
292int AudioTrack::channelCount() const
293{
294 return mChannelCount;
295}
296
297uint32_t AudioTrack::frameCount() const
298{
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700299 return mCblk->frameCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300}
301
302int AudioTrack::frameSize() const
303{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700304 if (audio_is_linear_pcm(mFormat)) {
Eric Laurentc310dcb2011-06-16 21:30:45 -0700305 return channelCount()*audio_bytes_per_sample(mFormat);
Eric Laurenta553c252009-07-17 12:17:14 -0700306 } else {
307 return sizeof(uint8_t);
308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309}
310
311sp<IMemory>& AudioTrack::sharedBuffer()
312{
313 return mSharedBuffer;
314}
315
316// -------------------------------------------------------------------------
317
318void AudioTrack::start()
319{
320 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten028ab992011-06-22 16:18:04 -0700321 status_t status = NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322
Steve Block71f2cf12011-10-20 11:56:00 +0100323 ALOGV("start %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 if (t != 0) {
325 if (t->exitPending()) {
326 if (t->requestExitAndWait() == WOULD_BLOCK) {
327 LOGE("AudioTrack::start called from thread");
328 return;
329 }
330 }
331 t->mLock.lock();
332 }
333
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800334 AutoMutex lock(mLock);
Eric Laurent421ddc02011-03-07 14:52:59 -0800335 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
336 // while we are accessing the cblk
337 sp <IAudioTrack> audioTrack = mAudioTrack;
338 sp <IMemory> iMem = mCblkMemory;
339 audio_track_cblk_t* cblk = mCblk;
340
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800341 if (mActive == 0) {
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700342 mFlushed = false;
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800343 mActive = 1;
Eric Laurent421ddc02011-03-07 14:52:59 -0800344 mNewPosition = cblk->server + mUpdatePeriod;
Eric Laurent913af0b2011-03-17 09:36:51 -0700345 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800346 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
347 cblk->waitTimeMs = 0;
Eric Laurentae29b762011-03-28 18:37:07 -0700348 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -0800349 if (t != 0) {
Glenn Kasten99d54432011-06-22 16:15:25 -0700350 t->run("AudioTrackThread", ANDROID_PRIORITY_AUDIO);
Eric Laurent059b4be2009-11-09 23:32:22 -0800351 } else {
Glenn Kasten99d54432011-06-22 16:15:25 -0700352 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
353 mPreviousSchedulingGroup = androidGetThreadSchedulingGroup(0);
354 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
Eric Laurent059b4be2009-11-09 23:32:22 -0800355 }
356
Steve Block71f2cf12011-10-20 11:56:00 +0100357 ALOGV("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) {
Steve Block71f2cf12011-10-20 11:56:00 +0100371 ALOGV("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 {
Glenn Kasten99d54432011-06-22 16:15:25 -0700376 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
377 androidSetThreadSchedulingGroup(0, mPreviousSchedulingGroup);
Eric Laurent059b4be2009-11-09 23:32:22 -0800378 }
Eric Laurentbda74692009-11-04 08:27:26 -0800379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
381
382 if (t != 0) {
383 t->mLock.unlock();
384 }
385}
386
387void AudioTrack::stop()
388{
389 sp<AudioTrackThread> t = mAudioTrackThread;
390
Steve Block71f2cf12011-10-20 11:56:00 +0100391 ALOGV("stop %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 if (t != 0) {
393 t->mLock.lock();
394 }
395
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800396 AutoMutex lock(mLock);
397 if (mActive == 1) {
398 mActive = 0;
Eric Laurentef028272009-04-21 07:56:33 -0700399 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 mAudioTrack->stop();
401 // Cancel loops (If we are in the middle of a loop, playback
402 // would not stop until loopCount reaches 0).
Eric Laurent421ddc02011-03-07 14:52:59 -0800403 setLoop_l(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700404 // the playback head position will reset to 0, so if a marker is set, we need
405 // to activate it again
406 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 // Force flush if a shared buffer is used otherwise audioflinger
408 // will not stop before end of buffer is reached.
409 if (mSharedBuffer != 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800410 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 }
412 if (t != 0) {
413 t->requestExit();
414 } else {
Glenn Kasten99d54432011-06-22 16:15:25 -0700415 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
416 androidSetThreadSchedulingGroup(0, mPreviousSchedulingGroup);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 }
418 }
419
420 if (t != 0) {
421 t->mLock.unlock();
422 }
423}
424
425bool AudioTrack::stopped() const
426{
427 return !mActive;
428}
429
430void AudioTrack::flush()
431{
Eric Laurent421ddc02011-03-07 14:52:59 -0800432 AutoMutex lock(mLock);
433 flush_l();
434}
435
436// must be called with mLock held
437void AudioTrack::flush_l()
438{
Steve Block71f2cf12011-10-20 11:56:00 +0100439 ALOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700440
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700441 // clear playback marker and periodic update counter
442 mMarkerPosition = 0;
443 mMarkerReached = false;
444 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 if (!mActive) {
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700447 mFlushed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 mAudioTrack->flush();
449 // Release AudioTrack callback thread in case it was waiting for new buffers
450 // in AudioTrack::obtainBuffer()
451 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 }
453}
454
455void AudioTrack::pause()
456{
Steve Block71f2cf12011-10-20 11:56:00 +0100457 ALOGV("pause");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800458 AutoMutex lock(mLock);
459 if (mActive == 1) {
460 mActive = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 mAudioTrack->pause();
462 }
463}
464
465void AudioTrack::mute(bool e)
466{
467 mAudioTrack->mute(e);
468 mMuted = e;
469}
470
471bool AudioTrack::muted() const
472{
473 return mMuted;
474}
475
Eric Laurent65b65452010-06-01 23:49:17 -0700476status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477{
Glenn Kasten1c50a782011-11-30 09:46:04 -0800478 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurent65b65452010-06-01 23:49:17 -0700479 return BAD_VALUE;
480 }
481
Eric Laurent421ddc02011-03-07 14:52:59 -0800482 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 mVolume[LEFT] = left;
484 mVolume[RIGHT] = right;
485
486 // write must be atomic
Eric Laurent65b65452010-06-01 23:49:17 -0700487 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
488
489 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490}
491
492void AudioTrack::getVolume(float* left, float* right)
493{
Eric Laurent65b65452010-06-01 23:49:17 -0700494 if (left != NULL) {
495 *left = mVolume[LEFT];
496 }
497 if (right != NULL) {
498 *right = mVolume[RIGHT];
499 }
500}
501
Eric Laurent7070b362010-07-16 07:43:46 -0700502status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurent65b65452010-06-01 23:49:17 -0700503{
Steve Block71f2cf12011-10-20 11:56:00 +0100504 ALOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurent65b65452010-06-01 23:49:17 -0700505 if (level > 1.0f) {
506 return BAD_VALUE;
507 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800508 AutoMutex lock(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -0700509
510 mSendLevel = level;
511
512 mCblk->sendLevel = uint16_t(level * 0x1000);
513
514 return NO_ERROR;
515}
516
Eric Laurent7070b362010-07-16 07:43:46 -0700517void AudioTrack::getAuxEffectSendLevel(float* level)
Eric Laurent65b65452010-06-01 23:49:17 -0700518{
519 if (level != NULL) {
520 *level = mSendLevel;
521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522}
523
Eric Laurent88e209d2009-07-07 07:10:45 -0700524status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525{
526 int afSamplingRate;
527
528 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700529 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 }
531 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700532 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533
Eric Laurent421ddc02011-03-07 14:52:59 -0800534 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700535 mCblk->sampleRate = rate;
536 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537}
538
539uint32_t AudioTrack::getSampleRate()
540{
Eric Laurent421ddc02011-03-07 14:52:59 -0800541 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700542 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543}
544
545status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
546{
Eric Laurent421ddc02011-03-07 14:52:59 -0800547 AutoMutex lock(mLock);
548 return setLoop_l(loopStart, loopEnd, loopCount);
549}
550
551// must be called with mLock held
552status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
553{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 audio_track_cblk_t* cblk = mCblk;
555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 Mutex::Autolock _l(cblk->lock);
557
558 if (loopCount == 0) {
559 cblk->loopStart = UINT_MAX;
560 cblk->loopEnd = UINT_MAX;
561 cblk->loopCount = 0;
562 mLoopCount = 0;
563 return NO_ERROR;
564 }
565
566 if (loopStart >= loopEnd ||
Eric Laurent6667ac32011-03-21 11:49:00 -0700567 loopEnd - loopStart > cblk->frameCount ||
568 cblk->server > loopStart) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700569 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 -0800570 return BAD_VALUE;
571 }
572
Eric Laurent6667ac32011-03-21 11:49:00 -0700573 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700575 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578
579 cblk->loopStart = loopStart;
580 cblk->loopEnd = loopEnd;
581 cblk->loopCount = loopCount;
582 mLoopCount = loopCount;
583
584 return NO_ERROR;
585}
586
587status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
588{
Eric Laurent421ddc02011-03-07 14:52:59 -0800589 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 if (loopStart != 0) {
591 *loopStart = mCblk->loopStart;
592 }
593 if (loopEnd != 0) {
594 *loopEnd = mCblk->loopEnd;
595 }
596 if (loopCount != 0) {
597 if (mCblk->loopCount < 0) {
598 *loopCount = -1;
599 } else {
600 *loopCount = mCblk->loopCount;
601 }
602 }
603
604 return NO_ERROR;
605}
606
607status_t AudioTrack::setMarkerPosition(uint32_t marker)
608{
609 if (mCbf == 0) return INVALID_OPERATION;
610
611 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700612 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613
614 return NO_ERROR;
615}
616
617status_t AudioTrack::getMarkerPosition(uint32_t *marker)
618{
619 if (marker == 0) return BAD_VALUE;
620
621 *marker = mMarkerPosition;
622
623 return NO_ERROR;
624}
625
626status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
627{
628 if (mCbf == 0) return INVALID_OPERATION;
629
630 uint32_t curPosition;
631 getPosition(&curPosition);
632 mNewPosition = curPosition + updatePeriod;
633 mUpdatePeriod = updatePeriod;
634
635 return NO_ERROR;
636}
637
638status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
639{
640 if (updatePeriod == 0) return BAD_VALUE;
641
642 *updatePeriod = mUpdatePeriod;
643
644 return NO_ERROR;
645}
646
647status_t AudioTrack::setPosition(uint32_t position)
648{
Eric Laurent421ddc02011-03-07 14:52:59 -0800649 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 Mutex::Autolock _l(mCblk->lock);
651
652 if (!stopped()) return INVALID_OPERATION;
653
654 if (position > mCblk->user) return BAD_VALUE;
655
656 mCblk->server = position;
Eric Laurentae29b762011-03-28 18:37:07 -0700657 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -0700658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 return NO_ERROR;
660}
661
662status_t AudioTrack::getPosition(uint32_t *position)
663{
664 if (position == 0) return BAD_VALUE;
Eric Laurent421ddc02011-03-07 14:52:59 -0800665 AutoMutex lock(mLock);
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700666 *position = mFlushed ? 0 : mCblk->server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667
668 return NO_ERROR;
669}
670
671status_t AudioTrack::reload()
672{
Eric Laurent421ddc02011-03-07 14:52:59 -0800673 AutoMutex lock(mLock);
674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700676
Eric Laurent421ddc02011-03-07 14:52:59 -0800677 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700679 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680
681 return NO_ERROR;
682}
683
Eric Laurenta553c252009-07-17 12:17:14 -0700684audio_io_handle_t AudioTrack::getOutput()
685{
Eric Laurent421ddc02011-03-07 14:52:59 -0800686 AutoMutex lock(mLock);
687 return getOutput_l();
688}
689
690// must be called with mLock held
691audio_io_handle_t AudioTrack::getOutput_l()
692{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700693 return AudioSystem::getOutput((audio_stream_type_t)mStreamType,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700694 mCblk->sampleRate, mFormat, mChannelMask, (audio_policy_output_flags_t)mFlags);
Eric Laurenta553c252009-07-17 12:17:14 -0700695}
696
Eric Laurent65b65452010-06-01 23:49:17 -0700697int AudioTrack::getSessionId()
698{
699 return mSessionId;
700}
701
702status_t AudioTrack::attachAuxEffect(int effectId)
703{
Steve Block71f2cf12011-10-20 11:56:00 +0100704 ALOGV("attachAuxEffect(%d)", effectId);
Eric Laurent7070b362010-07-16 07:43:46 -0700705 status_t status = mAudioTrack->attachAuxEffect(effectId);
706 if (status == NO_ERROR) {
707 mAuxEffectId = effectId;
708 }
709 return status;
Eric Laurent65b65452010-06-01 23:49:17 -0700710}
711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712// -------------------------------------------------------------------------
713
Eric Laurent421ddc02011-03-07 14:52:59 -0800714// must be called with mLock held
715status_t AudioTrack::createTrack_l(
Eric Laurentbda74692009-11-04 08:27:26 -0800716 int streamType,
717 uint32_t sampleRate,
Glenn Kasten1c5a89d2012-01-04 09:36:37 -0800718 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700719 uint32_t channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800720 int frameCount,
721 uint32_t flags,
722 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700723 audio_io_handle_t output,
724 bool enforceFrameCount)
Eric Laurentbda74692009-11-04 08:27:26 -0800725{
726 status_t status;
727 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
728 if (audioFlinger == 0) {
729 LOGE("Could not get audioflinger");
730 return NO_INIT;
731 }
732
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700733 int afSampleRate;
734 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
735 return NO_INIT;
736 }
737 int afFrameCount;
738 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
739 return NO_INIT;
740 }
741 uint32_t afLatency;
742 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
743 return NO_INIT;
744 }
745
746 mNotificationFramesAct = mNotificationFramesReq;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700747 if (!audio_is_linear_pcm(format)) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700748 if (sharedBuffer != 0) {
749 frameCount = sharedBuffer->size();
750 }
751 } else {
752 // Ensure that buffer depth covers at least audio hardware latency
753 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
754 if (minBufCount < 2) minBufCount = 2;
755
756 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
757
758 if (sharedBuffer == 0) {
759 if (frameCount == 0) {
760 frameCount = minFrameCount;
761 }
762 if (mNotificationFramesAct == 0) {
763 mNotificationFramesAct = frameCount/2;
764 }
765 // Make sure that application is notified with sufficient margin
766 // before underrun
767 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
768 mNotificationFramesAct = frameCount/2;
769 }
770 if (frameCount < minFrameCount) {
771 if (enforceFrameCount) {
772 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
773 return BAD_VALUE;
774 } else {
775 frameCount = minFrameCount;
776 }
777 }
778 } else {
779 // Ensure that buffer alignment matches channelcount
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700780 int channelCount = popcount(channelMask);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700781 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
782 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
783 return BAD_VALUE;
784 }
785 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
786 }
787 }
788
Eric Laurentbda74692009-11-04 08:27:26 -0800789 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
790 streamType,
791 sampleRate,
792 format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700793 channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800794 frameCount,
795 ((uint16_t)flags) << 16,
796 sharedBuffer,
797 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700798 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800799 &status);
800
801 if (track == 0) {
802 LOGE("AudioFlinger could not create track, status: %d", status);
803 return status;
804 }
805 sp<IMemory> cblk = track->getCblk();
806 if (cblk == 0) {
807 LOGE("Could not get control block");
808 return NO_INIT;
809 }
Eric Laurentbda74692009-11-04 08:27:26 -0800810 mAudioTrack = track;
Eric Laurentbda74692009-11-04 08:27:26 -0800811 mCblkMemory = cblk;
812 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurentae29b762011-03-28 18:37:07 -0700813 android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
Eric Laurentbda74692009-11-04 08:27:26 -0800814 if (sharedBuffer == 0) {
815 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
816 } else {
817 mCblk->buffers = sharedBuffer->pointer();
818 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700819 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800820 }
821
Eric Laurent65b65452010-06-01 23:49:17 -0700822 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
823 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent7070b362010-07-16 07:43:46 -0700824 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent49f02be2009-11-19 09:00:56 -0800825 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
826 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700827 mRemainingFrames = mNotificationFramesAct;
828 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800829 return NO_ERROR;
830}
831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
833{
Eric Laurent421ddc02011-03-07 14:52:59 -0800834 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 int active;
Glenn Kasten028ab992011-06-22 16:18:04 -0700836 status_t result = NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 audio_track_cblk_t* cblk = mCblk;
838 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700839 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840
841 audioBuffer->frameCount = 0;
842 audioBuffer->size = 0;
843
844 uint32_t framesAvail = cblk->framesAvailable();
845
Eric Laurent6667ac32011-03-21 11:49:00 -0700846 cblk->lock.lock();
847 if (cblk->flags & CBLK_INVALID_MSK) {
848 goto create_new_track;
849 }
850 cblk->lock.unlock();
851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800853 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 goto start_loop_here;
855 while (framesAvail == 0) {
856 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -0800857 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +0100858 ALOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800859 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 return NO_MORE_BUFFERS;
861 }
Glenn Kastene80a4cc2011-12-15 09:51:17 -0800862 if (CC_UNLIKELY(!waitCount)) {
Eric Laurentbda74692009-11-04 08:27:26 -0800863 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800865 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700866 if (!(cblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800867 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700868 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700869 cblk->lock.unlock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800870 mLock.lock();
871 if (mActive == 0) {
872 return status_t(STOPPED);
873 }
874 cblk->lock.lock();
875 }
876
877 if (cblk->flags & CBLK_INVALID_MSK) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700878 goto create_new_track;
879 }
Glenn Kastene80a4cc2011-12-15 09:51:17 -0800880 if (CC_UNLIKELY(result != NO_ERROR)) {
Eric Laurentef028272009-04-21 07:56:33 -0700881 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
883 // timing out when a loop has been set and we have already written upto loop end
884 // is a normal condition: no need to wake AudioFlinger up.
885 if (cblk->user < cblk->loopEnd) {
886 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
887 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700888 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800890 result = mAudioTrack->start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800892 if (result == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700893 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -0800894create_new_track:
895 result = restoreTrack_l(cblk, false);
896 }
897 if (result != NO_ERROR) {
898 LOGW("obtainBuffer create Track error %d", result);
899 cblk->lock.unlock();
900 return result;
901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
903 cblk->waitTimeMs = 0;
904 }
Eric Laurenta553c252009-07-17 12:17:14 -0700905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800907 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 return TIMED_OUT;
909 }
910 }
911 // read the server count again
912 start_loop_here:
913 framesAvail = cblk->framesAvailable_l();
914 }
Eric Laurentbda74692009-11-04 08:27:26 -0800915 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
917
Eric Laurent4712baa2010-09-30 16:12:31 -0700918 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent421ddc02011-03-07 14:52:59 -0800919 if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
Eric Laurentae29b762011-03-28 18:37:07 -0700920 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
921 LOGW("obtainBuffer() track %p disabled, restarting", this);
922 mAudioTrack->start();
Eric Laurent4712baa2010-09-30 16:12:31 -0700923 }
924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 if (framesReq > framesAvail) {
928 framesReq = framesAvail;
929 }
930
931 uint32_t u = cblk->user;
932 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
933
934 if (u + framesReq > bufferEnd) {
935 framesReq = bufferEnd - u;
936 }
937
Eric Laurenta553c252009-07-17 12:17:14 -0700938 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
939 audioBuffer->channelCount = mChannelCount;
940 audioBuffer->frameCount = framesReq;
941 audioBuffer->size = framesReq * cblk->frameSize;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700942 if (audio_is_linear_pcm(mFormat)) {
943 audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurenta553c252009-07-17 12:17:14 -0700944 } else {
945 audioBuffer->format = mFormat;
946 }
947 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 active = mActive;
949 return active ? status_t(NO_ERROR) : status_t(STOPPED);
950}
951
952void AudioTrack::releaseBuffer(Buffer* audioBuffer)
953{
Eric Laurent421ddc02011-03-07 14:52:59 -0800954 AutoMutex lock(mLock);
955 mCblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956}
957
958// -------------------------------------------------------------------------
959
960ssize_t AudioTrack::write(const void* buffer, size_t userSize)
961{
962
963 if (mSharedBuffer != 0) return INVALID_OPERATION;
964
965 if (ssize_t(userSize) < 0) {
966 // sanity-check. user is most-likely passing an error code.
967 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
968 buffer, userSize, userSize);
969 return BAD_VALUE;
970 }
971
Steve Block71f2cf12011-10-20 11:56:00 +0100972 ALOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973
Eric Laurent421ddc02011-03-07 14:52:59 -0800974 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
975 // while we are accessing the cblk
976 mLock.lock();
977 sp <IAudioTrack> audioTrack = mAudioTrack;
978 sp <IMemory> iMem = mCblkMemory;
979 mLock.unlock();
980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 ssize_t written = 0;
982 const int8_t *src = (const int8_t *)buffer;
983 Buffer audioBuffer;
Eric Laurent913af0b2011-03-17 09:36:51 -0700984 size_t frameSz = (size_t)frameSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985
986 do {
Eric Laurent913af0b2011-03-17 09:36:51 -0700987 audioBuffer.frameCount = userSize/frameSz;
Eric Laurenta553c252009-07-17 12:17:14 -0700988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 // Calling obtainBuffer() with a negative wait count causes
990 // an (almost) infinite wait time.
991 status_t err = obtainBuffer(&audioBuffer, -1);
992 if (err < 0) {
993 // out of buffers, return #bytes written
994 if (err == status_t(NO_MORE_BUFFERS))
995 break;
996 return ssize_t(err);
997 }
998
999 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -07001000
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001001 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 // Divide capacity by 2 to take expansion into account
1003 toWrite = audioBuffer.size>>1;
1004 // 8 to 16 bit conversion
1005 int count = toWrite;
1006 int16_t *dst = (int16_t *)(audioBuffer.i8);
1007 while(count--) {
1008 *dst++ = (int16_t)(*src++^0x80) << 8;
1009 }
Eric Laurent28ad42b2009-08-04 10:42:26 -07001010 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 toWrite = audioBuffer.size;
1012 memcpy(audioBuffer.i8, src, toWrite);
1013 src += toWrite;
1014 }
1015 userSize -= toWrite;
1016 written += toWrite;
1017
1018 releaseBuffer(&audioBuffer);
Eric Laurent913af0b2011-03-17 09:36:51 -07001019 } while (userSize >= frameSz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020
1021 return written;
1022}
1023
1024// -------------------------------------------------------------------------
1025
1026bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1027{
1028 Buffer audioBuffer;
1029 uint32_t frames;
1030 size_t writtenSize;
1031
Eric Laurent421ddc02011-03-07 14:52:59 -08001032 mLock.lock();
1033 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1034 // while we are accessing the cblk
1035 sp <IAudioTrack> audioTrack = mAudioTrack;
1036 sp <IMemory> iMem = mCblkMemory;
1037 audio_track_cblk_t* cblk = mCblk;
1038 mLock.unlock();
1039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 // Manage underrun callback
Eric Laurentae29b762011-03-28 18:37:07 -07001041 if (mActive && (cblk->framesAvailable() == cblk->frameCount)) {
Steve Block71f2cf12011-10-20 11:56:00 +01001042 ALOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
Eric Laurentae29b762011-03-28 18:37:07 -07001043 if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 mCbf(EVENT_UNDERRUN, mUserData, 0);
Eric Laurent421ddc02011-03-07 14:52:59 -08001045 if (cblk->server == cblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001046 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 if (mSharedBuffer != 0) return false;
1049 }
1050 }
Eric Laurenta553c252009-07-17 12:17:14 -07001051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 // Manage loop end callback
Eric Laurent421ddc02011-03-07 14:52:59 -08001053 while (mLoopCount > cblk->loopCount) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 int loopCount = -1;
1055 mLoopCount--;
1056 if (mLoopCount >= 0) loopCount = mLoopCount;
1057
1058 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1059 }
1060
1061 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001062 if (!mMarkerReached && (mMarkerPosition > 0)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001063 if (cblk->server >= mMarkerPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001065 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
1067 }
1068
1069 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -07001070 if (mUpdatePeriod > 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001071 while (cblk->server >= mNewPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1073 mNewPosition += mUpdatePeriod;
1074 }
1075 }
1076
1077 // If Shared buffer is used, no data is requested from client.
1078 if (mSharedBuffer != 0) {
1079 frames = 0;
1080 } else {
1081 frames = mRemainingFrames;
1082 }
1083
Eric Laurentf1d360a2011-09-07 11:13:23 -07001084 int32_t waitCount = -1;
1085 if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) {
1086 waitCount = 1;
1087 }
1088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 do {
1090
1091 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -07001092
1093 // Calling obtainBuffer() with a wait count of 1
1094 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1095 // stuck here not being able to handle timed events (position, markers, loops).
Eric Laurentf1d360a2011-09-07 11:13:23 -07001096 status_t err = obtainBuffer(&audioBuffer, waitCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 if (err < NO_ERROR) {
1098 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -07001099 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 -08001100 return false;
1101 }
1102 break;
1103 }
1104 if (err == status_t(STOPPED)) return false;
1105
1106 // Divide buffer size by 2 to take into account the expansion
1107 // due to 8 to 16 bit conversion: the callback must fill only half
1108 // of the destination buffer
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001109 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 audioBuffer.size >>= 1;
1111 }
1112
1113 size_t reqSize = audioBuffer.size;
1114 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1115 writtenSize = audioBuffer.size;
1116
1117 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001118 if (ssize_t(writtenSize) <= 0) {
1119 // The callback is done filling buffers
1120 // Keep this thread going to handle timed events and
1121 // still try to get more data in intervals of WAIT_PERIOD_MS
1122 // but don't just loop and block the CPU, so wait
1123 usleep(WAIT_PERIOD_MS*1000);
1124 break;
1125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 if (writtenSize > reqSize) writtenSize = reqSize;
1127
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001128 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 // 8 to 16 bit conversion
1130 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1131 int count = writtenSize;
1132 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1133 while(count--) {
1134 *dst-- = (int16_t)(*src--^0x80) << 8;
1135 }
1136 writtenSize <<= 1;
1137 }
1138
1139 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001140 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1141 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1142 // 16 bit.
1143 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 frames -= audioBuffer.frameCount;
1146
1147 releaseBuffer(&audioBuffer);
1148 }
1149 while (frames);
1150
1151 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001152 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 } else {
1154 mRemainingFrames = frames;
1155 }
1156 return true;
1157}
1158
Eric Laurent421ddc02011-03-07 14:52:59 -08001159// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1160// the IAudioTrack and IMemory in case they are recreated here.
1161// If the IAudioTrack is successfully restored, the cblk pointer is updated
1162status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1163{
1164 status_t result;
1165
Eric Laurentae29b762011-03-28 18:37:07 -07001166 if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001167 LOGW("dead IAudioTrack, creating a new one from %s TID %d",
1168 fromStart ? "start()" : "obtainBuffer()", gettid());
Eric Laurent421ddc02011-03-07 14:52:59 -08001169
Eric Laurent421ddc02011-03-07 14:52:59 -08001170 // signal old cblk condition so that other threads waiting for available buffers stop
1171 // waiting now
1172 cblk->cv.broadcast();
1173 cblk->lock.unlock();
1174
Eric Laurent05ce0942011-08-30 10:18:54 -07001175 // refresh the audio configuration cache in this process to make sure we get new
1176 // output parameters in getOutput_l() and createTrack_l()
1177 AudioSystem::clearAudioConfigCache();
1178
Eric Laurent421ddc02011-03-07 14:52:59 -08001179 // if the new IAudioTrack is created, createTrack_l() will modify the
1180 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1181 // It will also delete the strong references on previous IAudioTrack and IMemory
1182 result = createTrack_l(mStreamType,
1183 cblk->sampleRate,
1184 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001185 mChannelMask,
Eric Laurent421ddc02011-03-07 14:52:59 -08001186 mFrameCount,
1187 mFlags,
1188 mSharedBuffer,
1189 getOutput_l(),
1190 false);
1191
1192 if (result == NO_ERROR) {
Eric Laurentb0808f92011-09-06 12:36:15 -07001193 uint32_t user = cblk->user;
1194 uint32_t server = cblk->server;
Eric Laurent6667ac32011-03-21 11:49:00 -07001195 // restore write index and set other indexes to reflect empty buffer status
Eric Laurentb0808f92011-09-06 12:36:15 -07001196 mCblk->user = user;
1197 mCblk->server = user;
1198 mCblk->userBase = user;
1199 mCblk->serverBase = user;
Eric Laurent6667ac32011-03-21 11:49:00 -07001200 // restore loop: this is not guaranteed to succeed if new frame count is not
1201 // compatible with loop length
1202 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
Eric Laurent421ddc02011-03-07 14:52:59 -08001203 if (!fromStart) {
1204 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
Eric Laurentb0808f92011-09-06 12:36:15 -07001205 // Make sure that a client relying on callback events indicating underrun or
1206 // the actual amount of audio frames played (e.g SoundPool) receives them.
1207 if (mSharedBuffer == 0) {
1208 uint32_t frames = 0;
1209 if (user > server) {
1210 frames = ((user - server) > mCblk->frameCount) ?
1211 mCblk->frameCount : (user - server);
1212 memset(mCblk->buffers, 0, frames * mCblk->frameSize);
1213 }
1214 // restart playback even if buffer is not completely filled.
1215 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
1216 // stepUser() clears CBLK_UNDERRUN_ON flag enabling underrun callbacks to
1217 // the client
1218 mCblk->stepUser(frames);
1219 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001220 }
Eric Laurent6667ac32011-03-21 11:49:00 -07001221 if (mActive) {
1222 result = mAudioTrack->start();
Eric Laurent7e8626f2011-09-13 15:04:17 -07001223 LOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result);
Eric Laurent6667ac32011-03-21 11:49:00 -07001224 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001225 if (fromStart && result == NO_ERROR) {
1226 mNewPosition = mCblk->server + mUpdatePeriod;
1227 }
1228 }
1229 if (result != NO_ERROR) {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001230 android_atomic_and(~CBLK_RESTORING_ON, &cblk->flags);
1231 LOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result);
Eric Laurent421ddc02011-03-07 14:52:59 -08001232 }
Eric Laurent7e8626f2011-09-13 15:04:17 -07001233 mRestoreStatus = result;
Eric Laurent421ddc02011-03-07 14:52:59 -08001234 // signal old cblk condition for other threads waiting for restore completion
Eric Laurentae29b762011-03-28 18:37:07 -07001235 android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -08001236 cblk->cv.broadcast();
Eric Laurent421ddc02011-03-07 14:52:59 -08001237 } else {
1238 if (!(cblk->flags & CBLK_RESTORED_MSK)) {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001239 LOGW("dead IAudioTrack, waiting for a new one TID %d", gettid());
Eric Laurent421ddc02011-03-07 14:52:59 -08001240 mLock.unlock();
1241 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
Eric Laurent7e8626f2011-09-13 15:04:17 -07001242 if (result == NO_ERROR) {
1243 result = mRestoreStatus;
1244 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001245 cblk->lock.unlock();
1246 mLock.lock();
1247 } else {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001248 LOGW("dead IAudioTrack, already restored TID %d", gettid());
1249 result = mRestoreStatus;
Eric Laurent421ddc02011-03-07 14:52:59 -08001250 cblk->lock.unlock();
1251 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001252 }
Steve Block71f2cf12011-10-20 11:56:00 +01001253 ALOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
Eric Laurent421ddc02011-03-07 14:52:59 -08001254 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1255
1256 if (result == NO_ERROR) {
1257 // from now on we switch to the newly created cblk
1258 cblk = mCblk;
1259 }
1260 cblk->lock.lock();
1261
Eric Laurent7e8626f2011-09-13 15:04:17 -07001262 LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d TID %d", result, gettid());
Eric Laurent421ddc02011-03-07 14:52:59 -08001263
1264 return result;
1265}
1266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1268{
1269
1270 const size_t SIZE = 256;
1271 char buffer[SIZE];
1272 String8 result;
1273
1274 result.append(" AudioTrack::dump\n");
1275 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1276 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001277 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 -08001278 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001279 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 -08001280 result.append(buffer);
1281 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1282 result.append(buffer);
1283 ::write(fd, result.string(), result.size());
1284 return NO_ERROR;
1285}
1286
1287// =========================================================================
1288
1289AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1290 : Thread(bCanCallJava), mReceiver(receiver)
1291{
1292}
1293
1294bool AudioTrack::AudioTrackThread::threadLoop()
1295{
1296 return mReceiver.processAudioBuffer(this);
1297}
1298
1299status_t AudioTrack::AudioTrackThread::readyToRun()
1300{
1301 return NO_ERROR;
1302}
1303
1304void AudioTrack::AudioTrackThread::onFirstRef()
1305{
1306}
1307
1308// =========================================================================
1309
Eric Laurentae29b762011-03-28 18:37:07 -07001310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001312 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1313 userBase(0), serverBase(0), buffers(0), frameCount(0),
1314 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurentae29b762011-03-28 18:37:07 -07001315 sendLevel(0), flags(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316{
1317}
1318
1319uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1320{
Glenn Kastendb298a42011-12-13 11:45:07 -08001321 uint32_t u = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322
1323 u += frameCount;
1324 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001325 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1327 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1328 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1329 }
Glenn Kastendb298a42011-12-13 11:45:07 -08001330 } else if (u > server) {
1331 LOGW("stepServer occurred after track reset");
1332 u = server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
1334
1335 if (u >= userBase + this->frameCount) {
1336 userBase += this->frameCount;
1337 }
1338
Glenn Kastendb298a42011-12-13 11:45:07 -08001339 user = u;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340
1341 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurent913af0b2011-03-17 09:36:51 -07001342 if (flags & CBLK_UNDERRUN_MSK) {
Eric Laurentae29b762011-03-28 18:37:07 -07001343 android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
Eric Laurent913af0b2011-03-17 09:36:51 -07001344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345
1346 return u;
1347}
1348
1349bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1350{
Eric Laurentae29b762011-03-28 18:37:07 -07001351 if (!tryLock()) {
1352 LOGW("stepServer() could not lock cblk");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 return false;
1354 }
1355
Glenn Kastendb298a42011-12-13 11:45:07 -08001356 uint32_t s = server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357
1358 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001359 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 // Mark that we have read the first buffer so that next time stepUser() is called
1361 // we switch to normal obtainBuffer() timeout period
1362 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001363 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 // It is possible that we receive a flush()
1366 // while the mixer is processing a block: in this case,
1367 // stepServer() is called After the flush() has reset u & s and
1368 // we have s > u
Glenn Kastendb298a42011-12-13 11:45:07 -08001369 if (s > user) {
1370 LOGW("stepServer occurred after track reset");
1371 s = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373 }
1374
1375 if (s >= loopEnd) {
1376 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1377 s = loopStart;
1378 if (--loopCount == 0) {
1379 loopEnd = UINT_MAX;
1380 loopStart = UINT_MAX;
1381 }
1382 }
1383 if (s >= serverBase + this->frameCount) {
1384 serverBase += this->frameCount;
1385 }
1386
Glenn Kastendb298a42011-12-13 11:45:07 -08001387 server = s;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388
Eric Laurent421ddc02011-03-07 14:52:59 -08001389 if (!(flags & CBLK_INVALID_MSK)) {
1390 cv.signal();
1391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 lock.unlock();
1393 return true;
1394}
1395
1396void* audio_track_cblk_t::buffer(uint32_t offset) const
1397{
Glenn Kastendb298a42011-12-13 11:45:07 -08001398 return (int8_t *)buffers + (offset - userBase) * frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399}
1400
1401uint32_t audio_track_cblk_t::framesAvailable()
1402{
1403 Mutex::Autolock _l(lock);
1404 return framesAvailable_l();
1405}
1406
1407uint32_t audio_track_cblk_t::framesAvailable_l()
1408{
Glenn Kastendb298a42011-12-13 11:45:07 -08001409 uint32_t u = user;
1410 uint32_t s = server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001412 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 uint32_t limit = (s < loopStart) ? s : loopStart;
1414 return limit + frameCount - u;
1415 } else {
1416 return frameCount + u - s;
1417 }
1418}
1419
1420uint32_t audio_track_cblk_t::framesReady()
1421{
Glenn Kastendb298a42011-12-13 11:45:07 -08001422 uint32_t u = user;
1423 uint32_t s = server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001425 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 if (u < loopEnd) {
1427 return u - s;
1428 } else {
Eric Laurentae29b762011-03-28 18:37:07 -07001429 // do not block on mutex shared with client on AudioFlinger side
1430 if (!tryLock()) {
1431 LOGW("framesReady() could not lock cblk");
1432 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
Eric Laurentae29b762011-03-28 18:37:07 -07001434 uint32_t frames = UINT_MAX;
1435 if (loopCount >= 0) {
1436 frames = (loopEnd - loopStart)*loopCount + u - s;
1437 }
1438 lock.unlock();
1439 return frames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441 } else {
1442 return s - u;
1443 }
1444}
1445
Eric Laurentae29b762011-03-28 18:37:07 -07001446bool audio_track_cblk_t::tryLock()
1447{
1448 // the code below simulates lock-with-timeout
1449 // we MUST do this to protect the AudioFlinger server
1450 // as this lock is shared with the client.
1451 status_t err;
1452
1453 err = lock.tryLock();
1454 if (err == -EBUSY) { // just wait a bit
1455 usleep(1000);
1456 err = lock.tryLock();
1457 }
1458 if (err != NO_ERROR) {
1459 // probably, the client just died.
1460 return false;
1461 }
1462 return true;
1463}
1464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465// -------------------------------------------------------------------------
1466
1467}; // namespace android