blob: 97fb955bc2becfb8bdf75c9d1c8d9db787859b37 [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,
88 int 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,
107 int 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,
145 int 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...
182 if (format == 0) {
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,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700208 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,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700227 (uint32_t)format,
228 (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;
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700250 mFormat = (uint32_t)format;
251 mChannelMask = (uint32_t)channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 mChannelCount = channelCount;
253 mSharedBuffer = sharedBuffer;
254 mMuted = false;
Glenn Kastene6810ff2012-01-03 09:42:47 -0800255 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287int AudioTrack::format() const
288{
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
Glenn Kastene6810ff2012-01-03 09:42:47 -0800341 if (!mActive) {
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700342 mFlushed = false;
Glenn Kastene6810ff2012-01-03 09:42:47 -0800343 mActive = true;
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");
Glenn Kastene6810ff2012-01-03 09:42:47 -0800372 mActive = false;
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);
Glenn Kastene6810ff2012-01-03 09:42:47 -0800397 if (mActive) {
398 mActive = false;
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{
Glenn Kastene6810ff2012-01-03 09:42:47 -0800427 AutoMutex lock(mLock);
428 return stopped_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429}
430
431void AudioTrack::flush()
432{
Eric Laurent421ddc02011-03-07 14:52:59 -0800433 AutoMutex lock(mLock);
434 flush_l();
435}
436
437// must be called with mLock held
438void AudioTrack::flush_l()
439{
Steve Block71f2cf12011-10-20 11:56:00 +0100440 ALOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700441
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700442 // clear playback marker and periodic update counter
443 mMarkerPosition = 0;
444 mMarkerReached = false;
445 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 if (!mActive) {
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700448 mFlushed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 mAudioTrack->flush();
450 // Release AudioTrack callback thread in case it was waiting for new buffers
451 // in AudioTrack::obtainBuffer()
452 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 }
454}
455
456void AudioTrack::pause()
457{
Steve Block71f2cf12011-10-20 11:56:00 +0100458 ALOGV("pause");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800459 AutoMutex lock(mLock);
Glenn Kastene6810ff2012-01-03 09:42:47 -0800460 if (mActive) {
461 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 mAudioTrack->pause();
463 }
464}
465
466void AudioTrack::mute(bool e)
467{
468 mAudioTrack->mute(e);
469 mMuted = e;
470}
471
472bool AudioTrack::muted() const
473{
474 return mMuted;
475}
476
Eric Laurent65b65452010-06-01 23:49:17 -0700477status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478{
Glenn Kasten1c50a782011-11-30 09:46:04 -0800479 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurent65b65452010-06-01 23:49:17 -0700480 return BAD_VALUE;
481 }
482
Eric Laurent421ddc02011-03-07 14:52:59 -0800483 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 mVolume[LEFT] = left;
485 mVolume[RIGHT] = right;
486
487 // write must be atomic
Eric Laurent65b65452010-06-01 23:49:17 -0700488 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
489
490 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491}
492
493void AudioTrack::getVolume(float* left, float* right)
494{
Eric Laurent65b65452010-06-01 23:49:17 -0700495 if (left != NULL) {
496 *left = mVolume[LEFT];
497 }
498 if (right != NULL) {
499 *right = mVolume[RIGHT];
500 }
501}
502
Eric Laurent7070b362010-07-16 07:43:46 -0700503status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurent65b65452010-06-01 23:49:17 -0700504{
Steve Block71f2cf12011-10-20 11:56:00 +0100505 ALOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurent65b65452010-06-01 23:49:17 -0700506 if (level > 1.0f) {
507 return BAD_VALUE;
508 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800509 AutoMutex lock(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -0700510
511 mSendLevel = level;
512
513 mCblk->sendLevel = uint16_t(level * 0x1000);
514
515 return NO_ERROR;
516}
517
Eric Laurent7070b362010-07-16 07:43:46 -0700518void AudioTrack::getAuxEffectSendLevel(float* level)
Eric Laurent65b65452010-06-01 23:49:17 -0700519{
520 if (level != NULL) {
521 *level = mSendLevel;
522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523}
524
Eric Laurent88e209d2009-07-07 07:10:45 -0700525status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526{
527 int afSamplingRate;
528
529 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700530 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 }
532 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700533 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534
Eric Laurent421ddc02011-03-07 14:52:59 -0800535 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700536 mCblk->sampleRate = rate;
537 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538}
539
540uint32_t AudioTrack::getSampleRate()
541{
Eric Laurent421ddc02011-03-07 14:52:59 -0800542 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700543 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544}
545
546status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
547{
Eric Laurent421ddc02011-03-07 14:52:59 -0800548 AutoMutex lock(mLock);
549 return setLoop_l(loopStart, loopEnd, loopCount);
550}
551
552// must be called with mLock held
553status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
554{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 audio_track_cblk_t* cblk = mCblk;
556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 Mutex::Autolock _l(cblk->lock);
558
559 if (loopCount == 0) {
560 cblk->loopStart = UINT_MAX;
561 cblk->loopEnd = UINT_MAX;
562 cblk->loopCount = 0;
563 mLoopCount = 0;
564 return NO_ERROR;
565 }
566
567 if (loopStart >= loopEnd ||
Eric Laurent6667ac32011-03-21 11:49:00 -0700568 loopEnd - loopStart > cblk->frameCount ||
569 cblk->server > loopStart) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700570 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 -0800571 return BAD_VALUE;
572 }
573
Eric Laurent6667ac32011-03-21 11:49:00 -0700574 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700576 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579
580 cblk->loopStart = loopStart;
581 cblk->loopEnd = loopEnd;
582 cblk->loopCount = loopCount;
583 mLoopCount = loopCount;
584
585 return NO_ERROR;
586}
587
588status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
589{
Eric Laurent421ddc02011-03-07 14:52:59 -0800590 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 if (loopStart != 0) {
592 *loopStart = mCblk->loopStart;
593 }
594 if (loopEnd != 0) {
595 *loopEnd = mCblk->loopEnd;
596 }
597 if (loopCount != 0) {
598 if (mCblk->loopCount < 0) {
599 *loopCount = -1;
600 } else {
601 *loopCount = mCblk->loopCount;
602 }
603 }
604
605 return NO_ERROR;
606}
607
608status_t AudioTrack::setMarkerPosition(uint32_t marker)
609{
610 if (mCbf == 0) return INVALID_OPERATION;
611
612 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700613 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614
615 return NO_ERROR;
616}
617
618status_t AudioTrack::getMarkerPosition(uint32_t *marker)
619{
620 if (marker == 0) return BAD_VALUE;
621
622 *marker = mMarkerPosition;
623
624 return NO_ERROR;
625}
626
627status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
628{
629 if (mCbf == 0) return INVALID_OPERATION;
630
631 uint32_t curPosition;
632 getPosition(&curPosition);
633 mNewPosition = curPosition + updatePeriod;
634 mUpdatePeriod = updatePeriod;
635
636 return NO_ERROR;
637}
638
639status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
640{
641 if (updatePeriod == 0) return BAD_VALUE;
642
643 *updatePeriod = mUpdatePeriod;
644
645 return NO_ERROR;
646}
647
648status_t AudioTrack::setPosition(uint32_t position)
649{
Eric Laurent421ddc02011-03-07 14:52:59 -0800650 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651
Glenn Kastene6810ff2012-01-03 09:42:47 -0800652 if (!stopped_l()) return INVALID_OPERATION;
653
654 Mutex::Autolock _l(mCblk->lock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655
656 if (position > mCblk->user) return BAD_VALUE;
657
658 mCblk->server = position;
Eric Laurentae29b762011-03-28 18:37:07 -0700659 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -0700660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 return NO_ERROR;
662}
663
664status_t AudioTrack::getPosition(uint32_t *position)
665{
666 if (position == 0) return BAD_VALUE;
Eric Laurent421ddc02011-03-07 14:52:59 -0800667 AutoMutex lock(mLock);
Jean-Michel Trivi22cb2042011-08-25 16:47:23 -0700668 *position = mFlushed ? 0 : mCblk->server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669
670 return NO_ERROR;
671}
672
673status_t AudioTrack::reload()
674{
Eric Laurent421ddc02011-03-07 14:52:59 -0800675 AutoMutex lock(mLock);
676
Glenn Kastene6810ff2012-01-03 09:42:47 -0800677 if (!stopped_l()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700678
Eric Laurent421ddc02011-03-07 14:52:59 -0800679 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700681 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682
683 return NO_ERROR;
684}
685
Eric Laurenta553c252009-07-17 12:17:14 -0700686audio_io_handle_t AudioTrack::getOutput()
687{
Eric Laurent421ddc02011-03-07 14:52:59 -0800688 AutoMutex lock(mLock);
689 return getOutput_l();
690}
691
692// must be called with mLock held
693audio_io_handle_t AudioTrack::getOutput_l()
694{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700695 return AudioSystem::getOutput((audio_stream_type_t)mStreamType,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700696 mCblk->sampleRate, mFormat, mChannelMask, (audio_policy_output_flags_t)mFlags);
Eric Laurenta553c252009-07-17 12:17:14 -0700697}
698
Eric Laurent65b65452010-06-01 23:49:17 -0700699int AudioTrack::getSessionId()
700{
701 return mSessionId;
702}
703
704status_t AudioTrack::attachAuxEffect(int effectId)
705{
Steve Block71f2cf12011-10-20 11:56:00 +0100706 ALOGV("attachAuxEffect(%d)", effectId);
Eric Laurent7070b362010-07-16 07:43:46 -0700707 status_t status = mAudioTrack->attachAuxEffect(effectId);
708 if (status == NO_ERROR) {
709 mAuxEffectId = effectId;
710 }
711 return status;
Eric Laurent65b65452010-06-01 23:49:17 -0700712}
713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714// -------------------------------------------------------------------------
715
Eric Laurent421ddc02011-03-07 14:52:59 -0800716// must be called with mLock held
717status_t AudioTrack::createTrack_l(
Eric Laurentbda74692009-11-04 08:27:26 -0800718 int streamType,
719 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700720 uint32_t format,
721 uint32_t channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800722 int frameCount,
723 uint32_t flags,
724 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700725 audio_io_handle_t output,
726 bool enforceFrameCount)
Eric Laurentbda74692009-11-04 08:27:26 -0800727{
728 status_t status;
729 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
730 if (audioFlinger == 0) {
731 LOGE("Could not get audioflinger");
732 return NO_INIT;
733 }
734
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700735 int afSampleRate;
736 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
737 return NO_INIT;
738 }
739 int afFrameCount;
740 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
741 return NO_INIT;
742 }
743 uint32_t afLatency;
744 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
745 return NO_INIT;
746 }
747
748 mNotificationFramesAct = mNotificationFramesReq;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700749 if (!audio_is_linear_pcm(format)) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700750 if (sharedBuffer != 0) {
751 frameCount = sharedBuffer->size();
752 }
753 } else {
754 // Ensure that buffer depth covers at least audio hardware latency
755 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
756 if (minBufCount < 2) minBufCount = 2;
757
758 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
759
760 if (sharedBuffer == 0) {
761 if (frameCount == 0) {
762 frameCount = minFrameCount;
763 }
764 if (mNotificationFramesAct == 0) {
765 mNotificationFramesAct = frameCount/2;
766 }
767 // Make sure that application is notified with sufficient margin
768 // before underrun
769 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
770 mNotificationFramesAct = frameCount/2;
771 }
772 if (frameCount < minFrameCount) {
773 if (enforceFrameCount) {
774 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
775 return BAD_VALUE;
776 } else {
777 frameCount = minFrameCount;
778 }
779 }
780 } else {
781 // Ensure that buffer alignment matches channelcount
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700782 int channelCount = popcount(channelMask);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700783 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
784 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
785 return BAD_VALUE;
786 }
787 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
788 }
789 }
790
Eric Laurentbda74692009-11-04 08:27:26 -0800791 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
792 streamType,
793 sampleRate,
794 format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700795 channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800796 frameCount,
797 ((uint16_t)flags) << 16,
798 sharedBuffer,
799 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700800 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800801 &status);
802
803 if (track == 0) {
804 LOGE("AudioFlinger could not create track, status: %d", status);
805 return status;
806 }
807 sp<IMemory> cblk = track->getCblk();
808 if (cblk == 0) {
809 LOGE("Could not get control block");
810 return NO_INIT;
811 }
Eric Laurentbda74692009-11-04 08:27:26 -0800812 mAudioTrack = track;
Eric Laurentbda74692009-11-04 08:27:26 -0800813 mCblkMemory = cblk;
814 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurentae29b762011-03-28 18:37:07 -0700815 android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
Eric Laurentbda74692009-11-04 08:27:26 -0800816 if (sharedBuffer == 0) {
817 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
818 } else {
819 mCblk->buffers = sharedBuffer->pointer();
820 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700821 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800822 }
823
Eric Laurent65b65452010-06-01 23:49:17 -0700824 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
825 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent7070b362010-07-16 07:43:46 -0700826 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent49f02be2009-11-19 09:00:56 -0800827 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
828 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700829 mRemainingFrames = mNotificationFramesAct;
830 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800831 return NO_ERROR;
832}
833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
835{
Eric Laurent421ddc02011-03-07 14:52:59 -0800836 AutoMutex lock(mLock);
Glenn Kastene6810ff2012-01-03 09:42:47 -0800837 bool active;
Glenn Kasten028ab992011-06-22 16:18:04 -0700838 status_t result = NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 audio_track_cblk_t* cblk = mCblk;
840 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700841 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842
843 audioBuffer->frameCount = 0;
844 audioBuffer->size = 0;
845
846 uint32_t framesAvail = cblk->framesAvailable();
847
Eric Laurent6667ac32011-03-21 11:49:00 -0700848 cblk->lock.lock();
849 if (cblk->flags & CBLK_INVALID_MSK) {
850 goto create_new_track;
851 }
852 cblk->lock.unlock();
853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800855 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 goto start_loop_here;
857 while (framesAvail == 0) {
858 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -0800859 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +0100860 ALOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800861 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 return NO_MORE_BUFFERS;
863 }
Glenn Kastene80a4cc2011-12-15 09:51:17 -0800864 if (CC_UNLIKELY(!waitCount)) {
Eric Laurentbda74692009-11-04 08:27:26 -0800865 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800867 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700868 if (!(cblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800869 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700870 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700871 cblk->lock.unlock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800872 mLock.lock();
Glenn Kastene6810ff2012-01-03 09:42:47 -0800873 if (!mActive) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800874 return status_t(STOPPED);
875 }
876 cblk->lock.lock();
877 }
878
879 if (cblk->flags & CBLK_INVALID_MSK) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700880 goto create_new_track;
881 }
Glenn Kastene80a4cc2011-12-15 09:51:17 -0800882 if (CC_UNLIKELY(result != NO_ERROR)) {
Eric Laurentef028272009-04-21 07:56:33 -0700883 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
885 // timing out when a loop has been set and we have already written upto loop end
886 // is a normal condition: no need to wake AudioFlinger up.
887 if (cblk->user < cblk->loopEnd) {
888 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
889 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700890 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800892 result = mAudioTrack->start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800894 if (result == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700895 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -0800896create_new_track:
897 result = restoreTrack_l(cblk, false);
898 }
899 if (result != NO_ERROR) {
900 LOGW("obtainBuffer create Track error %d", result);
901 cblk->lock.unlock();
902 return result;
903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 }
905 cblk->waitTimeMs = 0;
906 }
Eric Laurenta553c252009-07-17 12:17:14 -0700907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800909 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 return TIMED_OUT;
911 }
912 }
913 // read the server count again
914 start_loop_here:
915 framesAvail = cblk->framesAvailable_l();
916 }
Eric Laurentbda74692009-11-04 08:27:26 -0800917 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
919
Eric Laurent4712baa2010-09-30 16:12:31 -0700920 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent421ddc02011-03-07 14:52:59 -0800921 if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
Eric Laurentae29b762011-03-28 18:37:07 -0700922 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
923 LOGW("obtainBuffer() track %p disabled, restarting", this);
924 mAudioTrack->start();
Eric Laurent4712baa2010-09-30 16:12:31 -0700925 }
926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 if (framesReq > framesAvail) {
930 framesReq = framesAvail;
931 }
932
933 uint32_t u = cblk->user;
934 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
935
936 if (u + framesReq > bufferEnd) {
937 framesReq = bufferEnd - u;
938 }
939
Eric Laurenta553c252009-07-17 12:17:14 -0700940 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
941 audioBuffer->channelCount = mChannelCount;
942 audioBuffer->frameCount = framesReq;
943 audioBuffer->size = framesReq * cblk->frameSize;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700944 if (audio_is_linear_pcm(mFormat)) {
945 audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurenta553c252009-07-17 12:17:14 -0700946 } else {
947 audioBuffer->format = mFormat;
948 }
949 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 active = mActive;
951 return active ? status_t(NO_ERROR) : status_t(STOPPED);
952}
953
954void AudioTrack::releaseBuffer(Buffer* audioBuffer)
955{
Eric Laurent421ddc02011-03-07 14:52:59 -0800956 AutoMutex lock(mLock);
957 mCblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958}
959
960// -------------------------------------------------------------------------
961
962ssize_t AudioTrack::write(const void* buffer, size_t userSize)
963{
964
965 if (mSharedBuffer != 0) return INVALID_OPERATION;
966
967 if (ssize_t(userSize) < 0) {
968 // sanity-check. user is most-likely passing an error code.
969 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
970 buffer, userSize, userSize);
971 return BAD_VALUE;
972 }
973
Steve Block71f2cf12011-10-20 11:56:00 +0100974 ALOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975
Eric Laurent421ddc02011-03-07 14:52:59 -0800976 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
977 // while we are accessing the cblk
978 mLock.lock();
979 sp <IAudioTrack> audioTrack = mAudioTrack;
980 sp <IMemory> iMem = mCblkMemory;
981 mLock.unlock();
982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 ssize_t written = 0;
984 const int8_t *src = (const int8_t *)buffer;
985 Buffer audioBuffer;
Eric Laurent913af0b2011-03-17 09:36:51 -0700986 size_t frameSz = (size_t)frameSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987
988 do {
Eric Laurent913af0b2011-03-17 09:36:51 -0700989 audioBuffer.frameCount = userSize/frameSz;
Eric Laurenta553c252009-07-17 12:17:14 -0700990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 // Calling obtainBuffer() with a negative wait count causes
992 // an (almost) infinite wait time.
993 status_t err = obtainBuffer(&audioBuffer, -1);
994 if (err < 0) {
995 // out of buffers, return #bytes written
996 if (err == status_t(NO_MORE_BUFFERS))
997 break;
998 return ssize_t(err);
999 }
1000
1001 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -07001002
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001003 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 // Divide capacity by 2 to take expansion into account
1005 toWrite = audioBuffer.size>>1;
1006 // 8 to 16 bit conversion
1007 int count = toWrite;
1008 int16_t *dst = (int16_t *)(audioBuffer.i8);
1009 while(count--) {
1010 *dst++ = (int16_t)(*src++^0x80) << 8;
1011 }
Eric Laurent28ad42b2009-08-04 10:42:26 -07001012 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 toWrite = audioBuffer.size;
1014 memcpy(audioBuffer.i8, src, toWrite);
1015 src += toWrite;
1016 }
1017 userSize -= toWrite;
1018 written += toWrite;
1019
1020 releaseBuffer(&audioBuffer);
Eric Laurent913af0b2011-03-17 09:36:51 -07001021 } while (userSize >= frameSz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022
1023 return written;
1024}
1025
1026// -------------------------------------------------------------------------
1027
1028bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1029{
1030 Buffer audioBuffer;
1031 uint32_t frames;
1032 size_t writtenSize;
1033
Eric Laurent421ddc02011-03-07 14:52:59 -08001034 mLock.lock();
1035 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1036 // while we are accessing the cblk
1037 sp <IAudioTrack> audioTrack = mAudioTrack;
1038 sp <IMemory> iMem = mCblkMemory;
1039 audio_track_cblk_t* cblk = mCblk;
Glenn Kastene6810ff2012-01-03 09:42:47 -08001040 bool active = mActive;
Eric Laurent421ddc02011-03-07 14:52:59 -08001041 mLock.unlock();
1042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 // Manage underrun callback
Glenn Kastene6810ff2012-01-03 09:42:47 -08001044 if (active && (cblk->framesAvailable() == cblk->frameCount)) {
Steve Block71f2cf12011-10-20 11:56:00 +01001045 ALOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
Eric Laurentae29b762011-03-28 18:37:07 -07001046 if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 mCbf(EVENT_UNDERRUN, mUserData, 0);
Eric Laurent421ddc02011-03-07 14:52:59 -08001048 if (cblk->server == cblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001049 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 if (mSharedBuffer != 0) return false;
1052 }
1053 }
Eric Laurenta553c252009-07-17 12:17:14 -07001054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 // Manage loop end callback
Eric Laurent421ddc02011-03-07 14:52:59 -08001056 while (mLoopCount > cblk->loopCount) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 int loopCount = -1;
1058 mLoopCount--;
1059 if (mLoopCount >= 0) loopCount = mLoopCount;
1060
1061 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1062 }
1063
1064 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001065 if (!mMarkerReached && (mMarkerPosition > 0)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001066 if (cblk->server >= mMarkerPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001068 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
1070 }
1071
1072 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -07001073 if (mUpdatePeriod > 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001074 while (cblk->server >= mNewPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1076 mNewPosition += mUpdatePeriod;
1077 }
1078 }
1079
1080 // If Shared buffer is used, no data is requested from client.
1081 if (mSharedBuffer != 0) {
1082 frames = 0;
1083 } else {
1084 frames = mRemainingFrames;
1085 }
1086
Eric Laurentf1d360a2011-09-07 11:13:23 -07001087 int32_t waitCount = -1;
1088 if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) {
1089 waitCount = 1;
1090 }
1091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 do {
1093
1094 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -07001095
1096 // Calling obtainBuffer() with a wait count of 1
1097 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1098 // stuck here not being able to handle timed events (position, markers, loops).
Eric Laurentf1d360a2011-09-07 11:13:23 -07001099 status_t err = obtainBuffer(&audioBuffer, waitCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 if (err < NO_ERROR) {
1101 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -07001102 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 -08001103 return false;
1104 }
1105 break;
1106 }
1107 if (err == status_t(STOPPED)) return false;
1108
1109 // Divide buffer size by 2 to take into account the expansion
1110 // due to 8 to 16 bit conversion: the callback must fill only half
1111 // of the destination buffer
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001112 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 audioBuffer.size >>= 1;
1114 }
1115
1116 size_t reqSize = audioBuffer.size;
1117 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1118 writtenSize = audioBuffer.size;
1119
1120 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001121 if (ssize_t(writtenSize) <= 0) {
1122 // The callback is done filling buffers
1123 // Keep this thread going to handle timed events and
1124 // still try to get more data in intervals of WAIT_PERIOD_MS
1125 // but don't just loop and block the CPU, so wait
1126 usleep(WAIT_PERIOD_MS*1000);
1127 break;
1128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 if (writtenSize > reqSize) writtenSize = reqSize;
1130
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001131 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 // 8 to 16 bit conversion
1133 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1134 int count = writtenSize;
1135 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1136 while(count--) {
1137 *dst-- = (int16_t)(*src--^0x80) << 8;
1138 }
1139 writtenSize <<= 1;
1140 }
1141
1142 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001143 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1144 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1145 // 16 bit.
1146 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 frames -= audioBuffer.frameCount;
1149
1150 releaseBuffer(&audioBuffer);
1151 }
1152 while (frames);
1153
1154 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001155 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 } else {
1157 mRemainingFrames = frames;
1158 }
1159 return true;
1160}
1161
Eric Laurent421ddc02011-03-07 14:52:59 -08001162// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1163// the IAudioTrack and IMemory in case they are recreated here.
1164// If the IAudioTrack is successfully restored, the cblk pointer is updated
1165status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1166{
1167 status_t result;
1168
Eric Laurentae29b762011-03-28 18:37:07 -07001169 if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001170 LOGW("dead IAudioTrack, creating a new one from %s TID %d",
1171 fromStart ? "start()" : "obtainBuffer()", gettid());
Eric Laurent421ddc02011-03-07 14:52:59 -08001172
Eric Laurent421ddc02011-03-07 14:52:59 -08001173 // signal old cblk condition so that other threads waiting for available buffers stop
1174 // waiting now
1175 cblk->cv.broadcast();
1176 cblk->lock.unlock();
1177
Eric Laurent05ce0942011-08-30 10:18:54 -07001178 // refresh the audio configuration cache in this process to make sure we get new
1179 // output parameters in getOutput_l() and createTrack_l()
1180 AudioSystem::clearAudioConfigCache();
1181
Eric Laurent421ddc02011-03-07 14:52:59 -08001182 // if the new IAudioTrack is created, createTrack_l() will modify the
1183 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1184 // It will also delete the strong references on previous IAudioTrack and IMemory
1185 result = createTrack_l(mStreamType,
1186 cblk->sampleRate,
1187 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001188 mChannelMask,
Eric Laurent421ddc02011-03-07 14:52:59 -08001189 mFrameCount,
1190 mFlags,
1191 mSharedBuffer,
1192 getOutput_l(),
1193 false);
1194
1195 if (result == NO_ERROR) {
Eric Laurentb0808f92011-09-06 12:36:15 -07001196 uint32_t user = cblk->user;
1197 uint32_t server = cblk->server;
Eric Laurent6667ac32011-03-21 11:49:00 -07001198 // restore write index and set other indexes to reflect empty buffer status
Eric Laurentb0808f92011-09-06 12:36:15 -07001199 mCblk->user = user;
1200 mCblk->server = user;
1201 mCblk->userBase = user;
1202 mCblk->serverBase = user;
Eric Laurent6667ac32011-03-21 11:49:00 -07001203 // restore loop: this is not guaranteed to succeed if new frame count is not
1204 // compatible with loop length
1205 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
Eric Laurent421ddc02011-03-07 14:52:59 -08001206 if (!fromStart) {
1207 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
Eric Laurentb0808f92011-09-06 12:36:15 -07001208 // Make sure that a client relying on callback events indicating underrun or
1209 // the actual amount of audio frames played (e.g SoundPool) receives them.
1210 if (mSharedBuffer == 0) {
1211 uint32_t frames = 0;
1212 if (user > server) {
1213 frames = ((user - server) > mCblk->frameCount) ?
1214 mCblk->frameCount : (user - server);
1215 memset(mCblk->buffers, 0, frames * mCblk->frameSize);
1216 }
1217 // restart playback even if buffer is not completely filled.
1218 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
1219 // stepUser() clears CBLK_UNDERRUN_ON flag enabling underrun callbacks to
1220 // the client
1221 mCblk->stepUser(frames);
1222 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001223 }
Eric Laurent6667ac32011-03-21 11:49:00 -07001224 if (mActive) {
1225 result = mAudioTrack->start();
Eric Laurent7e8626f2011-09-13 15:04:17 -07001226 LOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result);
Eric Laurent6667ac32011-03-21 11:49:00 -07001227 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001228 if (fromStart && result == NO_ERROR) {
1229 mNewPosition = mCblk->server + mUpdatePeriod;
1230 }
1231 }
1232 if (result != NO_ERROR) {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001233 android_atomic_and(~CBLK_RESTORING_ON, &cblk->flags);
1234 LOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result);
Eric Laurent421ddc02011-03-07 14:52:59 -08001235 }
Eric Laurent7e8626f2011-09-13 15:04:17 -07001236 mRestoreStatus = result;
Eric Laurent421ddc02011-03-07 14:52:59 -08001237 // signal old cblk condition for other threads waiting for restore completion
Eric Laurentae29b762011-03-28 18:37:07 -07001238 android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -08001239 cblk->cv.broadcast();
Eric Laurent421ddc02011-03-07 14:52:59 -08001240 } else {
1241 if (!(cblk->flags & CBLK_RESTORED_MSK)) {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001242 LOGW("dead IAudioTrack, waiting for a new one TID %d", gettid());
Eric Laurent421ddc02011-03-07 14:52:59 -08001243 mLock.unlock();
1244 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
Eric Laurent7e8626f2011-09-13 15:04:17 -07001245 if (result == NO_ERROR) {
1246 result = mRestoreStatus;
1247 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001248 cblk->lock.unlock();
1249 mLock.lock();
1250 } else {
Eric Laurent7e8626f2011-09-13 15:04:17 -07001251 LOGW("dead IAudioTrack, already restored TID %d", gettid());
1252 result = mRestoreStatus;
Eric Laurent421ddc02011-03-07 14:52:59 -08001253 cblk->lock.unlock();
1254 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001255 }
Steve Block71f2cf12011-10-20 11:56:00 +01001256 ALOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
Eric Laurent421ddc02011-03-07 14:52:59 -08001257 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1258
1259 if (result == NO_ERROR) {
1260 // from now on we switch to the newly created cblk
1261 cblk = mCblk;
1262 }
1263 cblk->lock.lock();
1264
Eric Laurent7e8626f2011-09-13 15:04:17 -07001265 LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d TID %d", result, gettid());
Eric Laurent421ddc02011-03-07 14:52:59 -08001266
1267 return result;
1268}
1269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1271{
1272
1273 const size_t SIZE = 256;
1274 char buffer[SIZE];
1275 String8 result;
1276
1277 result.append(" AudioTrack::dump\n");
1278 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1279 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001280 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 -08001281 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001282 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 -08001283 result.append(buffer);
1284 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1285 result.append(buffer);
1286 ::write(fd, result.string(), result.size());
1287 return NO_ERROR;
1288}
1289
1290// =========================================================================
1291
1292AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1293 : Thread(bCanCallJava), mReceiver(receiver)
1294{
1295}
1296
1297bool AudioTrack::AudioTrackThread::threadLoop()
1298{
1299 return mReceiver.processAudioBuffer(this);
1300}
1301
1302status_t AudioTrack::AudioTrackThread::readyToRun()
1303{
1304 return NO_ERROR;
1305}
1306
1307void AudioTrack::AudioTrackThread::onFirstRef()
1308{
1309}
1310
1311// =========================================================================
1312
Eric Laurentae29b762011-03-28 18:37:07 -07001313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001315 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1316 userBase(0), serverBase(0), buffers(0), frameCount(0),
1317 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurentae29b762011-03-28 18:37:07 -07001318 sendLevel(0), flags(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319{
1320}
1321
1322uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1323{
Glenn Kastendb298a42011-12-13 11:45:07 -08001324 uint32_t u = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325
1326 u += frameCount;
1327 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001328 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1330 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1331 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1332 }
Glenn Kastendb298a42011-12-13 11:45:07 -08001333 } else if (u > server) {
1334 LOGW("stepServer occurred after track reset");
1335 u = server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 }
1337
1338 if (u >= userBase + this->frameCount) {
1339 userBase += this->frameCount;
1340 }
1341
Glenn Kastendb298a42011-12-13 11:45:07 -08001342 user = u;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343
1344 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurent913af0b2011-03-17 09:36:51 -07001345 if (flags & CBLK_UNDERRUN_MSK) {
Eric Laurentae29b762011-03-28 18:37:07 -07001346 android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
Eric Laurent913af0b2011-03-17 09:36:51 -07001347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348
1349 return u;
1350}
1351
1352bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1353{
Eric Laurentae29b762011-03-28 18:37:07 -07001354 if (!tryLock()) {
1355 LOGW("stepServer() could not lock cblk");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 return false;
1357 }
1358
Glenn Kastendb298a42011-12-13 11:45:07 -08001359 uint32_t s = server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360
1361 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001362 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 // Mark that we have read the first buffer so that next time stepUser() is called
1364 // we switch to normal obtainBuffer() timeout period
1365 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001366 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 // It is possible that we receive a flush()
1369 // while the mixer is processing a block: in this case,
1370 // stepServer() is called After the flush() has reset u & s and
1371 // we have s > u
Glenn Kastendb298a42011-12-13 11:45:07 -08001372 if (s > user) {
1373 LOGW("stepServer occurred after track reset");
1374 s = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
1376 }
1377
1378 if (s >= loopEnd) {
1379 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1380 s = loopStart;
1381 if (--loopCount == 0) {
1382 loopEnd = UINT_MAX;
1383 loopStart = UINT_MAX;
1384 }
1385 }
1386 if (s >= serverBase + this->frameCount) {
1387 serverBase += this->frameCount;
1388 }
1389
Glenn Kastendb298a42011-12-13 11:45:07 -08001390 server = s;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391
Eric Laurent421ddc02011-03-07 14:52:59 -08001392 if (!(flags & CBLK_INVALID_MSK)) {
1393 cv.signal();
1394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 lock.unlock();
1396 return true;
1397}
1398
1399void* audio_track_cblk_t::buffer(uint32_t offset) const
1400{
Glenn Kastendb298a42011-12-13 11:45:07 -08001401 return (int8_t *)buffers + (offset - userBase) * frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402}
1403
1404uint32_t audio_track_cblk_t::framesAvailable()
1405{
1406 Mutex::Autolock _l(lock);
1407 return framesAvailable_l();
1408}
1409
1410uint32_t audio_track_cblk_t::framesAvailable_l()
1411{
Glenn Kastendb298a42011-12-13 11:45:07 -08001412 uint32_t u = user;
1413 uint32_t s = server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001415 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 uint32_t limit = (s < loopStart) ? s : loopStart;
1417 return limit + frameCount - u;
1418 } else {
1419 return frameCount + u - s;
1420 }
1421}
1422
1423uint32_t audio_track_cblk_t::framesReady()
1424{
Glenn Kastendb298a42011-12-13 11:45:07 -08001425 uint32_t u = user;
1426 uint32_t s = server;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001428 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 if (u < loopEnd) {
1430 return u - s;
1431 } else {
Eric Laurentae29b762011-03-28 18:37:07 -07001432 // do not block on mutex shared with client on AudioFlinger side
1433 if (!tryLock()) {
1434 LOGW("framesReady() could not lock cblk");
1435 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 }
Eric Laurentae29b762011-03-28 18:37:07 -07001437 uint32_t frames = UINT_MAX;
1438 if (loopCount >= 0) {
1439 frames = (loopEnd - loopStart)*loopCount + u - s;
1440 }
1441 lock.unlock();
1442 return frames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 }
1444 } else {
1445 return s - u;
1446 }
1447}
1448
Eric Laurentae29b762011-03-28 18:37:07 -07001449bool audio_track_cblk_t::tryLock()
1450{
1451 // the code below simulates lock-with-timeout
1452 // we MUST do this to protect the AudioFlinger server
1453 // as this lock is shared with the client.
1454 status_t err;
1455
1456 err = lock.tryLock();
1457 if (err == -EBUSY) { // just wait a bit
1458 usleep(1000);
1459 err = lock.tryLock();
1460 }
1461 if (err != NO_ERROR) {
1462 // probably, the client just died.
1463 return false;
1464 }
1465 return true;
1466}
1467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468// -------------------------------------------------------------------------
1469
1470}; // namespace android