blob: 6b4391bac6573349511be8dfc855909e23ad3528 [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 Zavin24fc2fb2011-04-19 22:30:36 -070043#include <hardware/audio_policy.h>
44
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();
137 }
138}
139
140status_t AudioTrack::set(
141 int streamType,
142 uint32_t sampleRate,
143 int format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700144 int channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 int frameCount,
146 uint32_t flags,
147 callback_t cbf,
148 void* user,
149 int notificationFrames,
150 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -0700151 bool threadCanCallJava,
152 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153{
154
155 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
156
Eric Laurent421ddc02011-03-07 14:52:59 -0800157 AutoMutex lock(mLock);
Eric Laurentef028272009-04-21 07:56:33 -0700158 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 LOGE("Track already in use");
160 return INVALID_OPERATION;
161 }
162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 int afSampleRate;
164 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
165 return NO_INIT;
166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 uint32_t afLatency;
168 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
169 return NO_INIT;
170 }
171
172 // handle default values first.
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700173 if (streamType == AUDIO_STREAM_DEFAULT) {
174 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 }
176 if (sampleRate == 0) {
177 sampleRate = afSampleRate;
178 }
179 // these below should probably come from the audioFlinger too...
180 if (format == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700181 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 }
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700183 if (channelMask == 0) {
184 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 }
186
187 // validate parameters
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700188 if (!audio_is_valid_format(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 LOGE("Invalid format");
190 return BAD_VALUE;
191 }
Eric Laurenta553c252009-07-17 12:17:14 -0700192
193 // force direct flag if format is not linear PCM
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700194 if (!audio_is_linear_pcm(format)) {
195 flags |= AUDIO_POLICY_OUTPUT_FLAG_DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -0700196 }
197
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700198 if (!audio_is_output_channel(channelMask)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700199 LOGE("Invalid channel mask");
200 return BAD_VALUE;
201 }
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700202 uint32_t channelCount = popcount(channelMask);
Eric Laurenta553c252009-07-17 12:17:14 -0700203
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700204 audio_io_handle_t output = AudioSystem::getOutput(
205 (audio_stream_type_t)streamType,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700206 sampleRate,format, channelMask,
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700207 (audio_policy_output_flags_t)flags);
Eric Laurenta553c252009-07-17 12:17:14 -0700208
209 if (output == 0) {
210 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 return BAD_VALUE;
212 }
213
Eric Laurentbda74692009-11-04 08:27:26 -0800214 mVolume[LEFT] = 1.0f;
215 mVolume[RIGHT] = 1.0f;
Eric Laurent65b65452010-06-01 23:49:17 -0700216 mSendLevel = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700217 mFrameCount = frameCount;
218 mNotificationFramesReq = notificationFrames;
Eric Laurent65b65452010-06-01 23:49:17 -0700219 mSessionId = sessionId;
Eric Laurent7070b362010-07-16 07:43:46 -0700220 mAuxEffectId = 0;
Eric Laurent65b65452010-06-01 23:49:17 -0700221
Eric Laurentbda74692009-11-04 08:27:26 -0800222 // create the IAudioTrack
Eric Laurent421ddc02011-03-07 14:52:59 -0800223 status_t status = createTrack_l(streamType,
224 sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700225 (uint32_t)format,
226 (uint32_t)channelMask,
Eric Laurent421ddc02011-03-07 14:52:59 -0800227 frameCount,
228 flags,
229 sharedBuffer,
230 output,
231 true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Eric Laurentbda74692009-11-04 08:27:26 -0800233 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 return status;
235 }
Eric Laurentbda74692009-11-04 08:27:26 -0800236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 if (cbf != 0) {
238 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
239 if (mAudioTrackThread == 0) {
240 LOGE("Could not create callback thread");
241 return NO_INIT;
242 }
243 }
244
245 mStatus = NO_ERROR;
246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 mStreamType = streamType;
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700248 mFormat = (uint32_t)format;
249 mChannelMask = (uint32_t)channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 mChannelCount = channelCount;
251 mSharedBuffer = sharedBuffer;
252 mMuted = false;
253 mActive = 0;
254 mCbf = cbf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 mUserData = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 mLoopCount = 0;
257 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700258 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 mNewPosition = 0;
260 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700261 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 return NO_ERROR;
264}
265
266status_t AudioTrack::initCheck() const
267{
268 return mStatus;
269}
270
271// -------------------------------------------------------------------------
272
273uint32_t AudioTrack::latency() const
274{
275 return mLatency;
276}
277
278int AudioTrack::streamType() const
279{
280 return mStreamType;
281}
282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283int AudioTrack::format() const
284{
285 return mFormat;
286}
287
288int AudioTrack::channelCount() const
289{
290 return mChannelCount;
291}
292
293uint32_t AudioTrack::frameCount() const
294{
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700295 return mCblk->frameCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296}
297
298int AudioTrack::frameSize() const
299{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700300 if (audio_is_linear_pcm(mFormat)) {
301 return channelCount()*((format() == AUDIO_FORMAT_PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -0700302 } else {
303 return sizeof(uint8_t);
304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305}
306
307sp<IMemory>& AudioTrack::sharedBuffer()
308{
309 return mSharedBuffer;
310}
311
312// -------------------------------------------------------------------------
313
314void AudioTrack::start()
315{
316 sp<AudioTrackThread> t = mAudioTrackThread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700317 status_t status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318
319 LOGV("start %p", this);
320 if (t != 0) {
321 if (t->exitPending()) {
322 if (t->requestExitAndWait() == WOULD_BLOCK) {
323 LOGE("AudioTrack::start called from thread");
324 return;
325 }
326 }
327 t->mLock.lock();
328 }
329
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800330 AutoMutex lock(mLock);
Eric Laurent421ddc02011-03-07 14:52:59 -0800331 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
332 // while we are accessing the cblk
333 sp <IAudioTrack> audioTrack = mAudioTrack;
334 sp <IMemory> iMem = mCblkMemory;
335 audio_track_cblk_t* cblk = mCblk;
336
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800337 if (mActive == 0) {
338 mActive = 1;
Eric Laurent421ddc02011-03-07 14:52:59 -0800339 mNewPosition = cblk->server + mUpdatePeriod;
Eric Laurent913af0b2011-03-17 09:36:51 -0700340 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800341 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
342 cblk->waitTimeMs = 0;
Eric Laurentae29b762011-03-28 18:37:07 -0700343 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -0800344 if (t != 0) {
Glenn Kasten993fcce2011-06-01 16:46:29 -0700345 t->run("AudioTrackThread", ANDROID_PRIORITY_AUDIO);
Eric Laurent059b4be2009-11-09 23:32:22 -0800346 } else {
Glenn Kasten993fcce2011-06-01 16:46:29 -0700347 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
Eric Laurent059b4be2009-11-09 23:32:22 -0800348 }
349
Eric Laurent421ddc02011-03-07 14:52:59 -0800350 LOGV("start %p before lock cblk %p", this, mCblk);
Eric Laurent421ddc02011-03-07 14:52:59 -0800351 if (!(cblk->flags & CBLK_INVALID_MSK)) {
352 cblk->lock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700353 status = mAudioTrack->start();
Eric Laurent421ddc02011-03-07 14:52:59 -0800354 cblk->lock.lock();
355 if (status == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700356 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent49f02be2009-11-19 09:00:56 -0800357 }
Eric Laurent059b4be2009-11-09 23:32:22 -0800358 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800359 if (cblk->flags & CBLK_INVALID_MSK) {
360 status = restoreTrack_l(cblk, true);
361 }
362 cblk->lock.unlock();
Eric Laurent059b4be2009-11-09 23:32:22 -0800363 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800364 LOGV("start() failed");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800365 mActive = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -0800366 if (t != 0) {
367 t->requestExit();
368 } else {
369 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
370 }
Eric Laurentbda74692009-11-04 08:27:26 -0800371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 }
373
374 if (t != 0) {
375 t->mLock.unlock();
376 }
377}
378
379void AudioTrack::stop()
380{
381 sp<AudioTrackThread> t = mAudioTrackThread;
382
383 LOGV("stop %p", this);
384 if (t != 0) {
385 t->mLock.lock();
386 }
387
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800388 AutoMutex lock(mLock);
389 if (mActive == 1) {
390 mActive = 0;
Eric Laurentef028272009-04-21 07:56:33 -0700391 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 mAudioTrack->stop();
393 // Cancel loops (If we are in the middle of a loop, playback
394 // would not stop until loopCount reaches 0).
Eric Laurent421ddc02011-03-07 14:52:59 -0800395 setLoop_l(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700396 // the playback head position will reset to 0, so if a marker is set, we need
397 // to activate it again
398 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 // Force flush if a shared buffer is used otherwise audioflinger
400 // will not stop before end of buffer is reached.
401 if (mSharedBuffer != 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800402 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 }
404 if (t != 0) {
405 t->requestExit();
406 } else {
407 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
408 }
409 }
410
411 if (t != 0) {
412 t->mLock.unlock();
413 }
414}
415
416bool AudioTrack::stopped() const
417{
418 return !mActive;
419}
420
421void AudioTrack::flush()
422{
Eric Laurent421ddc02011-03-07 14:52:59 -0800423 AutoMutex lock(mLock);
424 flush_l();
425}
426
427// must be called with mLock held
428void AudioTrack::flush_l()
429{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700431
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700432 // clear playback marker and periodic update counter
433 mMarkerPosition = 0;
434 mMarkerReached = false;
435 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 mAudioTrack->flush();
439 // Release AudioTrack callback thread in case it was waiting for new buffers
440 // in AudioTrack::obtainBuffer()
441 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 }
443}
444
445void AudioTrack::pause()
446{
447 LOGV("pause");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800448 AutoMutex lock(mLock);
449 if (mActive == 1) {
450 mActive = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 mAudioTrack->pause();
452 }
453}
454
455void AudioTrack::mute(bool e)
456{
457 mAudioTrack->mute(e);
458 mMuted = e;
459}
460
461bool AudioTrack::muted() const
462{
463 return mMuted;
464}
465
Eric Laurent65b65452010-06-01 23:49:17 -0700466status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467{
Eric Laurent65b65452010-06-01 23:49:17 -0700468 if (left > 1.0f || right > 1.0f) {
469 return BAD_VALUE;
470 }
471
Eric Laurent421ddc02011-03-07 14:52:59 -0800472 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 mVolume[LEFT] = left;
474 mVolume[RIGHT] = right;
475
476 // write must be atomic
Eric Laurent65b65452010-06-01 23:49:17 -0700477 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
478
479 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480}
481
482void AudioTrack::getVolume(float* left, float* right)
483{
Eric Laurent65b65452010-06-01 23:49:17 -0700484 if (left != NULL) {
485 *left = mVolume[LEFT];
486 }
487 if (right != NULL) {
488 *right = mVolume[RIGHT];
489 }
490}
491
Eric Laurent7070b362010-07-16 07:43:46 -0700492status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurent65b65452010-06-01 23:49:17 -0700493{
Eric Laurent7070b362010-07-16 07:43:46 -0700494 LOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurent65b65452010-06-01 23:49:17 -0700495 if (level > 1.0f) {
496 return BAD_VALUE;
497 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800498 AutoMutex lock(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -0700499
500 mSendLevel = level;
501
502 mCblk->sendLevel = uint16_t(level * 0x1000);
503
504 return NO_ERROR;
505}
506
Eric Laurent7070b362010-07-16 07:43:46 -0700507void AudioTrack::getAuxEffectSendLevel(float* level)
Eric Laurent65b65452010-06-01 23:49:17 -0700508{
509 if (level != NULL) {
510 *level = mSendLevel;
511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512}
513
Eric Laurent88e209d2009-07-07 07:10:45 -0700514status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515{
516 int afSamplingRate;
517
518 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700519 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 }
521 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700522 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523
Eric Laurent421ddc02011-03-07 14:52:59 -0800524 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700525 mCblk->sampleRate = rate;
526 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527}
528
529uint32_t AudioTrack::getSampleRate()
530{
Eric Laurent421ddc02011-03-07 14:52:59 -0800531 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700532 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533}
534
535status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
536{
Eric Laurent421ddc02011-03-07 14:52:59 -0800537 AutoMutex lock(mLock);
538 return setLoop_l(loopStart, loopEnd, loopCount);
539}
540
541// must be called with mLock held
542status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
543{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 audio_track_cblk_t* cblk = mCblk;
545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 Mutex::Autolock _l(cblk->lock);
547
548 if (loopCount == 0) {
549 cblk->loopStart = UINT_MAX;
550 cblk->loopEnd = UINT_MAX;
551 cblk->loopCount = 0;
552 mLoopCount = 0;
553 return NO_ERROR;
554 }
555
556 if (loopStart >= loopEnd ||
Eric Laurent6667ac32011-03-21 11:49:00 -0700557 loopEnd - loopStart > cblk->frameCount ||
558 cblk->server > loopStart) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700559 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 -0800560 return BAD_VALUE;
561 }
562
Eric Laurent6667ac32011-03-21 11:49:00 -0700563 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700565 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568
569 cblk->loopStart = loopStart;
570 cblk->loopEnd = loopEnd;
571 cblk->loopCount = loopCount;
572 mLoopCount = loopCount;
573
574 return NO_ERROR;
575}
576
577status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
578{
Eric Laurent421ddc02011-03-07 14:52:59 -0800579 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 if (loopStart != 0) {
581 *loopStart = mCblk->loopStart;
582 }
583 if (loopEnd != 0) {
584 *loopEnd = mCblk->loopEnd;
585 }
586 if (loopCount != 0) {
587 if (mCblk->loopCount < 0) {
588 *loopCount = -1;
589 } else {
590 *loopCount = mCblk->loopCount;
591 }
592 }
593
594 return NO_ERROR;
595}
596
597status_t AudioTrack::setMarkerPosition(uint32_t marker)
598{
599 if (mCbf == 0) return INVALID_OPERATION;
600
601 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700602 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603
604 return NO_ERROR;
605}
606
607status_t AudioTrack::getMarkerPosition(uint32_t *marker)
608{
609 if (marker == 0) return BAD_VALUE;
610
611 *marker = mMarkerPosition;
612
613 return NO_ERROR;
614}
615
616status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
617{
618 if (mCbf == 0) return INVALID_OPERATION;
619
620 uint32_t curPosition;
621 getPosition(&curPosition);
622 mNewPosition = curPosition + updatePeriod;
623 mUpdatePeriod = updatePeriod;
624
625 return NO_ERROR;
626}
627
628status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
629{
630 if (updatePeriod == 0) return BAD_VALUE;
631
632 *updatePeriod = mUpdatePeriod;
633
634 return NO_ERROR;
635}
636
637status_t AudioTrack::setPosition(uint32_t position)
638{
Eric Laurent421ddc02011-03-07 14:52:59 -0800639 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 Mutex::Autolock _l(mCblk->lock);
641
642 if (!stopped()) return INVALID_OPERATION;
643
644 if (position > mCblk->user) return BAD_VALUE;
645
646 mCblk->server = position;
Eric Laurentae29b762011-03-28 18:37:07 -0700647 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -0700648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 return NO_ERROR;
650}
651
652status_t AudioTrack::getPosition(uint32_t *position)
653{
654 if (position == 0) return BAD_VALUE;
Eric Laurent421ddc02011-03-07 14:52:59 -0800655 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 *position = mCblk->server;
657
658 return NO_ERROR;
659}
660
661status_t AudioTrack::reload()
662{
Eric Laurent421ddc02011-03-07 14:52:59 -0800663 AutoMutex lock(mLock);
664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700666
Eric Laurent421ddc02011-03-07 14:52:59 -0800667 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700669 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670
671 return NO_ERROR;
672}
673
Eric Laurenta553c252009-07-17 12:17:14 -0700674audio_io_handle_t AudioTrack::getOutput()
675{
Eric Laurent421ddc02011-03-07 14:52:59 -0800676 AutoMutex lock(mLock);
677 return getOutput_l();
678}
679
680// must be called with mLock held
681audio_io_handle_t AudioTrack::getOutput_l()
682{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700683 return AudioSystem::getOutput((audio_stream_type_t)mStreamType,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700684 mCblk->sampleRate, mFormat, mChannelMask, (audio_policy_output_flags_t)mFlags);
Eric Laurenta553c252009-07-17 12:17:14 -0700685}
686
Eric Laurent65b65452010-06-01 23:49:17 -0700687int AudioTrack::getSessionId()
688{
689 return mSessionId;
690}
691
692status_t AudioTrack::attachAuxEffect(int effectId)
693{
Eric Laurent7070b362010-07-16 07:43:46 -0700694 LOGV("attachAuxEffect(%d)", effectId);
695 status_t status = mAudioTrack->attachAuxEffect(effectId);
696 if (status == NO_ERROR) {
697 mAuxEffectId = effectId;
698 }
699 return status;
Eric Laurent65b65452010-06-01 23:49:17 -0700700}
701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702// -------------------------------------------------------------------------
703
Eric Laurent421ddc02011-03-07 14:52:59 -0800704// must be called with mLock held
705status_t AudioTrack::createTrack_l(
Eric Laurentbda74692009-11-04 08:27:26 -0800706 int streamType,
707 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700708 uint32_t format,
709 uint32_t channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800710 int frameCount,
711 uint32_t flags,
712 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700713 audio_io_handle_t output,
714 bool enforceFrameCount)
Eric Laurentbda74692009-11-04 08:27:26 -0800715{
716 status_t status;
717 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
718 if (audioFlinger == 0) {
719 LOGE("Could not get audioflinger");
720 return NO_INIT;
721 }
722
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700723 int afSampleRate;
724 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
725 return NO_INIT;
726 }
727 int afFrameCount;
728 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
729 return NO_INIT;
730 }
731 uint32_t afLatency;
732 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
733 return NO_INIT;
734 }
735
736 mNotificationFramesAct = mNotificationFramesReq;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700737 if (!audio_is_linear_pcm(format)) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700738 if (sharedBuffer != 0) {
739 frameCount = sharedBuffer->size();
740 }
741 } else {
742 // Ensure that buffer depth covers at least audio hardware latency
743 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
744 if (minBufCount < 2) minBufCount = 2;
745
746 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
747
748 if (sharedBuffer == 0) {
749 if (frameCount == 0) {
750 frameCount = minFrameCount;
751 }
752 if (mNotificationFramesAct == 0) {
753 mNotificationFramesAct = frameCount/2;
754 }
755 // Make sure that application is notified with sufficient margin
756 // before underrun
757 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
758 mNotificationFramesAct = frameCount/2;
759 }
760 if (frameCount < minFrameCount) {
761 if (enforceFrameCount) {
762 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
763 return BAD_VALUE;
764 } else {
765 frameCount = minFrameCount;
766 }
767 }
768 } else {
769 // Ensure that buffer alignment matches channelcount
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700770 int channelCount = popcount(channelMask);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700771 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
772 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
773 return BAD_VALUE;
774 }
775 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
776 }
777 }
778
Eric Laurentbda74692009-11-04 08:27:26 -0800779 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
780 streamType,
781 sampleRate,
782 format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700783 channelMask,
Eric Laurentbda74692009-11-04 08:27:26 -0800784 frameCount,
785 ((uint16_t)flags) << 16,
786 sharedBuffer,
787 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700788 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800789 &status);
790
791 if (track == 0) {
792 LOGE("AudioFlinger could not create track, status: %d", status);
793 return status;
794 }
795 sp<IMemory> cblk = track->getCblk();
796 if (cblk == 0) {
797 LOGE("Could not get control block");
798 return NO_INIT;
799 }
800 mAudioTrack.clear();
801 mAudioTrack = track;
802 mCblkMemory.clear();
803 mCblkMemory = cblk;
804 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurentae29b762011-03-28 18:37:07 -0700805 android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
Eric Laurentbda74692009-11-04 08:27:26 -0800806 if (sharedBuffer == 0) {
807 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
808 } else {
809 mCblk->buffers = sharedBuffer->pointer();
810 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700811 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800812 }
813
Eric Laurent65b65452010-06-01 23:49:17 -0700814 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
815 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent7070b362010-07-16 07:43:46 -0700816 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent49f02be2009-11-19 09:00:56 -0800817 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
818 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700819 mRemainingFrames = mNotificationFramesAct;
820 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800821 return NO_ERROR;
822}
823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
825{
Eric Laurent421ddc02011-03-07 14:52:59 -0800826 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 status_t result;
829 audio_track_cblk_t* cblk = mCblk;
830 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700831 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832
833 audioBuffer->frameCount = 0;
834 audioBuffer->size = 0;
835
836 uint32_t framesAvail = cblk->framesAvailable();
837
Eric Laurent6667ac32011-03-21 11:49:00 -0700838 cblk->lock.lock();
839 if (cblk->flags & CBLK_INVALID_MSK) {
840 goto create_new_track;
841 }
842 cblk->lock.unlock();
843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800845 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 goto start_loop_here;
847 while (framesAvail == 0) {
848 active = mActive;
849 if (UNLIKELY(!active)) {
850 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800851 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 return NO_MORE_BUFFERS;
853 }
Eric Laurentbda74692009-11-04 08:27:26 -0800854 if (UNLIKELY(!waitCount)) {
855 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800857 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700858 if (!(cblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800859 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700860 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700861 cblk->lock.unlock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800862 mLock.lock();
863 if (mActive == 0) {
864 return status_t(STOPPED);
865 }
866 cblk->lock.lock();
867 }
868
869 if (cblk->flags & CBLK_INVALID_MSK) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700870 goto create_new_track;
871 }
Eric Laurenta553c252009-07-17 12:17:14 -0700872 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700873 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
875 // timing out when a loop has been set and we have already written upto loop end
876 // is a normal condition: no need to wake AudioFlinger up.
877 if (cblk->user < cblk->loopEnd) {
878 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
879 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700880 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800882 result = mAudioTrack->start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800884 if (result == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700885 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -0800886create_new_track:
887 result = restoreTrack_l(cblk, false);
888 }
889 if (result != NO_ERROR) {
890 LOGW("obtainBuffer create Track error %d", result);
891 cblk->lock.unlock();
892 return result;
893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
895 cblk->waitTimeMs = 0;
896 }
Eric Laurenta553c252009-07-17 12:17:14 -0700897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800899 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 return TIMED_OUT;
901 }
902 }
903 // read the server count again
904 start_loop_here:
905 framesAvail = cblk->framesAvailable_l();
906 }
Eric Laurentbda74692009-11-04 08:27:26 -0800907 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 }
909
Eric Laurent4712baa2010-09-30 16:12:31 -0700910 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent421ddc02011-03-07 14:52:59 -0800911 if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
Eric Laurentae29b762011-03-28 18:37:07 -0700912 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
913 LOGW("obtainBuffer() track %p disabled, restarting", this);
914 mAudioTrack->start();
Eric Laurent4712baa2010-09-30 16:12:31 -0700915 }
916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 if (framesReq > framesAvail) {
920 framesReq = framesAvail;
921 }
922
923 uint32_t u = cblk->user;
924 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
925
926 if (u + framesReq > bufferEnd) {
927 framesReq = bufferEnd - u;
928 }
929
Eric Laurenta553c252009-07-17 12:17:14 -0700930 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
931 audioBuffer->channelCount = mChannelCount;
932 audioBuffer->frameCount = framesReq;
933 audioBuffer->size = framesReq * cblk->frameSize;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700934 if (audio_is_linear_pcm(mFormat)) {
935 audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurenta553c252009-07-17 12:17:14 -0700936 } else {
937 audioBuffer->format = mFormat;
938 }
939 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 active = mActive;
941 return active ? status_t(NO_ERROR) : status_t(STOPPED);
942}
943
944void AudioTrack::releaseBuffer(Buffer* audioBuffer)
945{
Eric Laurent421ddc02011-03-07 14:52:59 -0800946 AutoMutex lock(mLock);
947 mCblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948}
949
950// -------------------------------------------------------------------------
951
952ssize_t AudioTrack::write(const void* buffer, size_t userSize)
953{
954
955 if (mSharedBuffer != 0) return INVALID_OPERATION;
956
957 if (ssize_t(userSize) < 0) {
958 // sanity-check. user is most-likely passing an error code.
959 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
960 buffer, userSize, userSize);
961 return BAD_VALUE;
962 }
963
964 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
965
Eric Laurent421ddc02011-03-07 14:52:59 -0800966 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
967 // while we are accessing the cblk
968 mLock.lock();
969 sp <IAudioTrack> audioTrack = mAudioTrack;
970 sp <IMemory> iMem = mCblkMemory;
971 mLock.unlock();
972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 ssize_t written = 0;
974 const int8_t *src = (const int8_t *)buffer;
975 Buffer audioBuffer;
Eric Laurent913af0b2011-03-17 09:36:51 -0700976 size_t frameSz = (size_t)frameSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977
978 do {
Eric Laurent913af0b2011-03-17 09:36:51 -0700979 audioBuffer.frameCount = userSize/frameSz;
Eric Laurenta553c252009-07-17 12:17:14 -0700980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 // Calling obtainBuffer() with a negative wait count causes
982 // an (almost) infinite wait time.
983 status_t err = obtainBuffer(&audioBuffer, -1);
984 if (err < 0) {
985 // out of buffers, return #bytes written
986 if (err == status_t(NO_MORE_BUFFERS))
987 break;
988 return ssize_t(err);
989 }
990
991 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700992
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700993 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 // Divide capacity by 2 to take expansion into account
995 toWrite = audioBuffer.size>>1;
996 // 8 to 16 bit conversion
997 int count = toWrite;
998 int16_t *dst = (int16_t *)(audioBuffer.i8);
999 while(count--) {
1000 *dst++ = (int16_t)(*src++^0x80) << 8;
1001 }
Eric Laurent28ad42b2009-08-04 10:42:26 -07001002 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 toWrite = audioBuffer.size;
1004 memcpy(audioBuffer.i8, src, toWrite);
1005 src += toWrite;
1006 }
1007 userSize -= toWrite;
1008 written += toWrite;
1009
1010 releaseBuffer(&audioBuffer);
Eric Laurent913af0b2011-03-17 09:36:51 -07001011 } while (userSize >= frameSz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012
1013 return written;
1014}
1015
1016// -------------------------------------------------------------------------
1017
1018bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1019{
1020 Buffer audioBuffer;
1021 uint32_t frames;
1022 size_t writtenSize;
1023
Eric Laurent421ddc02011-03-07 14:52:59 -08001024 mLock.lock();
1025 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1026 // while we are accessing the cblk
1027 sp <IAudioTrack> audioTrack = mAudioTrack;
1028 sp <IMemory> iMem = mCblkMemory;
1029 audio_track_cblk_t* cblk = mCblk;
1030 mLock.unlock();
1031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 // Manage underrun callback
Eric Laurentae29b762011-03-28 18:37:07 -07001033 if (mActive && (cblk->framesAvailable() == cblk->frameCount)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001034 LOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
Eric Laurentae29b762011-03-28 18:37:07 -07001035 if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 mCbf(EVENT_UNDERRUN, mUserData, 0);
Eric Laurent421ddc02011-03-07 14:52:59 -08001037 if (cblk->server == cblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001038 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 if (mSharedBuffer != 0) return false;
1041 }
1042 }
Eric Laurenta553c252009-07-17 12:17:14 -07001043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 // Manage loop end callback
Eric Laurent421ddc02011-03-07 14:52:59 -08001045 while (mLoopCount > cblk->loopCount) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 int loopCount = -1;
1047 mLoopCount--;
1048 if (mLoopCount >= 0) loopCount = mLoopCount;
1049
1050 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1051 }
1052
1053 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001054 if (!mMarkerReached && (mMarkerPosition > 0)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001055 if (cblk->server >= mMarkerPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001057 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
1059 }
1060
1061 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -07001062 if (mUpdatePeriod > 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001063 while (cblk->server >= mNewPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1065 mNewPosition += mUpdatePeriod;
1066 }
1067 }
1068
1069 // If Shared buffer is used, no data is requested from client.
1070 if (mSharedBuffer != 0) {
1071 frames = 0;
1072 } else {
1073 frames = mRemainingFrames;
1074 }
1075
1076 do {
1077
1078 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -07001079
1080 // Calling obtainBuffer() with a wait count of 1
1081 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1082 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 status_t err = obtainBuffer(&audioBuffer, 1);
1084 if (err < NO_ERROR) {
1085 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -07001086 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 -08001087 return false;
1088 }
1089 break;
1090 }
1091 if (err == status_t(STOPPED)) return false;
1092
1093 // Divide buffer size by 2 to take into account the expansion
1094 // due to 8 to 16 bit conversion: the callback must fill only half
1095 // of the destination buffer
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001096 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 audioBuffer.size >>= 1;
1098 }
1099
1100 size_t reqSize = audioBuffer.size;
1101 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1102 writtenSize = audioBuffer.size;
1103
1104 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001105 if (ssize_t(writtenSize) <= 0) {
1106 // The callback is done filling buffers
1107 // Keep this thread going to handle timed events and
1108 // still try to get more data in intervals of WAIT_PERIOD_MS
1109 // but don't just loop and block the CPU, so wait
1110 usleep(WAIT_PERIOD_MS*1000);
1111 break;
1112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 if (writtenSize > reqSize) writtenSize = reqSize;
1114
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001115 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 // 8 to 16 bit conversion
1117 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1118 int count = writtenSize;
1119 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1120 while(count--) {
1121 *dst-- = (int16_t)(*src--^0x80) << 8;
1122 }
1123 writtenSize <<= 1;
1124 }
1125
1126 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001127 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1128 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1129 // 16 bit.
1130 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 frames -= audioBuffer.frameCount;
1133
1134 releaseBuffer(&audioBuffer);
1135 }
1136 while (frames);
1137
1138 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001139 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 } else {
1141 mRemainingFrames = frames;
1142 }
1143 return true;
1144}
1145
Eric Laurent421ddc02011-03-07 14:52:59 -08001146// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1147// the IAudioTrack and IMemory in case they are recreated here.
1148// If the IAudioTrack is successfully restored, the cblk pointer is updated
1149status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1150{
1151 status_t result;
1152
Eric Laurentae29b762011-03-28 18:37:07 -07001153 if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001154 LOGW("dead IAudioTrack, creating a new one from %s",
1155 fromStart ? "start()" : "obtainBuffer()");
1156
Eric Laurent421ddc02011-03-07 14:52:59 -08001157 // signal old cblk condition so that other threads waiting for available buffers stop
1158 // waiting now
1159 cblk->cv.broadcast();
1160 cblk->lock.unlock();
1161
1162 // if the new IAudioTrack is created, createTrack_l() will modify the
1163 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1164 // It will also delete the strong references on previous IAudioTrack and IMemory
1165 result = createTrack_l(mStreamType,
1166 cblk->sampleRate,
1167 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001168 mChannelMask,
Eric Laurent421ddc02011-03-07 14:52:59 -08001169 mFrameCount,
1170 mFlags,
1171 mSharedBuffer,
1172 getOutput_l(),
1173 false);
1174
1175 if (result == NO_ERROR) {
Eric Laurent6667ac32011-03-21 11:49:00 -07001176 // restore write index and set other indexes to reflect empty buffer status
1177 mCblk->user = cblk->user;
1178 mCblk->server = cblk->user;
1179 mCblk->userBase = cblk->user;
1180 mCblk->serverBase = cblk->user;
1181 // restore loop: this is not guaranteed to succeed if new frame count is not
1182 // compatible with loop length
1183 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
Eric Laurent421ddc02011-03-07 14:52:59 -08001184 if (!fromStart) {
1185 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1186 }
Eric Laurent6667ac32011-03-21 11:49:00 -07001187 if (mActive) {
1188 result = mAudioTrack->start();
1189 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001190 if (fromStart && result == NO_ERROR) {
1191 mNewPosition = mCblk->server + mUpdatePeriod;
1192 }
1193 }
1194 if (result != NO_ERROR) {
1195 mActive = false;
1196 }
1197
1198 // signal old cblk condition for other threads waiting for restore completion
Eric Laurentae29b762011-03-28 18:37:07 -07001199 android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -08001200 cblk->cv.broadcast();
Eric Laurent421ddc02011-03-07 14:52:59 -08001201 } else {
1202 if (!(cblk->flags & CBLK_RESTORED_MSK)) {
1203 LOGW("dead IAudioTrack, waiting for a new one");
1204 mLock.unlock();
1205 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
1206 cblk->lock.unlock();
1207 mLock.lock();
1208 } else {
1209 LOGW("dead IAudioTrack, already restored");
1210 result = NO_ERROR;
1211 cblk->lock.unlock();
1212 }
1213 if (result != NO_ERROR || mActive == 0) {
1214 result = status_t(STOPPED);
1215 }
1216 }
1217 LOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1218 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1219
1220 if (result == NO_ERROR) {
1221 // from now on we switch to the newly created cblk
1222 cblk = mCblk;
1223 }
1224 cblk->lock.lock();
1225
1226 LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d", result);
1227
1228 return result;
1229}
1230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1232{
1233
1234 const size_t SIZE = 256;
1235 char buffer[SIZE];
1236 String8 result;
1237
1238 result.append(" AudioTrack::dump\n");
1239 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1240 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001241 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 -08001242 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001243 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 -08001244 result.append(buffer);
1245 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1246 result.append(buffer);
1247 ::write(fd, result.string(), result.size());
1248 return NO_ERROR;
1249}
1250
1251// =========================================================================
1252
1253AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1254 : Thread(bCanCallJava), mReceiver(receiver)
1255{
1256}
1257
1258bool AudioTrack::AudioTrackThread::threadLoop()
1259{
1260 return mReceiver.processAudioBuffer(this);
1261}
1262
1263status_t AudioTrack::AudioTrackThread::readyToRun()
1264{
1265 return NO_ERROR;
1266}
1267
1268void AudioTrack::AudioTrackThread::onFirstRef()
1269{
1270}
1271
1272// =========================================================================
1273
Eric Laurentae29b762011-03-28 18:37:07 -07001274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001276 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1277 userBase(0), serverBase(0), buffers(0), frameCount(0),
1278 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurentae29b762011-03-28 18:37:07 -07001279 sendLevel(0), flags(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280{
1281}
1282
1283uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1284{
1285 uint32_t u = this->user;
1286
1287 u += frameCount;
1288 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001289 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1291 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1292 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1293 }
1294 } else if (u > this->server) {
1295 LOGW("stepServer occured after track reset");
1296 u = this->server;
1297 }
1298
1299 if (u >= userBase + this->frameCount) {
1300 userBase += this->frameCount;
1301 }
1302
1303 this->user = u;
1304
1305 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurent913af0b2011-03-17 09:36:51 -07001306 if (flags & CBLK_UNDERRUN_MSK) {
Eric Laurentae29b762011-03-28 18:37:07 -07001307 android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
Eric Laurent913af0b2011-03-17 09:36:51 -07001308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309
1310 return u;
1311}
1312
1313bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1314{
Eric Laurentae29b762011-03-28 18:37:07 -07001315 if (!tryLock()) {
1316 LOGW("stepServer() could not lock cblk");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 return false;
1318 }
1319
1320 uint32_t s = this->server;
1321
1322 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001323 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 // Mark that we have read the first buffer so that next time stepUser() is called
1325 // we switch to normal obtainBuffer() timeout period
1326 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001327 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 // It is possible that we receive a flush()
1330 // while the mixer is processing a block: in this case,
1331 // stepServer() is called After the flush() has reset u & s and
1332 // we have s > u
1333 if (s > this->user) {
1334 LOGW("stepServer occured after track reset");
1335 s = this->user;
1336 }
1337 }
1338
1339 if (s >= loopEnd) {
1340 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1341 s = loopStart;
1342 if (--loopCount == 0) {
1343 loopEnd = UINT_MAX;
1344 loopStart = UINT_MAX;
1345 }
1346 }
1347 if (s >= serverBase + this->frameCount) {
1348 serverBase += this->frameCount;
1349 }
1350
1351 this->server = s;
1352
Eric Laurent421ddc02011-03-07 14:52:59 -08001353 if (!(flags & CBLK_INVALID_MSK)) {
1354 cv.signal();
1355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 lock.unlock();
1357 return true;
1358}
1359
1360void* audio_track_cblk_t::buffer(uint32_t offset) const
1361{
Eric Laurenta553c252009-07-17 12:17:14 -07001362 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363}
1364
1365uint32_t audio_track_cblk_t::framesAvailable()
1366{
1367 Mutex::Autolock _l(lock);
1368 return framesAvailable_l();
1369}
1370
1371uint32_t audio_track_cblk_t::framesAvailable_l()
1372{
1373 uint32_t u = this->user;
1374 uint32_t s = this->server;
1375
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001376 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 uint32_t limit = (s < loopStart) ? s : loopStart;
1378 return limit + frameCount - u;
1379 } else {
1380 return frameCount + u - s;
1381 }
1382}
1383
1384uint32_t audio_track_cblk_t::framesReady()
1385{
1386 uint32_t u = this->user;
1387 uint32_t s = this->server;
1388
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001389 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 if (u < loopEnd) {
1391 return u - s;
1392 } else {
Eric Laurentae29b762011-03-28 18:37:07 -07001393 // do not block on mutex shared with client on AudioFlinger side
1394 if (!tryLock()) {
1395 LOGW("framesReady() could not lock cblk");
1396 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 }
Eric Laurentae29b762011-03-28 18:37:07 -07001398 uint32_t frames = UINT_MAX;
1399 if (loopCount >= 0) {
1400 frames = (loopEnd - loopStart)*loopCount + u - s;
1401 }
1402 lock.unlock();
1403 return frames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405 } else {
1406 return s - u;
1407 }
1408}
1409
Eric Laurentae29b762011-03-28 18:37:07 -07001410bool audio_track_cblk_t::tryLock()
1411{
1412 // the code below simulates lock-with-timeout
1413 // we MUST do this to protect the AudioFlinger server
1414 // as this lock is shared with the client.
1415 status_t err;
1416
1417 err = lock.tryLock();
1418 if (err == -EBUSY) { // just wait a bit
1419 usleep(1000);
1420 err = lock.tryLock();
1421 }
1422 if (err != NO_ERROR) {
1423 // probably, the client just died.
1424 return false;
1425 }
1426 return true;
1427}
1428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429// -------------------------------------------------------------------------
1430
1431}; // namespace android
1432