blob: 66e11d282d72af17e8a39511b63595f41cf9daf6 [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
40#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
41#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
42
43namespace android {
Chia-chi Yehbd240c22010-06-16 06:33:13 +080044// ---------------------------------------------------------------------------
45
46// static
47status_t AudioTrack::getMinFrameCount(
48 int* frameCount,
49 int streamType,
50 uint32_t sampleRate)
51{
52 int afSampleRate;
53 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
54 return NO_INIT;
55 }
56 int afFrameCount;
57 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
58 return NO_INIT;
59 }
60 uint32_t afLatency;
61 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
62 return NO_INIT;
63 }
64
65 // Ensure that buffer depth covers at least audio hardware latency
66 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
67 if (minBufCount < 2) minBufCount = 2;
68
69 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
70 afFrameCount * minBufCount * sampleRate / afSampleRate;
71 return NO_ERROR;
72}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
74// ---------------------------------------------------------------------------
75
76AudioTrack::AudioTrack()
77 : mStatus(NO_INIT)
78{
79}
80
81AudioTrack::AudioTrack(
82 int streamType,
83 uint32_t sampleRate,
84 int format,
Eric Laurenta553c252009-07-17 12:17:14 -070085 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 int frameCount,
87 uint32_t flags,
88 callback_t cbf,
89 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -070090 int notificationFrames,
91 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 : mStatus(NO_INIT)
93{
Eric Laurenta553c252009-07-17 12:17:14 -070094 mStatus = set(streamType, sampleRate, format, channels,
Eric Laurent619346f2010-06-21 09:27:30 -070095 frameCount, flags, cbf, user, notificationFrames,
96 0, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097}
98
99AudioTrack::AudioTrack(
100 int streamType,
101 uint32_t sampleRate,
102 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700103 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 const sp<IMemory>& sharedBuffer,
105 uint32_t flags,
106 callback_t cbf,
107 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -0700108 int notificationFrames,
109 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 : mStatus(NO_INIT)
111{
Eric Laurenta553c252009-07-17 12:17:14 -0700112 mStatus = set(streamType, sampleRate, format, channels,
Eric Laurent619346f2010-06-21 09:27:30 -0700113 0, flags, cbf, user, notificationFrames,
114 sharedBuffer, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115}
116
117AudioTrack::~AudioTrack()
118{
119 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
120
121 if (mStatus == NO_ERROR) {
122 // Make sure that callback function exits in the case where
123 // it is looping on buffer full condition in obtainBuffer().
124 // Otherwise the callback thread will never exit.
125 stop();
126 if (mAudioTrackThread != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 mAudioTrackThread->requestExitAndWait();
128 mAudioTrackThread.clear();
129 }
130 mAudioTrack.clear();
131 IPCThreadState::self()->flushCommands();
132 }
133}
134
135status_t AudioTrack::set(
136 int streamType,
137 uint32_t sampleRate,
138 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700139 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 int frameCount,
141 uint32_t flags,
142 callback_t cbf,
143 void* user,
144 int notificationFrames,
145 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -0700146 bool threadCanCallJava,
147 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148{
149
150 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
151
Eric Laurent421ddc02011-03-07 14:52:59 -0800152 AutoMutex lock(mLock);
Eric Laurentef028272009-04-21 07:56:33 -0700153 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 LOGE("Track already in use");
155 return INVALID_OPERATION;
156 }
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 int afSampleRate;
159 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
160 return NO_INIT;
161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 uint32_t afLatency;
163 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
164 return NO_INIT;
165 }
166
167 // handle default values first.
168 if (streamType == AudioSystem::DEFAULT) {
169 streamType = AudioSystem::MUSIC;
170 }
171 if (sampleRate == 0) {
172 sampleRate = afSampleRate;
173 }
174 // these below should probably come from the audioFlinger too...
175 if (format == 0) {
176 format = AudioSystem::PCM_16_BIT;
177 }
Eric Laurenta553c252009-07-17 12:17:14 -0700178 if (channels == 0) {
179 channels = AudioSystem::CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 }
181
182 // validate parameters
Eric Laurenta553c252009-07-17 12:17:14 -0700183 if (!AudioSystem::isValidFormat(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 LOGE("Invalid format");
185 return BAD_VALUE;
186 }
Eric Laurenta553c252009-07-17 12:17:14 -0700187
188 // force direct flag if format is not linear PCM
189 if (!AudioSystem::isLinearPCM(format)) {
190 flags |= AudioSystem::OUTPUT_FLAG_DIRECT;
191 }
192
193 if (!AudioSystem::isOutputChannel(channels)) {
194 LOGE("Invalid channel mask");
195 return BAD_VALUE;
196 }
197 uint32_t channelCount = AudioSystem::popCount(channels);
198
199 audio_io_handle_t output = AudioSystem::getOutput((AudioSystem::stream_type)streamType,
200 sampleRate, format, channels, (AudioSystem::output_flags)flags);
201
202 if (output == 0) {
203 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 return BAD_VALUE;
205 }
206
Eric Laurentbda74692009-11-04 08:27:26 -0800207 mVolume[LEFT] = 1.0f;
208 mVolume[RIGHT] = 1.0f;
Eric Laurent65b65452010-06-01 23:49:17 -0700209 mSendLevel = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700210 mFrameCount = frameCount;
211 mNotificationFramesReq = notificationFrames;
Eric Laurent65b65452010-06-01 23:49:17 -0700212 mSessionId = sessionId;
Eric Laurent7070b362010-07-16 07:43:46 -0700213 mAuxEffectId = 0;
Eric Laurent65b65452010-06-01 23:49:17 -0700214
Eric Laurentbda74692009-11-04 08:27:26 -0800215 // create the IAudioTrack
Eric Laurent421ddc02011-03-07 14:52:59 -0800216 status_t status = createTrack_l(streamType,
217 sampleRate,
218 format,
219 channelCount,
220 frameCount,
221 flags,
222 sharedBuffer,
223 output,
224 true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225
Eric Laurentbda74692009-11-04 08:27:26 -0800226 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 return status;
228 }
Eric Laurentbda74692009-11-04 08:27:26 -0800229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 if (cbf != 0) {
231 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
232 if (mAudioTrackThread == 0) {
233 LOGE("Could not create callback thread");
234 return NO_INIT;
235 }
236 }
237
238 mStatus = NO_ERROR;
239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 mStreamType = streamType;
241 mFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -0700242 mChannels = channels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 mChannelCount = channelCount;
244 mSharedBuffer = sharedBuffer;
245 mMuted = false;
246 mActive = 0;
247 mCbf = cbf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 mUserData = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 mLoopCount = 0;
250 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700251 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 mNewPosition = 0;
253 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700254 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
256 return NO_ERROR;
257}
258
259status_t AudioTrack::initCheck() const
260{
261 return mStatus;
262}
263
264// -------------------------------------------------------------------------
265
266uint32_t AudioTrack::latency() const
267{
268 return mLatency;
269}
270
271int AudioTrack::streamType() const
272{
273 return mStreamType;
274}
275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276int AudioTrack::format() const
277{
278 return mFormat;
279}
280
281int AudioTrack::channelCount() const
282{
283 return mChannelCount;
284}
285
286uint32_t AudioTrack::frameCount() const
287{
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700288 return mCblk->frameCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289}
290
291int AudioTrack::frameSize() const
292{
Eric Laurenta553c252009-07-17 12:17:14 -0700293 if (AudioSystem::isLinearPCM(mFormat)) {
294 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
295 } else {
296 return sizeof(uint8_t);
297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298}
299
300sp<IMemory>& AudioTrack::sharedBuffer()
301{
302 return mSharedBuffer;
303}
304
305// -------------------------------------------------------------------------
306
307void AudioTrack::start()
308{
309 sp<AudioTrackThread> t = mAudioTrackThread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700310 status_t status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311
312 LOGV("start %p", this);
313 if (t != 0) {
314 if (t->exitPending()) {
315 if (t->requestExitAndWait() == WOULD_BLOCK) {
316 LOGE("AudioTrack::start called from thread");
317 return;
318 }
319 }
320 t->mLock.lock();
321 }
322
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800323 AutoMutex lock(mLock);
Eric Laurent421ddc02011-03-07 14:52:59 -0800324 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
325 // while we are accessing the cblk
326 sp <IAudioTrack> audioTrack = mAudioTrack;
327 sp <IMemory> iMem = mCblkMemory;
328 audio_track_cblk_t* cblk = mCblk;
329
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800330 if (mActive == 0) {
331 mActive = 1;
Eric Laurent421ddc02011-03-07 14:52:59 -0800332 mNewPosition = cblk->server + mUpdatePeriod;
Eric Laurent913af0b2011-03-17 09:36:51 -0700333 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800334 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
335 cblk->waitTimeMs = 0;
Eric Laurentae29b762011-03-28 18:37:07 -0700336 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -0800337 if (t != 0) {
338 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
339 } else {
340 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
341 }
342
Eric Laurent421ddc02011-03-07 14:52:59 -0800343 LOGV("start %p before lock cblk %p", this, mCblk);
Eric Laurent421ddc02011-03-07 14:52:59 -0800344 if (!(cblk->flags & CBLK_INVALID_MSK)) {
345 cblk->lock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700346 status = mAudioTrack->start();
Eric Laurent421ddc02011-03-07 14:52:59 -0800347 cblk->lock.lock();
348 if (status == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700349 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent49f02be2009-11-19 09:00:56 -0800350 }
Eric Laurent059b4be2009-11-09 23:32:22 -0800351 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800352 if (cblk->flags & CBLK_INVALID_MSK) {
353 status = restoreTrack_l(cblk, true);
354 }
355 cblk->lock.unlock();
Eric Laurent059b4be2009-11-09 23:32:22 -0800356 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800357 LOGV("start() failed");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800358 mActive = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -0800359 if (t != 0) {
360 t->requestExit();
361 } else {
362 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
363 }
Eric Laurentbda74692009-11-04 08:27:26 -0800364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 }
366
367 if (t != 0) {
368 t->mLock.unlock();
369 }
370}
371
372void AudioTrack::stop()
373{
374 sp<AudioTrackThread> t = mAudioTrackThread;
375
376 LOGV("stop %p", this);
377 if (t != 0) {
378 t->mLock.lock();
379 }
380
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800381 AutoMutex lock(mLock);
382 if (mActive == 1) {
383 mActive = 0;
Eric Laurentef028272009-04-21 07:56:33 -0700384 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 mAudioTrack->stop();
386 // Cancel loops (If we are in the middle of a loop, playback
387 // would not stop until loopCount reaches 0).
Eric Laurent421ddc02011-03-07 14:52:59 -0800388 setLoop_l(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700389 // the playback head position will reset to 0, so if a marker is set, we need
390 // to activate it again
391 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 // Force flush if a shared buffer is used otherwise audioflinger
393 // will not stop before end of buffer is reached.
394 if (mSharedBuffer != 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800395 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 }
397 if (t != 0) {
398 t->requestExit();
399 } else {
400 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
401 }
402 }
403
404 if (t != 0) {
405 t->mLock.unlock();
406 }
407}
408
409bool AudioTrack::stopped() const
410{
411 return !mActive;
412}
413
414void AudioTrack::flush()
415{
Eric Laurent421ddc02011-03-07 14:52:59 -0800416 AutoMutex lock(mLock);
417 flush_l();
418}
419
420// must be called with mLock held
421void AudioTrack::flush_l()
422{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700424
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700425 // clear playback marker and periodic update counter
426 mMarkerPosition = 0;
427 mMarkerReached = false;
428 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 mAudioTrack->flush();
432 // Release AudioTrack callback thread in case it was waiting for new buffers
433 // in AudioTrack::obtainBuffer()
434 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 }
436}
437
438void AudioTrack::pause()
439{
440 LOGV("pause");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800441 AutoMutex lock(mLock);
442 if (mActive == 1) {
443 mActive = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 mAudioTrack->pause();
445 }
446}
447
448void AudioTrack::mute(bool e)
449{
450 mAudioTrack->mute(e);
451 mMuted = e;
452}
453
454bool AudioTrack::muted() const
455{
456 return mMuted;
457}
458
Eric Laurent65b65452010-06-01 23:49:17 -0700459status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460{
Eric Laurent65b65452010-06-01 23:49:17 -0700461 if (left > 1.0f || right > 1.0f) {
462 return BAD_VALUE;
463 }
464
Eric Laurent421ddc02011-03-07 14:52:59 -0800465 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 mVolume[LEFT] = left;
467 mVolume[RIGHT] = right;
468
469 // write must be atomic
Eric Laurent65b65452010-06-01 23:49:17 -0700470 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
471
472 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473}
474
475void AudioTrack::getVolume(float* left, float* right)
476{
Eric Laurent65b65452010-06-01 23:49:17 -0700477 if (left != NULL) {
478 *left = mVolume[LEFT];
479 }
480 if (right != NULL) {
481 *right = mVolume[RIGHT];
482 }
483}
484
Eric Laurent7070b362010-07-16 07:43:46 -0700485status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurent65b65452010-06-01 23:49:17 -0700486{
Eric Laurent7070b362010-07-16 07:43:46 -0700487 LOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurent65b65452010-06-01 23:49:17 -0700488 if (level > 1.0f) {
489 return BAD_VALUE;
490 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800491 AutoMutex lock(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -0700492
493 mSendLevel = level;
494
495 mCblk->sendLevel = uint16_t(level * 0x1000);
496
497 return NO_ERROR;
498}
499
Eric Laurent7070b362010-07-16 07:43:46 -0700500void AudioTrack::getAuxEffectSendLevel(float* level)
Eric Laurent65b65452010-06-01 23:49:17 -0700501{
502 if (level != NULL) {
503 *level = mSendLevel;
504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505}
506
Eric Laurent88e209d2009-07-07 07:10:45 -0700507status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508{
509 int afSamplingRate;
510
511 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700512 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
514 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700515 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516
Eric Laurent421ddc02011-03-07 14:52:59 -0800517 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700518 mCblk->sampleRate = rate;
519 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520}
521
522uint32_t AudioTrack::getSampleRate()
523{
Eric Laurent421ddc02011-03-07 14:52:59 -0800524 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700525 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526}
527
528status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
529{
Eric Laurent421ddc02011-03-07 14:52:59 -0800530 AutoMutex lock(mLock);
531 return setLoop_l(loopStart, loopEnd, loopCount);
532}
533
534// must be called with mLock held
535status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
536{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 audio_track_cblk_t* cblk = mCblk;
538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 Mutex::Autolock _l(cblk->lock);
540
541 if (loopCount == 0) {
542 cblk->loopStart = UINT_MAX;
543 cblk->loopEnd = UINT_MAX;
544 cblk->loopCount = 0;
545 mLoopCount = 0;
546 return NO_ERROR;
547 }
548
549 if (loopStart >= loopEnd ||
Eric Laurent6667ac32011-03-21 11:49:00 -0700550 loopEnd - loopStart > cblk->frameCount ||
551 cblk->server > loopStart) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700552 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 -0800553 return BAD_VALUE;
554 }
555
Eric Laurent6667ac32011-03-21 11:49:00 -0700556 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700558 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561
562 cblk->loopStart = loopStart;
563 cblk->loopEnd = loopEnd;
564 cblk->loopCount = loopCount;
565 mLoopCount = loopCount;
566
567 return NO_ERROR;
568}
569
570status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
571{
Eric Laurent421ddc02011-03-07 14:52:59 -0800572 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 if (loopStart != 0) {
574 *loopStart = mCblk->loopStart;
575 }
576 if (loopEnd != 0) {
577 *loopEnd = mCblk->loopEnd;
578 }
579 if (loopCount != 0) {
580 if (mCblk->loopCount < 0) {
581 *loopCount = -1;
582 } else {
583 *loopCount = mCblk->loopCount;
584 }
585 }
586
587 return NO_ERROR;
588}
589
590status_t AudioTrack::setMarkerPosition(uint32_t marker)
591{
592 if (mCbf == 0) return INVALID_OPERATION;
593
594 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700595 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596
597 return NO_ERROR;
598}
599
600status_t AudioTrack::getMarkerPosition(uint32_t *marker)
601{
602 if (marker == 0) return BAD_VALUE;
603
604 *marker = mMarkerPosition;
605
606 return NO_ERROR;
607}
608
609status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
610{
611 if (mCbf == 0) return INVALID_OPERATION;
612
613 uint32_t curPosition;
614 getPosition(&curPosition);
615 mNewPosition = curPosition + updatePeriod;
616 mUpdatePeriod = updatePeriod;
617
618 return NO_ERROR;
619}
620
621status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
622{
623 if (updatePeriod == 0) return BAD_VALUE;
624
625 *updatePeriod = mUpdatePeriod;
626
627 return NO_ERROR;
628}
629
630status_t AudioTrack::setPosition(uint32_t position)
631{
Eric Laurent421ddc02011-03-07 14:52:59 -0800632 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 Mutex::Autolock _l(mCblk->lock);
634
635 if (!stopped()) return INVALID_OPERATION;
636
637 if (position > mCblk->user) return BAD_VALUE;
638
639 mCblk->server = position;
Eric Laurentae29b762011-03-28 18:37:07 -0700640 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -0700641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 return NO_ERROR;
643}
644
645status_t AudioTrack::getPosition(uint32_t *position)
646{
647 if (position == 0) return BAD_VALUE;
Eric Laurent421ddc02011-03-07 14:52:59 -0800648 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 *position = mCblk->server;
650
651 return NO_ERROR;
652}
653
654status_t AudioTrack::reload()
655{
Eric Laurent421ddc02011-03-07 14:52:59 -0800656 AutoMutex lock(mLock);
657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700659
Eric Laurent421ddc02011-03-07 14:52:59 -0800660 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700662 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663
664 return NO_ERROR;
665}
666
Eric Laurenta553c252009-07-17 12:17:14 -0700667audio_io_handle_t AudioTrack::getOutput()
668{
Eric Laurent421ddc02011-03-07 14:52:59 -0800669 AutoMutex lock(mLock);
670 return getOutput_l();
671}
672
673// must be called with mLock held
674audio_io_handle_t AudioTrack::getOutput_l()
675{
Eric Laurenta553c252009-07-17 12:17:14 -0700676 return AudioSystem::getOutput((AudioSystem::stream_type)mStreamType,
677 mCblk->sampleRate, mFormat, mChannels, (AudioSystem::output_flags)mFlags);
678}
679
Eric Laurent65b65452010-06-01 23:49:17 -0700680int AudioTrack::getSessionId()
681{
682 return mSessionId;
683}
684
685status_t AudioTrack::attachAuxEffect(int effectId)
686{
Eric Laurent7070b362010-07-16 07:43:46 -0700687 LOGV("attachAuxEffect(%d)", effectId);
688 status_t status = mAudioTrack->attachAuxEffect(effectId);
689 if (status == NO_ERROR) {
690 mAuxEffectId = effectId;
691 }
692 return status;
Eric Laurent65b65452010-06-01 23:49:17 -0700693}
694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695// -------------------------------------------------------------------------
696
Eric Laurent421ddc02011-03-07 14:52:59 -0800697// must be called with mLock held
698status_t AudioTrack::createTrack_l(
Eric Laurentbda74692009-11-04 08:27:26 -0800699 int streamType,
700 uint32_t sampleRate,
701 int format,
702 int channelCount,
703 int frameCount,
704 uint32_t flags,
705 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700706 audio_io_handle_t output,
707 bool enforceFrameCount)
Eric Laurentbda74692009-11-04 08:27:26 -0800708{
709 status_t status;
710 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
711 if (audioFlinger == 0) {
712 LOGE("Could not get audioflinger");
713 return NO_INIT;
714 }
715
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700716 int afSampleRate;
717 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
718 return NO_INIT;
719 }
720 int afFrameCount;
721 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
722 return NO_INIT;
723 }
724 uint32_t afLatency;
725 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
726 return NO_INIT;
727 }
728
729 mNotificationFramesAct = mNotificationFramesReq;
730 if (!AudioSystem::isLinearPCM(format)) {
731 if (sharedBuffer != 0) {
732 frameCount = sharedBuffer->size();
733 }
734 } else {
735 // Ensure that buffer depth covers at least audio hardware latency
736 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
737 if (minBufCount < 2) minBufCount = 2;
738
739 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
740
741 if (sharedBuffer == 0) {
742 if (frameCount == 0) {
743 frameCount = minFrameCount;
744 }
745 if (mNotificationFramesAct == 0) {
746 mNotificationFramesAct = frameCount/2;
747 }
748 // Make sure that application is notified with sufficient margin
749 // before underrun
750 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
751 mNotificationFramesAct = frameCount/2;
752 }
753 if (frameCount < minFrameCount) {
754 if (enforceFrameCount) {
755 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
756 return BAD_VALUE;
757 } else {
758 frameCount = minFrameCount;
759 }
760 }
761 } else {
762 // Ensure that buffer alignment matches channelcount
763 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
764 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
765 return BAD_VALUE;
766 }
767 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
768 }
769 }
770
Eric Laurentbda74692009-11-04 08:27:26 -0800771 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
772 streamType,
773 sampleRate,
774 format,
775 channelCount,
776 frameCount,
777 ((uint16_t)flags) << 16,
778 sharedBuffer,
779 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700780 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800781 &status);
782
783 if (track == 0) {
784 LOGE("AudioFlinger could not create track, status: %d", status);
785 return status;
786 }
787 sp<IMemory> cblk = track->getCblk();
788 if (cblk == 0) {
789 LOGE("Could not get control block");
790 return NO_INIT;
791 }
792 mAudioTrack.clear();
793 mAudioTrack = track;
794 mCblkMemory.clear();
795 mCblkMemory = cblk;
796 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurentae29b762011-03-28 18:37:07 -0700797 android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
Eric Laurentbda74692009-11-04 08:27:26 -0800798 if (sharedBuffer == 0) {
799 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
800 } else {
801 mCblk->buffers = sharedBuffer->pointer();
802 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700803 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800804 }
805
Eric Laurent65b65452010-06-01 23:49:17 -0700806 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
807 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent7070b362010-07-16 07:43:46 -0700808 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent49f02be2009-11-19 09:00:56 -0800809 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
810 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700811 mRemainingFrames = mNotificationFramesAct;
812 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800813 return NO_ERROR;
814}
815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
817{
Eric Laurent421ddc02011-03-07 14:52:59 -0800818 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 status_t result;
821 audio_track_cblk_t* cblk = mCblk;
822 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700823 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824
825 audioBuffer->frameCount = 0;
826 audioBuffer->size = 0;
827
828 uint32_t framesAvail = cblk->framesAvailable();
829
Eric Laurent6667ac32011-03-21 11:49:00 -0700830 cblk->lock.lock();
831 if (cblk->flags & CBLK_INVALID_MSK) {
832 goto create_new_track;
833 }
834 cblk->lock.unlock();
835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800837 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 goto start_loop_here;
839 while (framesAvail == 0) {
840 active = mActive;
841 if (UNLIKELY(!active)) {
842 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800843 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 return NO_MORE_BUFFERS;
845 }
Eric Laurentbda74692009-11-04 08:27:26 -0800846 if (UNLIKELY(!waitCount)) {
847 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800849 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700850 if (!(cblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800851 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700852 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700853 cblk->lock.unlock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800854 mLock.lock();
855 if (mActive == 0) {
856 return status_t(STOPPED);
857 }
858 cblk->lock.lock();
859 }
860
861 if (cblk->flags & CBLK_INVALID_MSK) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700862 goto create_new_track;
863 }
Eric Laurenta553c252009-07-17 12:17:14 -0700864 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700865 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
867 // timing out when a loop has been set and we have already written upto loop end
868 // is a normal condition: no need to wake AudioFlinger up.
869 if (cblk->user < cblk->loopEnd) {
870 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
871 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700872 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800874 result = mAudioTrack->start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800876 if (result == DEAD_OBJECT) {
Eric Laurentae29b762011-03-28 18:37:07 -0700877 android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -0800878create_new_track:
879 result = restoreTrack_l(cblk, false);
880 }
881 if (result != NO_ERROR) {
882 LOGW("obtainBuffer create Track error %d", result);
883 cblk->lock.unlock();
884 return result;
885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 }
887 cblk->waitTimeMs = 0;
888 }
Eric Laurenta553c252009-07-17 12:17:14 -0700889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800891 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 return TIMED_OUT;
893 }
894 }
895 // read the server count again
896 start_loop_here:
897 framesAvail = cblk->framesAvailable_l();
898 }
Eric Laurentbda74692009-11-04 08:27:26 -0800899 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 }
901
Eric Laurent4712baa2010-09-30 16:12:31 -0700902 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent421ddc02011-03-07 14:52:59 -0800903 if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
Eric Laurentae29b762011-03-28 18:37:07 -0700904 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
905 LOGW("obtainBuffer() track %p disabled, restarting", this);
906 mAudioTrack->start();
Eric Laurent4712baa2010-09-30 16:12:31 -0700907 }
908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 if (framesReq > framesAvail) {
912 framesReq = framesAvail;
913 }
914
915 uint32_t u = cblk->user;
916 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
917
918 if (u + framesReq > bufferEnd) {
919 framesReq = bufferEnd - u;
920 }
921
Eric Laurenta553c252009-07-17 12:17:14 -0700922 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
923 audioBuffer->channelCount = mChannelCount;
924 audioBuffer->frameCount = framesReq;
925 audioBuffer->size = framesReq * cblk->frameSize;
926 if (AudioSystem::isLinearPCM(mFormat)) {
927 audioBuffer->format = AudioSystem::PCM_16_BIT;
928 } else {
929 audioBuffer->format = mFormat;
930 }
931 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 active = mActive;
933 return active ? status_t(NO_ERROR) : status_t(STOPPED);
934}
935
936void AudioTrack::releaseBuffer(Buffer* audioBuffer)
937{
Eric Laurent421ddc02011-03-07 14:52:59 -0800938 AutoMutex lock(mLock);
939 mCblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940}
941
942// -------------------------------------------------------------------------
943
944ssize_t AudioTrack::write(const void* buffer, size_t userSize)
945{
946
947 if (mSharedBuffer != 0) return INVALID_OPERATION;
948
949 if (ssize_t(userSize) < 0) {
950 // sanity-check. user is most-likely passing an error code.
951 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
952 buffer, userSize, userSize);
953 return BAD_VALUE;
954 }
955
956 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
957
Eric Laurent421ddc02011-03-07 14:52:59 -0800958 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
959 // while we are accessing the cblk
960 mLock.lock();
961 sp <IAudioTrack> audioTrack = mAudioTrack;
962 sp <IMemory> iMem = mCblkMemory;
963 mLock.unlock();
964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 ssize_t written = 0;
966 const int8_t *src = (const int8_t *)buffer;
967 Buffer audioBuffer;
Eric Laurent913af0b2011-03-17 09:36:51 -0700968 size_t frameSz = (size_t)frameSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969
970 do {
Eric Laurent913af0b2011-03-17 09:36:51 -0700971 audioBuffer.frameCount = userSize/frameSz;
Eric Laurenta553c252009-07-17 12:17:14 -0700972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 // Calling obtainBuffer() with a negative wait count causes
974 // an (almost) infinite wait time.
975 status_t err = obtainBuffer(&audioBuffer, -1);
976 if (err < 0) {
977 // out of buffers, return #bytes written
978 if (err == status_t(NO_MORE_BUFFERS))
979 break;
980 return ssize_t(err);
981 }
982
983 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700984
Eric Laurent28ad42b2009-08-04 10:42:26 -0700985 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 // Divide capacity by 2 to take expansion into account
987 toWrite = audioBuffer.size>>1;
988 // 8 to 16 bit conversion
989 int count = toWrite;
990 int16_t *dst = (int16_t *)(audioBuffer.i8);
991 while(count--) {
992 *dst++ = (int16_t)(*src++^0x80) << 8;
993 }
Eric Laurent28ad42b2009-08-04 10:42:26 -0700994 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 toWrite = audioBuffer.size;
996 memcpy(audioBuffer.i8, src, toWrite);
997 src += toWrite;
998 }
999 userSize -= toWrite;
1000 written += toWrite;
1001
1002 releaseBuffer(&audioBuffer);
Eric Laurent913af0b2011-03-17 09:36:51 -07001003 } while (userSize >= frameSz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004
1005 return written;
1006}
1007
1008// -------------------------------------------------------------------------
1009
1010bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1011{
1012 Buffer audioBuffer;
1013 uint32_t frames;
1014 size_t writtenSize;
1015
Eric Laurent421ddc02011-03-07 14:52:59 -08001016 mLock.lock();
1017 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1018 // while we are accessing the cblk
1019 sp <IAudioTrack> audioTrack = mAudioTrack;
1020 sp <IMemory> iMem = mCblkMemory;
1021 audio_track_cblk_t* cblk = mCblk;
1022 mLock.unlock();
1023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 // Manage underrun callback
Eric Laurentae29b762011-03-28 18:37:07 -07001025 if (mActive && (cblk->framesAvailable() == cblk->frameCount)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001026 LOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
Eric Laurentae29b762011-03-28 18:37:07 -07001027 if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 mCbf(EVENT_UNDERRUN, mUserData, 0);
Eric Laurent421ddc02011-03-07 14:52:59 -08001029 if (cblk->server == cblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001030 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 if (mSharedBuffer != 0) return false;
1033 }
1034 }
Eric Laurenta553c252009-07-17 12:17:14 -07001035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 // Manage loop end callback
Eric Laurent421ddc02011-03-07 14:52:59 -08001037 while (mLoopCount > cblk->loopCount) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 int loopCount = -1;
1039 mLoopCount--;
1040 if (mLoopCount >= 0) loopCount = mLoopCount;
1041
1042 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1043 }
1044
1045 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001046 if (!mMarkerReached && (mMarkerPosition > 0)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001047 if (cblk->server >= mMarkerPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001049 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 }
1052
1053 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -07001054 if (mUpdatePeriod > 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001055 while (cblk->server >= mNewPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1057 mNewPosition += mUpdatePeriod;
1058 }
1059 }
1060
1061 // If Shared buffer is used, no data is requested from client.
1062 if (mSharedBuffer != 0) {
1063 frames = 0;
1064 } else {
1065 frames = mRemainingFrames;
1066 }
1067
1068 do {
1069
1070 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -07001071
1072 // Calling obtainBuffer() with a wait count of 1
1073 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1074 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 status_t err = obtainBuffer(&audioBuffer, 1);
1076 if (err < NO_ERROR) {
1077 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -07001078 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 -08001079 return false;
1080 }
1081 break;
1082 }
1083 if (err == status_t(STOPPED)) return false;
1084
1085 // Divide buffer size by 2 to take into account the expansion
1086 // due to 8 to 16 bit conversion: the callback must fill only half
1087 // of the destination buffer
Eric Laurent28ad42b2009-08-04 10:42:26 -07001088 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 audioBuffer.size >>= 1;
1090 }
1091
1092 size_t reqSize = audioBuffer.size;
1093 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1094 writtenSize = audioBuffer.size;
1095
1096 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001097 if (ssize_t(writtenSize) <= 0) {
1098 // The callback is done filling buffers
1099 // Keep this thread going to handle timed events and
1100 // still try to get more data in intervals of WAIT_PERIOD_MS
1101 // but don't just loop and block the CPU, so wait
1102 usleep(WAIT_PERIOD_MS*1000);
1103 break;
1104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 if (writtenSize > reqSize) writtenSize = reqSize;
1106
Eric Laurent28ad42b2009-08-04 10:42:26 -07001107 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 // 8 to 16 bit conversion
1109 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1110 int count = writtenSize;
1111 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1112 while(count--) {
1113 *dst-- = (int16_t)(*src--^0x80) << 8;
1114 }
1115 writtenSize <<= 1;
1116 }
1117
1118 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001119 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1120 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1121 // 16 bit.
1122 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 frames -= audioBuffer.frameCount;
1125
1126 releaseBuffer(&audioBuffer);
1127 }
1128 while (frames);
1129
1130 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001131 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 } else {
1133 mRemainingFrames = frames;
1134 }
1135 return true;
1136}
1137
Eric Laurent421ddc02011-03-07 14:52:59 -08001138// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1139// the IAudioTrack and IMemory in case they are recreated here.
1140// If the IAudioTrack is successfully restored, the cblk pointer is updated
1141status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1142{
1143 status_t result;
1144
Eric Laurentae29b762011-03-28 18:37:07 -07001145 if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001146 LOGW("dead IAudioTrack, creating a new one from %s",
1147 fromStart ? "start()" : "obtainBuffer()");
1148
Eric Laurent421ddc02011-03-07 14:52:59 -08001149 // signal old cblk condition so that other threads waiting for available buffers stop
1150 // waiting now
1151 cblk->cv.broadcast();
1152 cblk->lock.unlock();
1153
1154 // if the new IAudioTrack is created, createTrack_l() will modify the
1155 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1156 // It will also delete the strong references on previous IAudioTrack and IMemory
1157 result = createTrack_l(mStreamType,
1158 cblk->sampleRate,
1159 mFormat,
1160 mChannelCount,
1161 mFrameCount,
1162 mFlags,
1163 mSharedBuffer,
1164 getOutput_l(),
1165 false);
1166
1167 if (result == NO_ERROR) {
Eric Laurent6667ac32011-03-21 11:49:00 -07001168 // restore write index and set other indexes to reflect empty buffer status
1169 mCblk->user = cblk->user;
1170 mCblk->server = cblk->user;
1171 mCblk->userBase = cblk->user;
1172 mCblk->serverBase = cblk->user;
1173 // restore loop: this is not guaranteed to succeed if new frame count is not
1174 // compatible with loop length
1175 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
Eric Laurent421ddc02011-03-07 14:52:59 -08001176 if (!fromStart) {
1177 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1178 }
Eric Laurent6667ac32011-03-21 11:49:00 -07001179 if (mActive) {
1180 result = mAudioTrack->start();
1181 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001182 if (fromStart && result == NO_ERROR) {
1183 mNewPosition = mCblk->server + mUpdatePeriod;
1184 }
1185 }
1186 if (result != NO_ERROR) {
1187 mActive = false;
1188 }
1189
1190 // signal old cblk condition for other threads waiting for restore completion
Eric Laurentae29b762011-03-28 18:37:07 -07001191 android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
Eric Laurent421ddc02011-03-07 14:52:59 -08001192 cblk->cv.broadcast();
Eric Laurent421ddc02011-03-07 14:52:59 -08001193 } else {
1194 if (!(cblk->flags & CBLK_RESTORED_MSK)) {
1195 LOGW("dead IAudioTrack, waiting for a new one");
1196 mLock.unlock();
1197 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
1198 cblk->lock.unlock();
1199 mLock.lock();
1200 } else {
1201 LOGW("dead IAudioTrack, already restored");
1202 result = NO_ERROR;
1203 cblk->lock.unlock();
1204 }
1205 if (result != NO_ERROR || mActive == 0) {
1206 result = status_t(STOPPED);
1207 }
1208 }
1209 LOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1210 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1211
1212 if (result == NO_ERROR) {
1213 // from now on we switch to the newly created cblk
1214 cblk = mCblk;
1215 }
1216 cblk->lock.lock();
1217
1218 LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d", result);
1219
1220 return result;
1221}
1222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1224{
1225
1226 const size_t SIZE = 256;
1227 char buffer[SIZE];
1228 String8 result;
1229
1230 result.append(" AudioTrack::dump\n");
1231 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1232 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001233 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 -08001234 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001235 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 -08001236 result.append(buffer);
1237 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1238 result.append(buffer);
1239 ::write(fd, result.string(), result.size());
1240 return NO_ERROR;
1241}
1242
1243// =========================================================================
1244
1245AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1246 : Thread(bCanCallJava), mReceiver(receiver)
1247{
1248}
1249
1250bool AudioTrack::AudioTrackThread::threadLoop()
1251{
1252 return mReceiver.processAudioBuffer(this);
1253}
1254
1255status_t AudioTrack::AudioTrackThread::readyToRun()
1256{
1257 return NO_ERROR;
1258}
1259
1260void AudioTrack::AudioTrackThread::onFirstRef()
1261{
1262}
1263
1264// =========================================================================
1265
Eric Laurentae29b762011-03-28 18:37:07 -07001266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001268 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1269 userBase(0), serverBase(0), buffers(0), frameCount(0),
1270 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurentae29b762011-03-28 18:37:07 -07001271 sendLevel(0), flags(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272{
1273}
1274
1275uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1276{
1277 uint32_t u = this->user;
1278
1279 u += frameCount;
1280 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001281 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1283 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1284 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1285 }
1286 } else if (u > this->server) {
1287 LOGW("stepServer occured after track reset");
1288 u = this->server;
1289 }
1290
1291 if (u >= userBase + this->frameCount) {
1292 userBase += this->frameCount;
1293 }
1294
1295 this->user = u;
1296
1297 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurent913af0b2011-03-17 09:36:51 -07001298 if (flags & CBLK_UNDERRUN_MSK) {
Eric Laurentae29b762011-03-28 18:37:07 -07001299 android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
Eric Laurent913af0b2011-03-17 09:36:51 -07001300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301
1302 return u;
1303}
1304
1305bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1306{
Eric Laurentae29b762011-03-28 18:37:07 -07001307 if (!tryLock()) {
1308 LOGW("stepServer() could not lock cblk");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 return false;
1310 }
1311
1312 uint32_t s = this->server;
1313
1314 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001315 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 // Mark that we have read the first buffer so that next time stepUser() is called
1317 // we switch to normal obtainBuffer() timeout period
1318 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001319 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 // It is possible that we receive a flush()
1322 // while the mixer is processing a block: in this case,
1323 // stepServer() is called After the flush() has reset u & s and
1324 // we have s > u
1325 if (s > this->user) {
1326 LOGW("stepServer occured after track reset");
1327 s = this->user;
1328 }
1329 }
1330
1331 if (s >= loopEnd) {
1332 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1333 s = loopStart;
1334 if (--loopCount == 0) {
1335 loopEnd = UINT_MAX;
1336 loopStart = UINT_MAX;
1337 }
1338 }
1339 if (s >= serverBase + this->frameCount) {
1340 serverBase += this->frameCount;
1341 }
1342
1343 this->server = s;
1344
Eric Laurent421ddc02011-03-07 14:52:59 -08001345 if (!(flags & CBLK_INVALID_MSK)) {
1346 cv.signal();
1347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 lock.unlock();
1349 return true;
1350}
1351
1352void* audio_track_cblk_t::buffer(uint32_t offset) const
1353{
Eric Laurenta553c252009-07-17 12:17:14 -07001354 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355}
1356
1357uint32_t audio_track_cblk_t::framesAvailable()
1358{
1359 Mutex::Autolock _l(lock);
1360 return framesAvailable_l();
1361}
1362
1363uint32_t audio_track_cblk_t::framesAvailable_l()
1364{
1365 uint32_t u = this->user;
1366 uint32_t s = this->server;
1367
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001368 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 uint32_t limit = (s < loopStart) ? s : loopStart;
1370 return limit + frameCount - u;
1371 } else {
1372 return frameCount + u - s;
1373 }
1374}
1375
1376uint32_t audio_track_cblk_t::framesReady()
1377{
1378 uint32_t u = this->user;
1379 uint32_t s = this->server;
1380
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001381 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 if (u < loopEnd) {
1383 return u - s;
1384 } else {
Eric Laurentae29b762011-03-28 18:37:07 -07001385 // do not block on mutex shared with client on AudioFlinger side
1386 if (!tryLock()) {
1387 LOGW("framesReady() could not lock cblk");
1388 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
Eric Laurentae29b762011-03-28 18:37:07 -07001390 uint32_t frames = UINT_MAX;
1391 if (loopCount >= 0) {
1392 frames = (loopEnd - loopStart)*loopCount + u - s;
1393 }
1394 lock.unlock();
1395 return frames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
1397 } else {
1398 return s - u;
1399 }
1400}
1401
Eric Laurentae29b762011-03-28 18:37:07 -07001402bool audio_track_cblk_t::tryLock()
1403{
1404 // the code below simulates lock-with-timeout
1405 // we MUST do this to protect the AudioFlinger server
1406 // as this lock is shared with the client.
1407 status_t err;
1408
1409 err = lock.tryLock();
1410 if (err == -EBUSY) { // just wait a bit
1411 usleep(1000);
1412 err = lock.tryLock();
1413 }
1414 if (err != NO_ERROR) {
1415 // probably, the client just died.
1416 return false;
1417 }
1418 return true;
1419}
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421// -------------------------------------------------------------------------
1422
1423}; // namespace android
1424