blob: 7520ed92349e868e1fa08a30e91fe763de566166 [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,
Eric Laurenta553c252009-07-17 12:17:14 -070090 int channels,
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{
Eric Laurenta553c252009-07-17 12:17:14 -070099 mStatus = set(streamType, sampleRate, format, channels,
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,
Eric Laurenta553c252009-07-17 12:17:14 -0700108 int channels,
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{
Eric Laurenta553c252009-07-17 12:17:14 -0700117 mStatus = set(streamType, sampleRate, format, channels,
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,
Eric Laurenta553c252009-07-17 12:17:14 -0700144 int channels,
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 }
Eric Laurenta553c252009-07-17 12:17:14 -0700183 if (channels == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700184 channels = 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
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700198 if (!audio_is_output_channel(channels)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700199 LOGE("Invalid channel mask");
200 return BAD_VALUE;
201 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700202 uint32_t channelCount = popcount(channels);
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,
206 sampleRate,format, channels,
207 (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,
225 format,
226 channelCount,
227 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;
248 mFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -0700249 mChannels = channels;
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) {
345 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
346 } else {
347 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
348 }
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,
684 mCblk->sampleRate, mFormat, mChannels, (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,
708 int format,
709 int channelCount,
710 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
770 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
771 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
772 return BAD_VALUE;
773 }
774 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
775 }
776 }
777
Eric Laurentbda74692009-11-04 08:27:26 -0800778 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
779 streamType,
780 sampleRate,
781 format,
782 channelCount,
783 frameCount,
784 ((uint16_t)flags) << 16,
785 sharedBuffer,
786 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700787 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800788 &status);
789
790 if (track == 0) {
791 LOGE("AudioFlinger could not create track, status: %d", status);
792 return status;
793 }
794 sp<IMemory> cblk = track->getCblk();
795 if (cblk == 0) {
796 LOGE("Could not get control block");
797 return NO_INIT;
798 }
799 mAudioTrack.clear();
800 mAudioTrack = track;
801 mCblkMemory.clear();
802 mCblkMemory = cblk;
803 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurentae29b762011-03-28 18:37:07 -0700804 android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
Eric Laurentbda74692009-11-04 08:27:26 -0800805 if (sharedBuffer == 0) {
806 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
807 } else {
808 mCblk->buffers = sharedBuffer->pointer();
809 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700810 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800811 }
812
Eric Laurent65b65452010-06-01 23:49:17 -0700813 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
814 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent7070b362010-07-16 07:43:46 -0700815 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent49f02be2009-11-19 09:00:56 -0800816 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
817 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700818 mRemainingFrames = mNotificationFramesAct;
819 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800820 return NO_ERROR;
821}
822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
824{
Eric Laurent421ddc02011-03-07 14:52:59 -0800825 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 status_t result;
828 audio_track_cblk_t* cblk = mCblk;
829 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700830 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831
832 audioBuffer->frameCount = 0;
833 audioBuffer->size = 0;
834
835 uint32_t framesAvail = cblk->framesAvailable();
836
Eric Laurent6667ac32011-03-21 11:49:00 -0700837 cblk->lock.lock();
838 if (cblk->flags & CBLK_INVALID_MSK) {
839 goto create_new_track;
840 }
841 cblk->lock.unlock();
842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800844 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 goto start_loop_here;
846 while (framesAvail == 0) {
847 active = mActive;
848 if (UNLIKELY(!active)) {
849 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800850 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 return NO_MORE_BUFFERS;
852 }
Eric Laurentbda74692009-11-04 08:27:26 -0800853 if (UNLIKELY(!waitCount)) {
854 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800856 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700857 if (!(cblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800858 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700859 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700860 cblk->lock.unlock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800861 mLock.lock();
862 if (mActive == 0) {
863 return status_t(STOPPED);
864 }
865 cblk->lock.lock();
866 }
867
868 if (cblk->flags & CBLK_INVALID_MSK) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700869 goto create_new_track;
870 }
Eric Laurenta553c252009-07-17 12:17:14 -0700871 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700872 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
874 // timing out when a loop has been set and we have already written upto loop end
875 // is a normal condition: no need to wake AudioFlinger up.
876 if (cblk->user < cblk->loopEnd) {
877 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
878 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700879 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800881 result = mAudioTrack->start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800883 if (result == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700884 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -0800885create_new_track:
886 result = restoreTrack_l(cblk, false);
887 }
888 if (result != NO_ERROR) {
889 LOGW("obtainBuffer create Track error %d", result);
890 cblk->lock.unlock();
891 return result;
892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
894 cblk->waitTimeMs = 0;
895 }
Eric Laurenta553c252009-07-17 12:17:14 -0700896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800898 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 return TIMED_OUT;
900 }
901 }
902 // read the server count again
903 start_loop_here:
904 framesAvail = cblk->framesAvailable_l();
905 }
Eric Laurentbda74692009-11-04 08:27:26 -0800906 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
908
Eric Laurent4712baa2010-09-30 16:12:31 -0700909 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent421ddc02011-03-07 14:52:59 -0800910 if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
Eric Laurentae29b762011-03-28 18:37:07 -0700911 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
912 LOGW("obtainBuffer() track %p disabled, restarting", this);
913 mAudioTrack->start();
Eric Laurent4712baa2010-09-30 16:12:31 -0700914 }
915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 if (framesReq > framesAvail) {
919 framesReq = framesAvail;
920 }
921
922 uint32_t u = cblk->user;
923 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
924
925 if (u + framesReq > bufferEnd) {
926 framesReq = bufferEnd - u;
927 }
928
Eric Laurenta553c252009-07-17 12:17:14 -0700929 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
930 audioBuffer->channelCount = mChannelCount;
931 audioBuffer->frameCount = framesReq;
932 audioBuffer->size = framesReq * cblk->frameSize;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700933 if (audio_is_linear_pcm(mFormat)) {
934 audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurenta553c252009-07-17 12:17:14 -0700935 } else {
936 audioBuffer->format = mFormat;
937 }
938 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 active = mActive;
940 return active ? status_t(NO_ERROR) : status_t(STOPPED);
941}
942
943void AudioTrack::releaseBuffer(Buffer* audioBuffer)
944{
Eric Laurent421ddc02011-03-07 14:52:59 -0800945 AutoMutex lock(mLock);
946 mCblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947}
948
949// -------------------------------------------------------------------------
950
951ssize_t AudioTrack::write(const void* buffer, size_t userSize)
952{
953
954 if (mSharedBuffer != 0) return INVALID_OPERATION;
955
956 if (ssize_t(userSize) < 0) {
957 // sanity-check. user is most-likely passing an error code.
958 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
959 buffer, userSize, userSize);
960 return BAD_VALUE;
961 }
962
963 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
964
Eric Laurent421ddc02011-03-07 14:52:59 -0800965 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
966 // while we are accessing the cblk
967 mLock.lock();
968 sp <IAudioTrack> audioTrack = mAudioTrack;
969 sp <IMemory> iMem = mCblkMemory;
970 mLock.unlock();
971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 ssize_t written = 0;
973 const int8_t *src = (const int8_t *)buffer;
974 Buffer audioBuffer;
Eric Laurent913af0b2011-03-17 09:36:51 -0700975 size_t frameSz = (size_t)frameSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976
977 do {
Eric Laurent913af0b2011-03-17 09:36:51 -0700978 audioBuffer.frameCount = userSize/frameSz;
Eric Laurenta553c252009-07-17 12:17:14 -0700979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 // Calling obtainBuffer() with a negative wait count causes
981 // an (almost) infinite wait time.
982 status_t err = obtainBuffer(&audioBuffer, -1);
983 if (err < 0) {
984 // out of buffers, return #bytes written
985 if (err == status_t(NO_MORE_BUFFERS))
986 break;
987 return ssize_t(err);
988 }
989
990 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700991
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700992 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 // Divide capacity by 2 to take expansion into account
994 toWrite = audioBuffer.size>>1;
995 // 8 to 16 bit conversion
996 int count = toWrite;
997 int16_t *dst = (int16_t *)(audioBuffer.i8);
998 while(count--) {
999 *dst++ = (int16_t)(*src++^0x80) << 8;
1000 }
Eric Laurent28ad42b2009-08-04 10:42:26 -07001001 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 toWrite = audioBuffer.size;
1003 memcpy(audioBuffer.i8, src, toWrite);
1004 src += toWrite;
1005 }
1006 userSize -= toWrite;
1007 written += toWrite;
1008
1009 releaseBuffer(&audioBuffer);
Eric Laurent913af0b2011-03-17 09:36:51 -07001010 } while (userSize >= frameSz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011
1012 return written;
1013}
1014
1015// -------------------------------------------------------------------------
1016
1017bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1018{
1019 Buffer audioBuffer;
1020 uint32_t frames;
1021 size_t writtenSize;
1022
Eric Laurent421ddc02011-03-07 14:52:59 -08001023 mLock.lock();
1024 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1025 // while we are accessing the cblk
1026 sp <IAudioTrack> audioTrack = mAudioTrack;
1027 sp <IMemory> iMem = mCblkMemory;
1028 audio_track_cblk_t* cblk = mCblk;
1029 mLock.unlock();
1030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 // Manage underrun callback
Eric Laurentae29b762011-03-28 18:37:07 -07001032 if (mActive && (cblk->framesAvailable() == cblk->frameCount)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001033 LOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
Eric Laurentae29b762011-03-28 18:37:07 -07001034 if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 mCbf(EVENT_UNDERRUN, mUserData, 0);
Eric Laurent421ddc02011-03-07 14:52:59 -08001036 if (cblk->server == cblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001037 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 if (mSharedBuffer != 0) return false;
1040 }
1041 }
Eric Laurenta553c252009-07-17 12:17:14 -07001042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 // Manage loop end callback
Eric Laurent421ddc02011-03-07 14:52:59 -08001044 while (mLoopCount > cblk->loopCount) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 int loopCount = -1;
1046 mLoopCount--;
1047 if (mLoopCount >= 0) loopCount = mLoopCount;
1048
1049 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1050 }
1051
1052 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001053 if (!mMarkerReached && (mMarkerPosition > 0)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001054 if (cblk->server >= mMarkerPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001056 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058 }
1059
1060 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -07001061 if (mUpdatePeriod > 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001062 while (cblk->server >= mNewPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1064 mNewPosition += mUpdatePeriod;
1065 }
1066 }
1067
1068 // If Shared buffer is used, no data is requested from client.
1069 if (mSharedBuffer != 0) {
1070 frames = 0;
1071 } else {
1072 frames = mRemainingFrames;
1073 }
1074
1075 do {
1076
1077 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -07001078
1079 // Calling obtainBuffer() with a wait count of 1
1080 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1081 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 status_t err = obtainBuffer(&audioBuffer, 1);
1083 if (err < NO_ERROR) {
1084 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -07001085 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 -08001086 return false;
1087 }
1088 break;
1089 }
1090 if (err == status_t(STOPPED)) return false;
1091
1092 // Divide buffer size by 2 to take into account the expansion
1093 // due to 8 to 16 bit conversion: the callback must fill only half
1094 // of the destination buffer
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001095 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 audioBuffer.size >>= 1;
1097 }
1098
1099 size_t reqSize = audioBuffer.size;
1100 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1101 writtenSize = audioBuffer.size;
1102
1103 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001104 if (ssize_t(writtenSize) <= 0) {
1105 // The callback is done filling buffers
1106 // Keep this thread going to handle timed events and
1107 // still try to get more data in intervals of WAIT_PERIOD_MS
1108 // but don't just loop and block the CPU, so wait
1109 usleep(WAIT_PERIOD_MS*1000);
1110 break;
1111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 if (writtenSize > reqSize) writtenSize = reqSize;
1113
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001114 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 // 8 to 16 bit conversion
1116 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1117 int count = writtenSize;
1118 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1119 while(count--) {
1120 *dst-- = (int16_t)(*src--^0x80) << 8;
1121 }
1122 writtenSize <<= 1;
1123 }
1124
1125 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001126 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1127 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1128 // 16 bit.
1129 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 frames -= audioBuffer.frameCount;
1132
1133 releaseBuffer(&audioBuffer);
1134 }
1135 while (frames);
1136
1137 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001138 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 } else {
1140 mRemainingFrames = frames;
1141 }
1142 return true;
1143}
1144
Eric Laurent421ddc02011-03-07 14:52:59 -08001145// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1146// the IAudioTrack and IMemory in case they are recreated here.
1147// If the IAudioTrack is successfully restored, the cblk pointer is updated
1148status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1149{
1150 status_t result;
1151
Eric Laurentae29b762011-03-28 18:37:07 -07001152 if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001153 LOGW("dead IAudioTrack, creating a new one from %s",
1154 fromStart ? "start()" : "obtainBuffer()");
1155
Eric Laurent421ddc02011-03-07 14:52:59 -08001156 // signal old cblk condition so that other threads waiting for available buffers stop
1157 // waiting now
1158 cblk->cv.broadcast();
1159 cblk->lock.unlock();
1160
1161 // if the new IAudioTrack is created, createTrack_l() will modify the
1162 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1163 // It will also delete the strong references on previous IAudioTrack and IMemory
1164 result = createTrack_l(mStreamType,
1165 cblk->sampleRate,
1166 mFormat,
1167 mChannelCount,
1168 mFrameCount,
1169 mFlags,
1170 mSharedBuffer,
1171 getOutput_l(),
1172 false);
1173
1174 if (result == NO_ERROR) {
Eric Laurent6667ac32011-03-21 11:49:00 -07001175 // restore write index and set other indexes to reflect empty buffer status
1176 mCblk->user = cblk->user;
1177 mCblk->server = cblk->user;
1178 mCblk->userBase = cblk->user;
1179 mCblk->serverBase = cblk->user;
1180 // restore loop: this is not guaranteed to succeed if new frame count is not
1181 // compatible with loop length
1182 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
Eric Laurent421ddc02011-03-07 14:52:59 -08001183 if (!fromStart) {
1184 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1185 }
Eric Laurent6667ac32011-03-21 11:49:00 -07001186 if (mActive) {
1187 result = mAudioTrack->start();
1188 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001189 if (fromStart && result == NO_ERROR) {
1190 mNewPosition = mCblk->server + mUpdatePeriod;
1191 }
1192 }
1193 if (result != NO_ERROR) {
1194 mActive = false;
1195 }
1196
1197 // signal old cblk condition for other threads waiting for restore completion
Eric Laurentae29b762011-03-28 18:37:07 -07001198 android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -08001199 cblk->cv.broadcast();
Eric Laurent421ddc02011-03-07 14:52:59 -08001200 } else {
1201 if (!(cblk->flags & CBLK_RESTORED_MSK)) {
1202 LOGW("dead IAudioTrack, waiting for a new one");
1203 mLock.unlock();
1204 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
1205 cblk->lock.unlock();
1206 mLock.lock();
1207 } else {
1208 LOGW("dead IAudioTrack, already restored");
1209 result = NO_ERROR;
1210 cblk->lock.unlock();
1211 }
1212 if (result != NO_ERROR || mActive == 0) {
1213 result = status_t(STOPPED);
1214 }
1215 }
1216 LOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1217 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1218
1219 if (result == NO_ERROR) {
1220 // from now on we switch to the newly created cblk
1221 cblk = mCblk;
1222 }
1223 cblk->lock.lock();
1224
1225 LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d", result);
1226
1227 return result;
1228}
1229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1231{
1232
1233 const size_t SIZE = 256;
1234 char buffer[SIZE];
1235 String8 result;
1236
1237 result.append(" AudioTrack::dump\n");
1238 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1239 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001240 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 -08001241 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001242 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 -08001243 result.append(buffer);
1244 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1245 result.append(buffer);
1246 ::write(fd, result.string(), result.size());
1247 return NO_ERROR;
1248}
1249
1250// =========================================================================
1251
1252AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1253 : Thread(bCanCallJava), mReceiver(receiver)
1254{
1255}
1256
1257bool AudioTrack::AudioTrackThread::threadLoop()
1258{
1259 return mReceiver.processAudioBuffer(this);
1260}
1261
1262status_t AudioTrack::AudioTrackThread::readyToRun()
1263{
1264 return NO_ERROR;
1265}
1266
1267void AudioTrack::AudioTrackThread::onFirstRef()
1268{
1269}
1270
1271// =========================================================================
1272
Eric Laurentae29b762011-03-28 18:37:07 -07001273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001275 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1276 userBase(0), serverBase(0), buffers(0), frameCount(0),
1277 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurentae29b762011-03-28 18:37:07 -07001278 sendLevel(0), flags(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279{
1280}
1281
1282uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1283{
1284 uint32_t u = this->user;
1285
1286 u += frameCount;
1287 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001288 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1290 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1291 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1292 }
1293 } else if (u > this->server) {
1294 LOGW("stepServer occured after track reset");
1295 u = this->server;
1296 }
1297
1298 if (u >= userBase + this->frameCount) {
1299 userBase += this->frameCount;
1300 }
1301
1302 this->user = u;
1303
1304 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurent913af0b2011-03-17 09:36:51 -07001305 if (flags & CBLK_UNDERRUN_MSK) {
Eric Laurentae29b762011-03-28 18:37:07 -07001306 android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
Eric Laurent913af0b2011-03-17 09:36:51 -07001307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308
1309 return u;
1310}
1311
1312bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1313{
Eric Laurentae29b762011-03-28 18:37:07 -07001314 if (!tryLock()) {
1315 LOGW("stepServer() could not lock cblk");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 return false;
1317 }
1318
1319 uint32_t s = this->server;
1320
1321 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001322 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 // Mark that we have read the first buffer so that next time stepUser() is called
1324 // we switch to normal obtainBuffer() timeout period
1325 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001326 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 // It is possible that we receive a flush()
1329 // while the mixer is processing a block: in this case,
1330 // stepServer() is called After the flush() has reset u & s and
1331 // we have s > u
1332 if (s > this->user) {
1333 LOGW("stepServer occured after track reset");
1334 s = this->user;
1335 }
1336 }
1337
1338 if (s >= loopEnd) {
1339 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1340 s = loopStart;
1341 if (--loopCount == 0) {
1342 loopEnd = UINT_MAX;
1343 loopStart = UINT_MAX;
1344 }
1345 }
1346 if (s >= serverBase + this->frameCount) {
1347 serverBase += this->frameCount;
1348 }
1349
1350 this->server = s;
1351
Eric Laurent421ddc02011-03-07 14:52:59 -08001352 if (!(flags & CBLK_INVALID_MSK)) {
1353 cv.signal();
1354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 lock.unlock();
1356 return true;
1357}
1358
1359void* audio_track_cblk_t::buffer(uint32_t offset) const
1360{
Eric Laurenta553c252009-07-17 12:17:14 -07001361 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362}
1363
1364uint32_t audio_track_cblk_t::framesAvailable()
1365{
1366 Mutex::Autolock _l(lock);
1367 return framesAvailable_l();
1368}
1369
1370uint32_t audio_track_cblk_t::framesAvailable_l()
1371{
1372 uint32_t u = this->user;
1373 uint32_t s = this->server;
1374
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001375 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 uint32_t limit = (s < loopStart) ? s : loopStart;
1377 return limit + frameCount - u;
1378 } else {
1379 return frameCount + u - s;
1380 }
1381}
1382
1383uint32_t audio_track_cblk_t::framesReady()
1384{
1385 uint32_t u = this->user;
1386 uint32_t s = this->server;
1387
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001388 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 if (u < loopEnd) {
1390 return u - s;
1391 } else {
Eric Laurentae29b762011-03-28 18:37:07 -07001392 // do not block on mutex shared with client on AudioFlinger side
1393 if (!tryLock()) {
1394 LOGW("framesReady() could not lock cblk");
1395 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
Eric Laurentae29b762011-03-28 18:37:07 -07001397 uint32_t frames = UINT_MAX;
1398 if (loopCount >= 0) {
1399 frames = (loopEnd - loopStart)*loopCount + u - s;
1400 }
1401 lock.unlock();
1402 return frames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404 } else {
1405 return s - u;
1406 }
1407}
1408
Eric Laurentae29b762011-03-28 18:37:07 -07001409bool audio_track_cblk_t::tryLock()
1410{
1411 // the code below simulates lock-with-timeout
1412 // we MUST do this to protect the AudioFlinger server
1413 // as this lock is shared with the client.
1414 status_t err;
1415
1416 err = lock.tryLock();
1417 if (err == -EBUSY) { // just wait a bit
1418 usleep(1000);
1419 err = lock.tryLock();
1420 }
1421 if (err != NO_ERROR) {
1422 // probably, the client just died.
1423 return false;
1424 }
1425 return true;
1426}
1427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428// -------------------------------------------------------------------------
1429
1430}; // namespace android
1431