blob: 3949c3936902a229815add69d36e75e75407cbba [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/* //device/extlibs/pv/android/AudioTrack.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "AudioTrack"
21
22#include <stdint.h>
23#include <sys/types.h>
24#include <limits.h>
25
26#include <sched.h>
27#include <sys/resource.h>
28
29#include <private/media/AudioTrackShared.h>
30
31#include <media/AudioSystem.h>
32#include <media/AudioTrack.h>
33
34#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070035#include <binder/Parcel.h>
36#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037#include <utils/Timers.h>
Eric Laurentae29b762011-03-28 18:37:07 -070038#include <utils/Atomic.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039
Dima Zavin24fc2fb2011-04-19 22:30:36 -070040#include <cutils/bitops.h>
41
Dima Zavin34bb4192011-05-11 14:15:23 -070042#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070043#include <system/audio_policy.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
46#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
47
48namespace android {
Chia-chi Yehbd240c22010-06-16 06:33:13 +080049// ---------------------------------------------------------------------------
50
51// static
52status_t AudioTrack::getMinFrameCount(
53 int* frameCount,
54 int streamType,
55 uint32_t sampleRate)
56{
57 int afSampleRate;
58 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
59 return NO_INIT;
60 }
61 int afFrameCount;
62 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
63 return NO_INIT;
64 }
65 uint32_t afLatency;
66 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
67 return NO_INIT;
68 }
69
70 // Ensure that buffer depth covers at least audio hardware latency
71 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
72 if (minBufCount < 2) minBufCount = 2;
73
74 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
75 afFrameCount * minBufCount * sampleRate / afSampleRate;
76 return NO_ERROR;
77}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79// ---------------------------------------------------------------------------
80
81AudioTrack::AudioTrack()
82 : mStatus(NO_INIT)
83{
84}
85
86AudioTrack::AudioTrack(
87 int streamType,
88 uint32_t sampleRate,
89 int format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -070090 int channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 int frameCount,
92 uint32_t flags,
93 callback_t cbf,
94 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -070095 int notificationFrames,
96 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 : mStatus(NO_INIT)
98{
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)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 : mStatus(NO_INIT)
116{
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700117 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurent619346f2010-06-21 09:27:30 -0700118 0, flags, cbf, user, notificationFrames,
119 sharedBuffer, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120}
121
122AudioTrack::~AudioTrack()
123{
124 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
125
126 if (mStatus == NO_ERROR) {
127 // Make sure that callback function exits in the case where
128 // it is looping on buffer full condition in obtainBuffer().
129 // Otherwise the callback thread will never exit.
130 stop();
131 if (mAudioTrackThread != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 mAudioTrackThread->requestExitAndWait();
133 mAudioTrackThread.clear();
134 }
135 mAudioTrack.clear();
136 IPCThreadState::self()->flushCommands();
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700137 AudioSystem::releaseAudioSessionId(mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 }
139}
140
141status_t AudioTrack::set(
142 int streamType,
143 uint32_t sampleRate,
144 int format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700145 int channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 int frameCount,
147 uint32_t flags,
148 callback_t cbf,
149 void* user,
150 int notificationFrames,
151 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -0700152 bool threadCanCallJava,
153 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154{
155
156 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
157
Eric Laurent421ddc02011-03-07 14:52:59 -0800158 AutoMutex lock(mLock);
Eric Laurentef028272009-04-21 07:56:33 -0700159 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 LOGE("Track already in use");
161 return INVALID_OPERATION;
162 }
163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 int afSampleRate;
165 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
166 return NO_INIT;
167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 uint32_t afLatency;
169 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
170 return NO_INIT;
171 }
172
173 // handle default values first.
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700174 if (streamType == AUDIO_STREAM_DEFAULT) {
175 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 }
177 if (sampleRate == 0) {
178 sampleRate = afSampleRate;
179 }
180 // these below should probably come from the audioFlinger too...
181 if (format == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700182 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 }
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700184 if (channelMask == 0) {
185 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 }
187
188 // validate parameters
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700189 if (!audio_is_valid_format(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 LOGE("Invalid format");
191 return BAD_VALUE;
192 }
Eric Laurenta553c252009-07-17 12:17:14 -0700193
194 // force direct flag if format is not linear PCM
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700195 if (!audio_is_linear_pcm(format)) {
196 flags |= AUDIO_POLICY_OUTPUT_FLAG_DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -0700197 }
198
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700199 if (!audio_is_output_channel(channelMask)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700200 LOGE("Invalid channel mask");
201 return BAD_VALUE;
202 }
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700203 uint32_t channelCount = popcount(channelMask);
Eric Laurenta553c252009-07-17 12:17:14 -0700204
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700205 audio_io_handle_t output = AudioSystem::getOutput(
206 (audio_stream_type_t)streamType,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700207 sampleRate,format, channelMask,
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700208 (audio_policy_output_flags_t)flags);
Eric Laurenta553c252009-07-17 12:17:14 -0700209
210 if (output == 0) {
211 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 return BAD_VALUE;
213 }
214
Eric Laurentbda74692009-11-04 08:27:26 -0800215 mVolume[LEFT] = 1.0f;
216 mVolume[RIGHT] = 1.0f;
Eric Laurent65b65452010-06-01 23:49:17 -0700217 mSendLevel = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700218 mFrameCount = frameCount;
219 mNotificationFramesReq = notificationFrames;
Eric Laurent65b65452010-06-01 23:49:17 -0700220 mSessionId = sessionId;
Eric Laurent7070b362010-07-16 07:43:46 -0700221 mAuxEffectId = 0;
Eric Laurent65b65452010-06-01 23:49:17 -0700222
Eric Laurentbda74692009-11-04 08:27:26 -0800223 // create the IAudioTrack
Eric Laurent421ddc02011-03-07 14:52:59 -0800224 status_t status = createTrack_l(streamType,
225 sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700226 (uint32_t)format,
227 (uint32_t)channelMask,
Eric Laurent421ddc02011-03-07 14:52:59 -0800228 frameCount,
229 flags,
230 sharedBuffer,
231 output,
232 true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
Eric Laurentbda74692009-11-04 08:27:26 -0800234 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 return status;
236 }
Eric Laurentbda74692009-11-04 08:27:26 -0800237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 if (cbf != 0) {
239 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
240 if (mAudioTrackThread == 0) {
241 LOGE("Could not create callback thread");
242 return NO_INIT;
243 }
244 }
245
246 mStatus = NO_ERROR;
247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 mStreamType = streamType;
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700249 mFormat = (uint32_t)format;
250 mChannelMask = (uint32_t)channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 mChannelCount = channelCount;
252 mSharedBuffer = sharedBuffer;
253 mMuted = false;
254 mActive = 0;
255 mCbf = cbf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 mUserData = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 mLoopCount = 0;
258 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700259 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 mNewPosition = 0;
261 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700262 mFlags = flags;
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700263 AudioSystem::acquireAudioSessionId(mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264
265 return NO_ERROR;
266}
267
268status_t AudioTrack::initCheck() const
269{
270 return mStatus;
271}
272
273// -------------------------------------------------------------------------
274
275uint32_t AudioTrack::latency() const
276{
277 return mLatency;
278}
279
280int AudioTrack::streamType() const
281{
282 return mStreamType;
283}
284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285int AudioTrack::format() const
286{
287 return mFormat;
288}
289
290int AudioTrack::channelCount() const
291{
292 return mChannelCount;
293}
294
295uint32_t AudioTrack::frameCount() const
296{
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700297 return mCblk->frameCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298}
299
300int AudioTrack::frameSize() const
301{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700302 if (audio_is_linear_pcm(mFormat)) {
Eric Laurentc310dcb2011-06-16 21:30:45 -0700303 return channelCount()*audio_bytes_per_sample(mFormat);
Eric Laurenta553c252009-07-17 12:17:14 -0700304 } else {
305 return sizeof(uint8_t);
306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307}
308
309sp<IMemory>& AudioTrack::sharedBuffer()
310{
311 return mSharedBuffer;
312}
313
314// -------------------------------------------------------------------------
315
316void AudioTrack::start()
317{
318 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten028ab992011-06-22 16:18:04 -0700319 status_t status = NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320
321 LOGV("start %p", this);
322 if (t != 0) {
323 if (t->exitPending()) {
324 if (t->requestExitAndWait() == WOULD_BLOCK) {
325 LOGE("AudioTrack::start called from thread");
326 return;
327 }
328 }
329 t->mLock.lock();
330 }
331
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800332 AutoMutex lock(mLock);
Eric Laurent421ddc02011-03-07 14:52:59 -0800333 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
334 // while we are accessing the cblk
335 sp <IAudioTrack> audioTrack = mAudioTrack;
336 sp <IMemory> iMem = mCblkMemory;
337 audio_track_cblk_t* cblk = mCblk;
338
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800339 if (mActive == 0) {
340 mActive = 1;
Eric Laurent421ddc02011-03-07 14:52:59 -0800341 mNewPosition = cblk->server + mUpdatePeriod;
Eric Laurent913af0b2011-03-17 09:36:51 -0700342 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800343 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
344 cblk->waitTimeMs = 0;
Eric Laurentae29b762011-03-28 18:37:07 -0700345 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -0800346 if (t != 0) {
Glenn Kasten993fcce2011-06-01 16:46:29 -0700347 t->run("AudioTrackThread", ANDROID_PRIORITY_AUDIO);
Eric Laurent059b4be2009-11-09 23:32:22 -0800348 } else {
Glenn Kasten993fcce2011-06-01 16:46:29 -0700349 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
Eric Laurent059b4be2009-11-09 23:32:22 -0800350 }
351
Eric Laurent421ddc02011-03-07 14:52:59 -0800352 LOGV("start %p before lock cblk %p", this, mCblk);
Eric Laurent421ddc02011-03-07 14:52:59 -0800353 if (!(cblk->flags & CBLK_INVALID_MSK)) {
354 cblk->lock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700355 status = mAudioTrack->start();
Eric Laurent421ddc02011-03-07 14:52:59 -0800356 cblk->lock.lock();
357 if (status == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700358 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent49f02be2009-11-19 09:00:56 -0800359 }
Eric Laurent059b4be2009-11-09 23:32:22 -0800360 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800361 if (cblk->flags & CBLK_INVALID_MSK) {
362 status = restoreTrack_l(cblk, true);
363 }
364 cblk->lock.unlock();
Eric Laurent059b4be2009-11-09 23:32:22 -0800365 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800366 LOGV("start() failed");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800367 mActive = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -0800368 if (t != 0) {
369 t->requestExit();
370 } else {
371 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
372 }
Eric Laurentbda74692009-11-04 08:27:26 -0800373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 }
375
376 if (t != 0) {
377 t->mLock.unlock();
378 }
379}
380
381void AudioTrack::stop()
382{
383 sp<AudioTrackThread> t = mAudioTrackThread;
384
385 LOGV("stop %p", this);
386 if (t != 0) {
387 t->mLock.lock();
388 }
389
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800390 AutoMutex lock(mLock);
391 if (mActive == 1) {
392 mActive = 0;
Eric Laurentef028272009-04-21 07:56:33 -0700393 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 mAudioTrack->stop();
395 // Cancel loops (If we are in the middle of a loop, playback
396 // would not stop until loopCount reaches 0).
Eric Laurent421ddc02011-03-07 14:52:59 -0800397 setLoop_l(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700398 // the playback head position will reset to 0, so if a marker is set, we need
399 // to activate it again
400 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 // Force flush if a shared buffer is used otherwise audioflinger
402 // will not stop before end of buffer is reached.
403 if (mSharedBuffer != 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800404 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 }
406 if (t != 0) {
407 t->requestExit();
408 } else {
409 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
410 }
411 }
412
413 if (t != 0) {
414 t->mLock.unlock();
415 }
416}
417
418bool AudioTrack::stopped() const
419{
420 return !mActive;
421}
422
423void AudioTrack::flush()
424{
Eric Laurent421ddc02011-03-07 14:52:59 -0800425 AutoMutex lock(mLock);
426 flush_l();
427}
428
429// must be called with mLock held
430void AudioTrack::flush_l()
431{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700433
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700434 // clear playback marker and periodic update counter
435 mMarkerPosition = 0;
436 mMarkerReached = false;
437 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 mAudioTrack->flush();
441 // Release AudioTrack callback thread in case it was waiting for new buffers
442 // in AudioTrack::obtainBuffer()
443 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 }
445}
446
447void AudioTrack::pause()
448{
449 LOGV("pause");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800450 AutoMutex lock(mLock);
451 if (mActive == 1) {
452 mActive = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 mAudioTrack->pause();
454 }
455}
456
457void AudioTrack::mute(bool e)
458{
459 mAudioTrack->mute(e);
460 mMuted = e;
461}
462
463bool AudioTrack::muted() const
464{
465 return mMuted;
466}
467
Eric Laurent65b65452010-06-01 23:49:17 -0700468status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469{
Eric Laurent65b65452010-06-01 23:49:17 -0700470 if (left > 1.0f || right > 1.0f) {
471 return BAD_VALUE;
472 }
473
Eric Laurent421ddc02011-03-07 14:52:59 -0800474 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 mVolume[LEFT] = left;
476 mVolume[RIGHT] = right;
477
478 // write must be atomic
Eric Laurent65b65452010-06-01 23:49:17 -0700479 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
480
481 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482}
483
484void AudioTrack::getVolume(float* left, float* right)
485{
Eric Laurent65b65452010-06-01 23:49:17 -0700486 if (left != NULL) {
487 *left = mVolume[LEFT];
488 }
489 if (right != NULL) {
490 *right = mVolume[RIGHT];
491 }
492}
493
Eric Laurent7070b362010-07-16 07:43:46 -0700494status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurent65b65452010-06-01 23:49:17 -0700495{
Eric Laurent7070b362010-07-16 07:43:46 -0700496 LOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurent65b65452010-06-01 23:49:17 -0700497 if (level > 1.0f) {
498 return BAD_VALUE;
499 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800500 AutoMutex lock(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -0700501
502 mSendLevel = level;
503
504 mCblk->sendLevel = uint16_t(level * 0x1000);
505
506 return NO_ERROR;
507}
508
Eric Laurent7070b362010-07-16 07:43:46 -0700509void AudioTrack::getAuxEffectSendLevel(float* level)
Eric Laurent65b65452010-06-01 23:49:17 -0700510{
511 if (level != NULL) {
512 *level = mSendLevel;
513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514}
515
Eric Laurent88e209d2009-07-07 07:10:45 -0700516status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517{
518 int afSamplingRate;
519
520 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700521 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 }
523 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700524 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525
Eric Laurent421ddc02011-03-07 14:52:59 -0800526 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700527 mCblk->sampleRate = rate;
528 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529}
530
531uint32_t AudioTrack::getSampleRate()
532{
Eric Laurent421ddc02011-03-07 14:52:59 -0800533 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700534 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535}
536
537status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
538{
Eric Laurent421ddc02011-03-07 14:52:59 -0800539 AutoMutex lock(mLock);
540 return setLoop_l(loopStart, loopEnd, loopCount);
541}
542
543// must be called with mLock held
544status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
545{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 audio_track_cblk_t* cblk = mCblk;
547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 Mutex::Autolock _l(cblk->lock);
549
550 if (loopCount == 0) {
551 cblk->loopStart = UINT_MAX;
552 cblk->loopEnd = UINT_MAX;
553 cblk->loopCount = 0;
554 mLoopCount = 0;
555 return NO_ERROR;
556 }
557
558 if (loopStart >= loopEnd ||
Eric Laurent6667ac32011-03-21 11:49:00 -0700559 loopEnd - loopStart > cblk->frameCount ||
560 cblk->server > loopStart) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700561 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 -0800562 return BAD_VALUE;
563 }
564
Eric Laurent6667ac32011-03-21 11:49:00 -0700565 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700567 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570
571 cblk->loopStart = loopStart;
572 cblk->loopEnd = loopEnd;
573 cblk->loopCount = loopCount;
574 mLoopCount = loopCount;
575
576 return NO_ERROR;
577}
578
579status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
580{
Eric Laurent421ddc02011-03-07 14:52:59 -0800581 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 if (loopStart != 0) {
583 *loopStart = mCblk->loopStart;
584 }
585 if (loopEnd != 0) {
586 *loopEnd = mCblk->loopEnd;
587 }
588 if (loopCount != 0) {
589 if (mCblk->loopCount < 0) {
590 *loopCount = -1;
591 } else {
592 *loopCount = mCblk->loopCount;
593 }
594 }
595
596 return NO_ERROR;
597}
598
599status_t AudioTrack::setMarkerPosition(uint32_t marker)
600{
601 if (mCbf == 0) return INVALID_OPERATION;
602
603 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700604 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605
606 return NO_ERROR;
607}
608
609status_t AudioTrack::getMarkerPosition(uint32_t *marker)
610{
611 if (marker == 0) return BAD_VALUE;
612
613 *marker = mMarkerPosition;
614
615 return NO_ERROR;
616}
617
618status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
619{
620 if (mCbf == 0) return INVALID_OPERATION;
621
622 uint32_t curPosition;
623 getPosition(&curPosition);
624 mNewPosition = curPosition + updatePeriod;
625 mUpdatePeriod = updatePeriod;
626
627 return NO_ERROR;
628}
629
630status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
631{
632 if (updatePeriod == 0) return BAD_VALUE;
633
634 *updatePeriod = mUpdatePeriod;
635
636 return NO_ERROR;
637}
638
639status_t AudioTrack::setPosition(uint32_t position)
640{
Eric Laurent421ddc02011-03-07 14:52:59 -0800641 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 Mutex::Autolock _l(mCblk->lock);
643
644 if (!stopped()) return INVALID_OPERATION;
645
646 if (position > mCblk->user) return BAD_VALUE;
647
648 mCblk->server = position;
Eric Laurentae29b762011-03-28 18:37:07 -0700649 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -0700650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 return NO_ERROR;
652}
653
654status_t AudioTrack::getPosition(uint32_t *position)
655{
656 if (position == 0) return BAD_VALUE;
Eric Laurent421ddc02011-03-07 14:52:59 -0800657 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 *position = mCblk->server;
659
660 return NO_ERROR;
661}
662
663status_t AudioTrack::reload()
664{
Eric Laurent421ddc02011-03-07 14:52:59 -0800665 AutoMutex lock(mLock);
666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700668
Eric Laurent421ddc02011-03-07 14:52:59 -0800669 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700671 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672
673 return NO_ERROR;
674}
675
Eric Laurenta553c252009-07-17 12:17:14 -0700676audio_io_handle_t AudioTrack::getOutput()
677{
Eric Laurent421ddc02011-03-07 14:52:59 -0800678 AutoMutex lock(mLock);
679 return getOutput_l();
680}
681
682// must be called with mLock held
683audio_io_handle_t AudioTrack::getOutput_l()
684{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700685 return AudioSystem::getOutput((audio_stream_type_t)mStreamType,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700686 mCblk->sampleRate, mFormat, mChannelMask, (audio_policy_output_flags_t)mFlags);
Eric Laurenta553c252009-07-17 12:17:14 -0700687}
688
Eric Laurent65b65452010-06-01 23:49:17 -0700689int AudioTrack::getSessionId()
690{
691 return mSessionId;
692}
693
694status_t AudioTrack::attachAuxEffect(int effectId)
695{
Eric Laurent7070b362010-07-16 07:43:46 -0700696 LOGV("attachAuxEffect(%d)", effectId);
697 status_t status = mAudioTrack->attachAuxEffect(effectId);
698 if (status == NO_ERROR) {
699 mAuxEffectId = effectId;
700 }
701 return status;
Eric Laurent65b65452010-06-01 23:49:17 -0700702}
703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704// -------------------------------------------------------------------------
705
Eric Laurent421ddc02011-03-07 14:52:59 -0800706// must be called with mLock held
707status_t AudioTrack::createTrack_l(
Eric Laurentbda74692009-11-04 08:27:26 -0800708 int streamType,
709 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700710 uint32_t format,
711 uint32_t channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800712 int frameCount,
713 uint32_t flags,
714 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700715 audio_io_handle_t output,
716 bool enforceFrameCount)
Eric Laurentbda74692009-11-04 08:27:26 -0800717{
718 status_t status;
719 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
720 if (audioFlinger == 0) {
721 LOGE("Could not get audioflinger");
722 return NO_INIT;
723 }
724
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700725 int afSampleRate;
726 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
727 return NO_INIT;
728 }
729 int afFrameCount;
730 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
731 return NO_INIT;
732 }
733 uint32_t afLatency;
734 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
735 return NO_INIT;
736 }
737
738 mNotificationFramesAct = mNotificationFramesReq;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700739 if (!audio_is_linear_pcm(format)) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700740 if (sharedBuffer != 0) {
741 frameCount = sharedBuffer->size();
742 }
743 } else {
744 // Ensure that buffer depth covers at least audio hardware latency
745 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
746 if (minBufCount < 2) minBufCount = 2;
747
748 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
749
750 if (sharedBuffer == 0) {
751 if (frameCount == 0) {
752 frameCount = minFrameCount;
753 }
754 if (mNotificationFramesAct == 0) {
755 mNotificationFramesAct = frameCount/2;
756 }
757 // Make sure that application is notified with sufficient margin
758 // before underrun
759 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
760 mNotificationFramesAct = frameCount/2;
761 }
762 if (frameCount < minFrameCount) {
763 if (enforceFrameCount) {
764 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
765 return BAD_VALUE;
766 } else {
767 frameCount = minFrameCount;
768 }
769 }
770 } else {
771 // Ensure that buffer alignment matches channelcount
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700772 int channelCount = popcount(channelMask);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700773 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
774 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
775 return BAD_VALUE;
776 }
777 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
778 }
779 }
780
Eric Laurentbda74692009-11-04 08:27:26 -0800781 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
782 streamType,
783 sampleRate,
784 format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700785 channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800786 frameCount,
787 ((uint16_t)flags) << 16,
788 sharedBuffer,
789 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700790 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800791 &status);
792
793 if (track == 0) {
794 LOGE("AudioFlinger could not create track, status: %d", status);
795 return status;
796 }
797 sp<IMemory> cblk = track->getCblk();
798 if (cblk == 0) {
799 LOGE("Could not get control block");
800 return NO_INIT;
801 }
802 mAudioTrack.clear();
803 mAudioTrack = track;
804 mCblkMemory.clear();
805 mCblkMemory = cblk;
806 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurentae29b762011-03-28 18:37:07 -0700807 android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
Eric Laurentbda74692009-11-04 08:27:26 -0800808 if (sharedBuffer == 0) {
809 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
810 } else {
811 mCblk->buffers = sharedBuffer->pointer();
812 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700813 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800814 }
815
Eric Laurent65b65452010-06-01 23:49:17 -0700816 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
817 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent7070b362010-07-16 07:43:46 -0700818 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent49f02be2009-11-19 09:00:56 -0800819 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
820 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700821 mRemainingFrames = mNotificationFramesAct;
822 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800823 return NO_ERROR;
824}
825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
827{
Eric Laurent421ddc02011-03-07 14:52:59 -0800828 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 int active;
Glenn Kasten028ab992011-06-22 16:18:04 -0700830 status_t result = NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 audio_track_cblk_t* cblk = mCblk;
832 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700833 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834
835 audioBuffer->frameCount = 0;
836 audioBuffer->size = 0;
837
838 uint32_t framesAvail = cblk->framesAvailable();
839
Eric Laurent6667ac32011-03-21 11:49:00 -0700840 cblk->lock.lock();
841 if (cblk->flags & CBLK_INVALID_MSK) {
842 goto create_new_track;
843 }
844 cblk->lock.unlock();
845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800847 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 goto start_loop_here;
849 while (framesAvail == 0) {
850 active = mActive;
851 if (UNLIKELY(!active)) {
852 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800853 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 return NO_MORE_BUFFERS;
855 }
Eric Laurentbda74692009-11-04 08:27:26 -0800856 if (UNLIKELY(!waitCount)) {
857 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800859 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700860 if (!(cblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800861 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700862 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700863 cblk->lock.unlock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800864 mLock.lock();
865 if (mActive == 0) {
866 return status_t(STOPPED);
867 }
868 cblk->lock.lock();
869 }
870
871 if (cblk->flags & CBLK_INVALID_MSK) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700872 goto create_new_track;
873 }
Eric Laurenta553c252009-07-17 12:17:14 -0700874 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700875 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
877 // timing out when a loop has been set and we have already written upto loop end
878 // is a normal condition: no need to wake AudioFlinger up.
879 if (cblk->user < cblk->loopEnd) {
880 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
881 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700882 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800884 result = mAudioTrack->start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800886 if (result == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700887 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -0800888create_new_track:
889 result = restoreTrack_l(cblk, false);
890 }
891 if (result != NO_ERROR) {
892 LOGW("obtainBuffer create Track error %d", result);
893 cblk->lock.unlock();
894 return result;
895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
897 cblk->waitTimeMs = 0;
898 }
Eric Laurenta553c252009-07-17 12:17:14 -0700899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800901 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 return TIMED_OUT;
903 }
904 }
905 // read the server count again
906 start_loop_here:
907 framesAvail = cblk->framesAvailable_l();
908 }
Eric Laurentbda74692009-11-04 08:27:26 -0800909 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911
Eric Laurent4712baa2010-09-30 16:12:31 -0700912 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent421ddc02011-03-07 14:52:59 -0800913 if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
Eric Laurentae29b762011-03-28 18:37:07 -0700914 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
915 LOGW("obtainBuffer() track %p disabled, restarting", this);
916 mAudioTrack->start();
Eric Laurent4712baa2010-09-30 16:12:31 -0700917 }
918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 if (framesReq > framesAvail) {
922 framesReq = framesAvail;
923 }
924
925 uint32_t u = cblk->user;
926 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
927
928 if (u + framesReq > bufferEnd) {
929 framesReq = bufferEnd - u;
930 }
931
Eric Laurenta553c252009-07-17 12:17:14 -0700932 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
933 audioBuffer->channelCount = mChannelCount;
934 audioBuffer->frameCount = framesReq;
935 audioBuffer->size = framesReq * cblk->frameSize;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700936 if (audio_is_linear_pcm(mFormat)) {
937 audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurenta553c252009-07-17 12:17:14 -0700938 } else {
939 audioBuffer->format = mFormat;
940 }
941 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 active = mActive;
943 return active ? status_t(NO_ERROR) : status_t(STOPPED);
944}
945
946void AudioTrack::releaseBuffer(Buffer* audioBuffer)
947{
Eric Laurent421ddc02011-03-07 14:52:59 -0800948 AutoMutex lock(mLock);
949 mCblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950}
951
952// -------------------------------------------------------------------------
953
954ssize_t AudioTrack::write(const void* buffer, size_t userSize)
955{
956
957 if (mSharedBuffer != 0) return INVALID_OPERATION;
958
959 if (ssize_t(userSize) < 0) {
960 // sanity-check. user is most-likely passing an error code.
961 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
962 buffer, userSize, userSize);
963 return BAD_VALUE;
964 }
965
966 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
967
Eric Laurent421ddc02011-03-07 14:52:59 -0800968 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
969 // while we are accessing the cblk
970 mLock.lock();
971 sp <IAudioTrack> audioTrack = mAudioTrack;
972 sp <IMemory> iMem = mCblkMemory;
973 mLock.unlock();
974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 ssize_t written = 0;
976 const int8_t *src = (const int8_t *)buffer;
977 Buffer audioBuffer;
Eric Laurent913af0b2011-03-17 09:36:51 -0700978 size_t frameSz = (size_t)frameSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979
980 do {
Eric Laurent913af0b2011-03-17 09:36:51 -0700981 audioBuffer.frameCount = userSize/frameSz;
Eric Laurenta553c252009-07-17 12:17:14 -0700982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 // Calling obtainBuffer() with a negative wait count causes
984 // an (almost) infinite wait time.
985 status_t err = obtainBuffer(&audioBuffer, -1);
986 if (err < 0) {
987 // out of buffers, return #bytes written
988 if (err == status_t(NO_MORE_BUFFERS))
989 break;
990 return ssize_t(err);
991 }
992
993 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700994
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700995 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 // Divide capacity by 2 to take expansion into account
997 toWrite = audioBuffer.size>>1;
998 // 8 to 16 bit conversion
999 int count = toWrite;
1000 int16_t *dst = (int16_t *)(audioBuffer.i8);
1001 while(count--) {
1002 *dst++ = (int16_t)(*src++^0x80) << 8;
1003 }
Eric Laurent28ad42b2009-08-04 10:42:26 -07001004 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 toWrite = audioBuffer.size;
1006 memcpy(audioBuffer.i8, src, toWrite);
1007 src += toWrite;
1008 }
1009 userSize -= toWrite;
1010 written += toWrite;
1011
1012 releaseBuffer(&audioBuffer);
Eric Laurent913af0b2011-03-17 09:36:51 -07001013 } while (userSize >= frameSz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014
1015 return written;
1016}
1017
1018// -------------------------------------------------------------------------
1019
1020bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1021{
1022 Buffer audioBuffer;
1023 uint32_t frames;
1024 size_t writtenSize;
1025
Eric Laurent421ddc02011-03-07 14:52:59 -08001026 mLock.lock();
1027 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1028 // while we are accessing the cblk
1029 sp <IAudioTrack> audioTrack = mAudioTrack;
1030 sp <IMemory> iMem = mCblkMemory;
1031 audio_track_cblk_t* cblk = mCblk;
1032 mLock.unlock();
1033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 // Manage underrun callback
Eric Laurentae29b762011-03-28 18:37:07 -07001035 if (mActive && (cblk->framesAvailable() == cblk->frameCount)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001036 LOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
Eric Laurentae29b762011-03-28 18:37:07 -07001037 if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 mCbf(EVENT_UNDERRUN, mUserData, 0);
Eric Laurent421ddc02011-03-07 14:52:59 -08001039 if (cblk->server == cblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001040 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 if (mSharedBuffer != 0) return false;
1043 }
1044 }
Eric Laurenta553c252009-07-17 12:17:14 -07001045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 // Manage loop end callback
Eric Laurent421ddc02011-03-07 14:52:59 -08001047 while (mLoopCount > cblk->loopCount) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 int loopCount = -1;
1049 mLoopCount--;
1050 if (mLoopCount >= 0) loopCount = mLoopCount;
1051
1052 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1053 }
1054
1055 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001056 if (!mMarkerReached && (mMarkerPosition > 0)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001057 if (cblk->server >= mMarkerPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001059 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 }
1061 }
1062
1063 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -07001064 if (mUpdatePeriod > 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001065 while (cblk->server >= mNewPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1067 mNewPosition += mUpdatePeriod;
1068 }
1069 }
1070
1071 // If Shared buffer is used, no data is requested from client.
1072 if (mSharedBuffer != 0) {
1073 frames = 0;
1074 } else {
1075 frames = mRemainingFrames;
1076 }
1077
1078 do {
1079
1080 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -07001081
1082 // Calling obtainBuffer() with a wait count of 1
1083 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1084 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 status_t err = obtainBuffer(&audioBuffer, 1);
1086 if (err < NO_ERROR) {
1087 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -07001088 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 -08001089 return false;
1090 }
1091 break;
1092 }
1093 if (err == status_t(STOPPED)) return false;
1094
1095 // Divide buffer size by 2 to take into account the expansion
1096 // due to 8 to 16 bit conversion: the callback must fill only half
1097 // of the destination buffer
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001098 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 audioBuffer.size >>= 1;
1100 }
1101
1102 size_t reqSize = audioBuffer.size;
1103 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1104 writtenSize = audioBuffer.size;
1105
1106 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001107 if (ssize_t(writtenSize) <= 0) {
1108 // The callback is done filling buffers
1109 // Keep this thread going to handle timed events and
1110 // still try to get more data in intervals of WAIT_PERIOD_MS
1111 // but don't just loop and block the CPU, so wait
1112 usleep(WAIT_PERIOD_MS*1000);
1113 break;
1114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 if (writtenSize > reqSize) writtenSize = reqSize;
1116
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001117 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 // 8 to 16 bit conversion
1119 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1120 int count = writtenSize;
1121 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1122 while(count--) {
1123 *dst-- = (int16_t)(*src--^0x80) << 8;
1124 }
1125 writtenSize <<= 1;
1126 }
1127
1128 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001129 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1130 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1131 // 16 bit.
1132 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 frames -= audioBuffer.frameCount;
1135
1136 releaseBuffer(&audioBuffer);
1137 }
1138 while (frames);
1139
1140 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001141 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 } else {
1143 mRemainingFrames = frames;
1144 }
1145 return true;
1146}
1147
Eric Laurent421ddc02011-03-07 14:52:59 -08001148// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1149// the IAudioTrack and IMemory in case they are recreated here.
1150// If the IAudioTrack is successfully restored, the cblk pointer is updated
1151status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1152{
1153 status_t result;
1154
Eric Laurentae29b762011-03-28 18:37:07 -07001155 if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001156 LOGW("dead IAudioTrack, creating a new one from %s",
1157 fromStart ? "start()" : "obtainBuffer()");
1158
Eric Laurent421ddc02011-03-07 14:52:59 -08001159 // signal old cblk condition so that other threads waiting for available buffers stop
1160 // waiting now
1161 cblk->cv.broadcast();
1162 cblk->lock.unlock();
1163
1164 // if the new IAudioTrack is created, createTrack_l() will modify the
1165 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1166 // It will also delete the strong references on previous IAudioTrack and IMemory
1167 result = createTrack_l(mStreamType,
1168 cblk->sampleRate,
1169 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001170 mChannelMask,
Eric Laurent421ddc02011-03-07 14:52:59 -08001171 mFrameCount,
1172 mFlags,
1173 mSharedBuffer,
1174 getOutput_l(),
1175 false);
1176
1177 if (result == NO_ERROR) {
Eric Laurent6667ac32011-03-21 11:49:00 -07001178 // restore write index and set other indexes to reflect empty buffer status
1179 mCblk->user = cblk->user;
1180 mCblk->server = cblk->user;
1181 mCblk->userBase = cblk->user;
1182 mCblk->serverBase = cblk->user;
1183 // restore loop: this is not guaranteed to succeed if new frame count is not
1184 // compatible with loop length
1185 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
Eric Laurent421ddc02011-03-07 14:52:59 -08001186 if (!fromStart) {
1187 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1188 }
Eric Laurent6667ac32011-03-21 11:49:00 -07001189 if (mActive) {
1190 result = mAudioTrack->start();
1191 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001192 if (fromStart && result == NO_ERROR) {
1193 mNewPosition = mCblk->server + mUpdatePeriod;
1194 }
1195 }
1196 if (result != NO_ERROR) {
1197 mActive = false;
1198 }
1199
1200 // signal old cblk condition for other threads waiting for restore completion
Eric Laurentae29b762011-03-28 18:37:07 -07001201 android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -08001202 cblk->cv.broadcast();
Eric Laurent421ddc02011-03-07 14:52:59 -08001203 } else {
1204 if (!(cblk->flags & CBLK_RESTORED_MSK)) {
1205 LOGW("dead IAudioTrack, waiting for a new one");
1206 mLock.unlock();
1207 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
1208 cblk->lock.unlock();
1209 mLock.lock();
1210 } else {
1211 LOGW("dead IAudioTrack, already restored");
1212 result = NO_ERROR;
1213 cblk->lock.unlock();
1214 }
1215 if (result != NO_ERROR || mActive == 0) {
1216 result = status_t(STOPPED);
1217 }
1218 }
1219 LOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1220 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1221
1222 if (result == NO_ERROR) {
1223 // from now on we switch to the newly created cblk
1224 cblk = mCblk;
1225 }
1226 cblk->lock.lock();
1227
1228 LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d", result);
1229
1230 return result;
1231}
1232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1234{
1235
1236 const size_t SIZE = 256;
1237 char buffer[SIZE];
1238 String8 result;
1239
1240 result.append(" AudioTrack::dump\n");
1241 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1242 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001243 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 -08001244 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001245 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 -08001246 result.append(buffer);
1247 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1248 result.append(buffer);
1249 ::write(fd, result.string(), result.size());
1250 return NO_ERROR;
1251}
1252
1253// =========================================================================
1254
1255AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1256 : Thread(bCanCallJava), mReceiver(receiver)
1257{
1258}
1259
1260bool AudioTrack::AudioTrackThread::threadLoop()
1261{
1262 return mReceiver.processAudioBuffer(this);
1263}
1264
1265status_t AudioTrack::AudioTrackThread::readyToRun()
1266{
1267 return NO_ERROR;
1268}
1269
1270void AudioTrack::AudioTrackThread::onFirstRef()
1271{
1272}
1273
1274// =========================================================================
1275
Eric Laurentae29b762011-03-28 18:37:07 -07001276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001278 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1279 userBase(0), serverBase(0), buffers(0), frameCount(0),
1280 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurentae29b762011-03-28 18:37:07 -07001281 sendLevel(0), flags(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282{
1283}
1284
1285uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1286{
1287 uint32_t u = this->user;
1288
1289 u += frameCount;
1290 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001291 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1293 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1294 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1295 }
1296 } else if (u > this->server) {
1297 LOGW("stepServer occured after track reset");
1298 u = this->server;
1299 }
1300
1301 if (u >= userBase + this->frameCount) {
1302 userBase += this->frameCount;
1303 }
1304
1305 this->user = u;
1306
1307 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurent913af0b2011-03-17 09:36:51 -07001308 if (flags & CBLK_UNDERRUN_MSK) {
Eric Laurentae29b762011-03-28 18:37:07 -07001309 android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
Eric Laurent913af0b2011-03-17 09:36:51 -07001310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311
1312 return u;
1313}
1314
1315bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1316{
Eric Laurentae29b762011-03-28 18:37:07 -07001317 if (!tryLock()) {
1318 LOGW("stepServer() could not lock cblk");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 return false;
1320 }
1321
1322 uint32_t s = this->server;
1323
1324 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001325 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 // Mark that we have read the first buffer so that next time stepUser() is called
1327 // we switch to normal obtainBuffer() timeout period
1328 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001329 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 // It is possible that we receive a flush()
1332 // while the mixer is processing a block: in this case,
1333 // stepServer() is called After the flush() has reset u & s and
1334 // we have s > u
1335 if (s > this->user) {
1336 LOGW("stepServer occured after track reset");
1337 s = this->user;
1338 }
1339 }
1340
1341 if (s >= loopEnd) {
1342 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1343 s = loopStart;
1344 if (--loopCount == 0) {
1345 loopEnd = UINT_MAX;
1346 loopStart = UINT_MAX;
1347 }
1348 }
1349 if (s >= serverBase + this->frameCount) {
1350 serverBase += this->frameCount;
1351 }
1352
1353 this->server = s;
1354
Eric Laurent421ddc02011-03-07 14:52:59 -08001355 if (!(flags & CBLK_INVALID_MSK)) {
1356 cv.signal();
1357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 lock.unlock();
1359 return true;
1360}
1361
1362void* audio_track_cblk_t::buffer(uint32_t offset) const
1363{
Eric Laurenta553c252009-07-17 12:17:14 -07001364 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365}
1366
1367uint32_t audio_track_cblk_t::framesAvailable()
1368{
1369 Mutex::Autolock _l(lock);
1370 return framesAvailable_l();
1371}
1372
1373uint32_t audio_track_cblk_t::framesAvailable_l()
1374{
1375 uint32_t u = this->user;
1376 uint32_t s = this->server;
1377
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001378 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 uint32_t limit = (s < loopStart) ? s : loopStart;
1380 return limit + frameCount - u;
1381 } else {
1382 return frameCount + u - s;
1383 }
1384}
1385
1386uint32_t audio_track_cblk_t::framesReady()
1387{
1388 uint32_t u = this->user;
1389 uint32_t s = this->server;
1390
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001391 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 if (u < loopEnd) {
1393 return u - s;
1394 } else {
Eric Laurentae29b762011-03-28 18:37:07 -07001395 // do not block on mutex shared with client on AudioFlinger side
1396 if (!tryLock()) {
1397 LOGW("framesReady() could not lock cblk");
1398 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
Eric Laurentae29b762011-03-28 18:37:07 -07001400 uint32_t frames = UINT_MAX;
1401 if (loopCount >= 0) {
1402 frames = (loopEnd - loopStart)*loopCount + u - s;
1403 }
1404 lock.unlock();
1405 return frames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 }
1407 } else {
1408 return s - u;
1409 }
1410}
1411
Eric Laurentae29b762011-03-28 18:37:07 -07001412bool audio_track_cblk_t::tryLock()
1413{
1414 // the code below simulates lock-with-timeout
1415 // we MUST do this to protect the AudioFlinger server
1416 // as this lock is shared with the client.
1417 status_t err;
1418
1419 err = lock.tryLock();
1420 if (err == -EBUSY) { // just wait a bit
1421 usleep(1000);
1422 err = lock.tryLock();
1423 }
1424 if (err != NO_ERROR) {
1425 // probably, the client just died.
1426 return false;
1427 }
1428 return true;
1429}
1430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431// -------------------------------------------------------------------------
1432
1433}; // namespace android
1434