blob: 8d8f67b438aee937bf9922f4829cce00e7d011e9 [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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038
39#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
40#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
41
42namespace android {
Chia-chi Yehbd240c22010-06-16 06:33:13 +080043// ---------------------------------------------------------------------------
44
45// static
46status_t AudioTrack::getMinFrameCount(
47 int* frameCount,
48 int streamType,
49 uint32_t sampleRate)
50{
51 int afSampleRate;
52 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
53 return NO_INIT;
54 }
55 int afFrameCount;
56 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
57 return NO_INIT;
58 }
59 uint32_t afLatency;
60 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
61 return NO_INIT;
62 }
63
64 // Ensure that buffer depth covers at least audio hardware latency
65 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
66 if (minBufCount < 2) minBufCount = 2;
67
68 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
69 afFrameCount * minBufCount * sampleRate / afSampleRate;
70 return NO_ERROR;
71}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
73// ---------------------------------------------------------------------------
74
75AudioTrack::AudioTrack()
76 : mStatus(NO_INIT)
77{
78}
79
80AudioTrack::AudioTrack(
81 int streamType,
82 uint32_t sampleRate,
83 int format,
Eric Laurenta553c252009-07-17 12:17:14 -070084 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 int frameCount,
86 uint32_t flags,
87 callback_t cbf,
88 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -070089 int notificationFrames,
90 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 : mStatus(NO_INIT)
92{
Eric Laurenta553c252009-07-17 12:17:14 -070093 mStatus = set(streamType, sampleRate, format, channels,
Eric Laurent619346f2010-06-21 09:27:30 -070094 frameCount, flags, cbf, user, notificationFrames,
95 0, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096}
97
98AudioTrack::AudioTrack(
99 int streamType,
100 uint32_t sampleRate,
101 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700102 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 const sp<IMemory>& sharedBuffer,
104 uint32_t flags,
105 callback_t cbf,
106 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -0700107 int notificationFrames,
108 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 : mStatus(NO_INIT)
110{
Eric Laurenta553c252009-07-17 12:17:14 -0700111 mStatus = set(streamType, sampleRate, format, channels,
Eric Laurent619346f2010-06-21 09:27:30 -0700112 0, flags, cbf, user, notificationFrames,
113 sharedBuffer, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114}
115
116AudioTrack::~AudioTrack()
117{
118 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
119
120 if (mStatus == NO_ERROR) {
121 // Make sure that callback function exits in the case where
122 // it is looping on buffer full condition in obtainBuffer().
123 // Otherwise the callback thread will never exit.
124 stop();
125 if (mAudioTrackThread != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 mAudioTrackThread->requestExitAndWait();
127 mAudioTrackThread.clear();
128 }
129 mAudioTrack.clear();
130 IPCThreadState::self()->flushCommands();
131 }
132}
133
134status_t AudioTrack::set(
135 int streamType,
136 uint32_t sampleRate,
137 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700138 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 int frameCount,
140 uint32_t flags,
141 callback_t cbf,
142 void* user,
143 int notificationFrames,
144 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -0700145 bool threadCanCallJava,
146 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147{
148
149 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
150
Eric Laurent421ddc02011-03-07 14:52:59 -0800151 AutoMutex lock(mLock);
Eric Laurentef028272009-04-21 07:56:33 -0700152 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 LOGE("Track already in use");
154 return INVALID_OPERATION;
155 }
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 int afSampleRate;
158 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
159 return NO_INIT;
160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 uint32_t afLatency;
162 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
163 return NO_INIT;
164 }
165
166 // handle default values first.
167 if (streamType == AudioSystem::DEFAULT) {
168 streamType = AudioSystem::MUSIC;
169 }
170 if (sampleRate == 0) {
171 sampleRate = afSampleRate;
172 }
173 // these below should probably come from the audioFlinger too...
174 if (format == 0) {
175 format = AudioSystem::PCM_16_BIT;
176 }
Eric Laurenta553c252009-07-17 12:17:14 -0700177 if (channels == 0) {
178 channels = AudioSystem::CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 }
180
181 // validate parameters
Eric Laurenta553c252009-07-17 12:17:14 -0700182 if (!AudioSystem::isValidFormat(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 LOGE("Invalid format");
184 return BAD_VALUE;
185 }
Eric Laurenta553c252009-07-17 12:17:14 -0700186
187 // force direct flag if format is not linear PCM
188 if (!AudioSystem::isLinearPCM(format)) {
189 flags |= AudioSystem::OUTPUT_FLAG_DIRECT;
190 }
191
192 if (!AudioSystem::isOutputChannel(channels)) {
193 LOGE("Invalid channel mask");
194 return BAD_VALUE;
195 }
196 uint32_t channelCount = AudioSystem::popCount(channels);
197
198 audio_io_handle_t output = AudioSystem::getOutput((AudioSystem::stream_type)streamType,
199 sampleRate, format, channels, (AudioSystem::output_flags)flags);
200
201 if (output == 0) {
202 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 return BAD_VALUE;
204 }
205
Eric Laurentbda74692009-11-04 08:27:26 -0800206 mVolume[LEFT] = 1.0f;
207 mVolume[RIGHT] = 1.0f;
Eric Laurent65b65452010-06-01 23:49:17 -0700208 mSendLevel = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700209 mFrameCount = frameCount;
210 mNotificationFramesReq = notificationFrames;
Eric Laurent65b65452010-06-01 23:49:17 -0700211 mSessionId = sessionId;
Eric Laurent7070b362010-07-16 07:43:46 -0700212 mAuxEffectId = 0;
Eric Laurent65b65452010-06-01 23:49:17 -0700213
Eric Laurentbda74692009-11-04 08:27:26 -0800214 // create the IAudioTrack
Eric Laurent421ddc02011-03-07 14:52:59 -0800215 status_t status = createTrack_l(streamType,
216 sampleRate,
217 format,
218 channelCount,
219 frameCount,
220 flags,
221 sharedBuffer,
222 output,
223 true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224
Eric Laurentbda74692009-11-04 08:27:26 -0800225 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 return status;
227 }
Eric Laurentbda74692009-11-04 08:27:26 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 if (cbf != 0) {
230 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
231 if (mAudioTrackThread == 0) {
232 LOGE("Could not create callback thread");
233 return NO_INIT;
234 }
235 }
236
237 mStatus = NO_ERROR;
238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 mStreamType = streamType;
240 mFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -0700241 mChannels = channels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 mChannelCount = channelCount;
243 mSharedBuffer = sharedBuffer;
244 mMuted = false;
245 mActive = 0;
246 mCbf = cbf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 mUserData = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 mLoopCount = 0;
249 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700250 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 mNewPosition = 0;
252 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700253 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254
255 return NO_ERROR;
256}
257
258status_t AudioTrack::initCheck() const
259{
260 return mStatus;
261}
262
263// -------------------------------------------------------------------------
264
265uint32_t AudioTrack::latency() const
266{
267 return mLatency;
268}
269
270int AudioTrack::streamType() const
271{
272 return mStreamType;
273}
274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275int AudioTrack::format() const
276{
277 return mFormat;
278}
279
280int AudioTrack::channelCount() const
281{
282 return mChannelCount;
283}
284
285uint32_t AudioTrack::frameCount() const
286{
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700287 return mCblk->frameCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288}
289
290int AudioTrack::frameSize() const
291{
Eric Laurenta553c252009-07-17 12:17:14 -0700292 if (AudioSystem::isLinearPCM(mFormat)) {
293 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
294 } else {
295 return sizeof(uint8_t);
296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297}
298
299sp<IMemory>& AudioTrack::sharedBuffer()
300{
301 return mSharedBuffer;
302}
303
304// -------------------------------------------------------------------------
305
306void AudioTrack::start()
307{
308 sp<AudioTrackThread> t = mAudioTrackThread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700309 status_t status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310
311 LOGV("start %p", this);
312 if (t != 0) {
313 if (t->exitPending()) {
314 if (t->requestExitAndWait() == WOULD_BLOCK) {
315 LOGE("AudioTrack::start called from thread");
316 return;
317 }
318 }
319 t->mLock.lock();
320 }
321
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800322 AutoMutex lock(mLock);
Eric Laurent421ddc02011-03-07 14:52:59 -0800323 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
324 // while we are accessing the cblk
325 sp <IAudioTrack> audioTrack = mAudioTrack;
326 sp <IMemory> iMem = mCblkMemory;
327 audio_track_cblk_t* cblk = mCblk;
328
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800329 if (mActive == 0) {
330 mActive = 1;
Eric Laurent421ddc02011-03-07 14:52:59 -0800331 mNewPosition = cblk->server + mUpdatePeriod;
332 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
333 cblk->waitTimeMs = 0;
334 cblk->flags &= ~CBLK_DISABLED_ON;
Eric Laurent059b4be2009-11-09 23:32:22 -0800335 if (t != 0) {
336 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
337 } else {
338 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
339 }
340
Eric Laurent421ddc02011-03-07 14:52:59 -0800341 LOGV("start %p before lock cblk %p", this, mCblk);
342 cblk->lock.lock();
343 if (!(cblk->flags & CBLK_INVALID_MSK)) {
344 cblk->lock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700345 status = mAudioTrack->start();
Eric Laurent421ddc02011-03-07 14:52:59 -0800346 cblk->lock.lock();
347 if (status == DEAD_OBJECT) {
348 cblk->flags |= CBLK_INVALID_MSK;
Eric Laurent49f02be2009-11-19 09:00:56 -0800349 }
Eric Laurent059b4be2009-11-09 23:32:22 -0800350 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800351 if (cblk->flags & CBLK_INVALID_MSK) {
352 status = restoreTrack_l(cblk, true);
353 }
354 cblk->lock.unlock();
Eric Laurent059b4be2009-11-09 23:32:22 -0800355 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800356 LOGV("start() failed");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800357 mActive = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -0800358 if (t != 0) {
359 t->requestExit();
360 } else {
361 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
362 }
Eric Laurentbda74692009-11-04 08:27:26 -0800363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 }
365
366 if (t != 0) {
367 t->mLock.unlock();
368 }
369}
370
371void AudioTrack::stop()
372{
373 sp<AudioTrackThread> t = mAudioTrackThread;
374
375 LOGV("stop %p", this);
376 if (t != 0) {
377 t->mLock.lock();
378 }
379
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800380 AutoMutex lock(mLock);
381 if (mActive == 1) {
382 mActive = 0;
Eric Laurentef028272009-04-21 07:56:33 -0700383 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 mAudioTrack->stop();
385 // Cancel loops (If we are in the middle of a loop, playback
386 // would not stop until loopCount reaches 0).
Eric Laurent421ddc02011-03-07 14:52:59 -0800387 setLoop_l(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700388 // the playback head position will reset to 0, so if a marker is set, we need
389 // to activate it again
390 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 // Force flush if a shared buffer is used otherwise audioflinger
392 // will not stop before end of buffer is reached.
393 if (mSharedBuffer != 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800394 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 }
396 if (t != 0) {
397 t->requestExit();
398 } else {
399 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
400 }
401 }
402
403 if (t != 0) {
404 t->mLock.unlock();
405 }
406}
407
408bool AudioTrack::stopped() const
409{
410 return !mActive;
411}
412
413void AudioTrack::flush()
414{
Eric Laurent421ddc02011-03-07 14:52:59 -0800415 AutoMutex lock(mLock);
416 flush_l();
417}
418
419// must be called with mLock held
420void AudioTrack::flush_l()
421{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700423
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700424 // clear playback marker and periodic update counter
425 mMarkerPosition = 0;
426 mMarkerReached = false;
427 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 mAudioTrack->flush();
431 // Release AudioTrack callback thread in case it was waiting for new buffers
432 // in AudioTrack::obtainBuffer()
433 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 }
435}
436
437void AudioTrack::pause()
438{
439 LOGV("pause");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800440 AutoMutex lock(mLock);
441 if (mActive == 1) {
442 mActive = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 mAudioTrack->pause();
444 }
445}
446
447void AudioTrack::mute(bool e)
448{
449 mAudioTrack->mute(e);
450 mMuted = e;
451}
452
453bool AudioTrack::muted() const
454{
455 return mMuted;
456}
457
Eric Laurent65b65452010-06-01 23:49:17 -0700458status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459{
Eric Laurent65b65452010-06-01 23:49:17 -0700460 if (left > 1.0f || right > 1.0f) {
461 return BAD_VALUE;
462 }
463
Eric Laurent421ddc02011-03-07 14:52:59 -0800464 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 mVolume[LEFT] = left;
466 mVolume[RIGHT] = right;
467
468 // write must be atomic
Eric Laurent65b65452010-06-01 23:49:17 -0700469 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
470
471 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472}
473
474void AudioTrack::getVolume(float* left, float* right)
475{
Eric Laurent65b65452010-06-01 23:49:17 -0700476 if (left != NULL) {
477 *left = mVolume[LEFT];
478 }
479 if (right != NULL) {
480 *right = mVolume[RIGHT];
481 }
482}
483
Eric Laurent7070b362010-07-16 07:43:46 -0700484status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurent65b65452010-06-01 23:49:17 -0700485{
Eric Laurent7070b362010-07-16 07:43:46 -0700486 LOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurent65b65452010-06-01 23:49:17 -0700487 if (level > 1.0f) {
488 return BAD_VALUE;
489 }
Eric Laurent421ddc02011-03-07 14:52:59 -0800490 AutoMutex lock(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -0700491
492 mSendLevel = level;
493
494 mCblk->sendLevel = uint16_t(level * 0x1000);
495
496 return NO_ERROR;
497}
498
Eric Laurent7070b362010-07-16 07:43:46 -0700499void AudioTrack::getAuxEffectSendLevel(float* level)
Eric Laurent65b65452010-06-01 23:49:17 -0700500{
501 if (level != NULL) {
502 *level = mSendLevel;
503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504}
505
Eric Laurent88e209d2009-07-07 07:10:45 -0700506status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507{
508 int afSamplingRate;
509
510 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700511 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
513 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700514 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515
Eric Laurent421ddc02011-03-07 14:52:59 -0800516 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700517 mCblk->sampleRate = rate;
518 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519}
520
521uint32_t AudioTrack::getSampleRate()
522{
Eric Laurent421ddc02011-03-07 14:52:59 -0800523 AutoMutex lock(mLock);
Eric Laurent88e209d2009-07-07 07:10:45 -0700524 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525}
526
527status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
528{
Eric Laurent421ddc02011-03-07 14:52:59 -0800529 AutoMutex lock(mLock);
530 return setLoop_l(loopStart, loopEnd, loopCount);
531}
532
533// must be called with mLock held
534status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
535{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 audio_track_cblk_t* cblk = mCblk;
537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 Mutex::Autolock _l(cblk->lock);
539
540 if (loopCount == 0) {
541 cblk->loopStart = UINT_MAX;
542 cblk->loopEnd = UINT_MAX;
543 cblk->loopCount = 0;
544 mLoopCount = 0;
545 return NO_ERROR;
546 }
547
548 if (loopStart >= loopEnd ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700549 loopEnd - loopStart > cblk->frameCount) {
550 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 -0800551 return BAD_VALUE;
552 }
553
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700554 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700556 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
560 cblk->loopStart = loopStart;
561 cblk->loopEnd = loopEnd;
562 cblk->loopCount = loopCount;
563 mLoopCount = loopCount;
564
565 return NO_ERROR;
566}
567
568status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
569{
Eric Laurent421ddc02011-03-07 14:52:59 -0800570 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 if (loopStart != 0) {
572 *loopStart = mCblk->loopStart;
573 }
574 if (loopEnd != 0) {
575 *loopEnd = mCblk->loopEnd;
576 }
577 if (loopCount != 0) {
578 if (mCblk->loopCount < 0) {
579 *loopCount = -1;
580 } else {
581 *loopCount = mCblk->loopCount;
582 }
583 }
584
585 return NO_ERROR;
586}
587
588status_t AudioTrack::setMarkerPosition(uint32_t marker)
589{
590 if (mCbf == 0) return INVALID_OPERATION;
591
592 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700593 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594
595 return NO_ERROR;
596}
597
598status_t AudioTrack::getMarkerPosition(uint32_t *marker)
599{
600 if (marker == 0) return BAD_VALUE;
601
602 *marker = mMarkerPosition;
603
604 return NO_ERROR;
605}
606
607status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
608{
609 if (mCbf == 0) return INVALID_OPERATION;
610
611 uint32_t curPosition;
612 getPosition(&curPosition);
613 mNewPosition = curPosition + updatePeriod;
614 mUpdatePeriod = updatePeriod;
615
616 return NO_ERROR;
617}
618
619status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
620{
621 if (updatePeriod == 0) return BAD_VALUE;
622
623 *updatePeriod = mUpdatePeriod;
624
625 return NO_ERROR;
626}
627
628status_t AudioTrack::setPosition(uint32_t position)
629{
Eric Laurent421ddc02011-03-07 14:52:59 -0800630 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 Mutex::Autolock _l(mCblk->lock);
632
633 if (!stopped()) return INVALID_OPERATION;
634
635 if (position > mCblk->user) return BAD_VALUE;
636
637 mCblk->server = position;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700638 mCblk->flags |= CBLK_FORCEREADY_ON;
Eric Laurenta553c252009-07-17 12:17:14 -0700639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 return NO_ERROR;
641}
642
643status_t AudioTrack::getPosition(uint32_t *position)
644{
645 if (position == 0) return BAD_VALUE;
Eric Laurent421ddc02011-03-07 14:52:59 -0800646 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 *position = mCblk->server;
648
649 return NO_ERROR;
650}
651
652status_t AudioTrack::reload()
653{
Eric Laurent421ddc02011-03-07 14:52:59 -0800654 AutoMutex lock(mLock);
655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700657
Eric Laurent421ddc02011-03-07 14:52:59 -0800658 flush_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700660 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661
662 return NO_ERROR;
663}
664
Eric Laurenta553c252009-07-17 12:17:14 -0700665audio_io_handle_t AudioTrack::getOutput()
666{
Eric Laurent421ddc02011-03-07 14:52:59 -0800667 AutoMutex lock(mLock);
668 return getOutput_l();
669}
670
671// must be called with mLock held
672audio_io_handle_t AudioTrack::getOutput_l()
673{
Eric Laurenta553c252009-07-17 12:17:14 -0700674 return AudioSystem::getOutput((AudioSystem::stream_type)mStreamType,
675 mCblk->sampleRate, mFormat, mChannels, (AudioSystem::output_flags)mFlags);
676}
677
Eric Laurent65b65452010-06-01 23:49:17 -0700678int AudioTrack::getSessionId()
679{
680 return mSessionId;
681}
682
683status_t AudioTrack::attachAuxEffect(int effectId)
684{
Eric Laurent7070b362010-07-16 07:43:46 -0700685 LOGV("attachAuxEffect(%d)", effectId);
686 status_t status = mAudioTrack->attachAuxEffect(effectId);
687 if (status == NO_ERROR) {
688 mAuxEffectId = effectId;
689 }
690 return status;
Eric Laurent65b65452010-06-01 23:49:17 -0700691}
692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693// -------------------------------------------------------------------------
694
Eric Laurent421ddc02011-03-07 14:52:59 -0800695// must be called with mLock held
696status_t AudioTrack::createTrack_l(
Eric Laurentbda74692009-11-04 08:27:26 -0800697 int streamType,
698 uint32_t sampleRate,
699 int format,
700 int channelCount,
701 int frameCount,
702 uint32_t flags,
703 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700704 audio_io_handle_t output,
705 bool enforceFrameCount)
Eric Laurentbda74692009-11-04 08:27:26 -0800706{
707 status_t status;
708 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
709 if (audioFlinger == 0) {
710 LOGE("Could not get audioflinger");
711 return NO_INIT;
712 }
713
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700714 int afSampleRate;
715 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
716 return NO_INIT;
717 }
718 int afFrameCount;
719 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
720 return NO_INIT;
721 }
722 uint32_t afLatency;
723 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
724 return NO_INIT;
725 }
726
727 mNotificationFramesAct = mNotificationFramesReq;
728 if (!AudioSystem::isLinearPCM(format)) {
729 if (sharedBuffer != 0) {
730 frameCount = sharedBuffer->size();
731 }
732 } else {
733 // Ensure that buffer depth covers at least audio hardware latency
734 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
735 if (minBufCount < 2) minBufCount = 2;
736
737 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
738
739 if (sharedBuffer == 0) {
740 if (frameCount == 0) {
741 frameCount = minFrameCount;
742 }
743 if (mNotificationFramesAct == 0) {
744 mNotificationFramesAct = frameCount/2;
745 }
746 // Make sure that application is notified with sufficient margin
747 // before underrun
748 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
749 mNotificationFramesAct = frameCount/2;
750 }
751 if (frameCount < minFrameCount) {
752 if (enforceFrameCount) {
753 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
754 return BAD_VALUE;
755 } else {
756 frameCount = minFrameCount;
757 }
758 }
759 } else {
760 // Ensure that buffer alignment matches channelcount
761 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
762 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
763 return BAD_VALUE;
764 }
765 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
766 }
767 }
768
Eric Laurentbda74692009-11-04 08:27:26 -0800769 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
770 streamType,
771 sampleRate,
772 format,
773 channelCount,
774 frameCount,
775 ((uint16_t)flags) << 16,
776 sharedBuffer,
777 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700778 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800779 &status);
780
781 if (track == 0) {
782 LOGE("AudioFlinger could not create track, status: %d", status);
783 return status;
784 }
785 sp<IMemory> cblk = track->getCblk();
786 if (cblk == 0) {
787 LOGE("Could not get control block");
788 return NO_INIT;
789 }
790 mAudioTrack.clear();
791 mAudioTrack = track;
792 mCblkMemory.clear();
793 mCblkMemory = cblk;
794 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700795 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurentbda74692009-11-04 08:27:26 -0800796 if (sharedBuffer == 0) {
797 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
798 } else {
799 mCblk->buffers = sharedBuffer->pointer();
800 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700801 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800802 }
803
Eric Laurent65b65452010-06-01 23:49:17 -0700804 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
805 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent7070b362010-07-16 07:43:46 -0700806 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent49f02be2009-11-19 09:00:56 -0800807 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
808 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700809 mRemainingFrames = mNotificationFramesAct;
810 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800811 return NO_ERROR;
812}
813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
815{
Eric Laurent421ddc02011-03-07 14:52:59 -0800816 AutoMutex lock(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 status_t result;
819 audio_track_cblk_t* cblk = mCblk;
820 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700821 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822
823 audioBuffer->frameCount = 0;
824 audioBuffer->size = 0;
825
826 uint32_t framesAvail = cblk->framesAvailable();
827
828 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800829 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 goto start_loop_here;
831 while (framesAvail == 0) {
832 active = mActive;
833 if (UNLIKELY(!active)) {
834 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800835 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 return NO_MORE_BUFFERS;
837 }
Eric Laurentbda74692009-11-04 08:27:26 -0800838 if (UNLIKELY(!waitCount)) {
839 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800841 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700842 if (!(cblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent421ddc02011-03-07 14:52:59 -0800843 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700844 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700845 cblk->lock.unlock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800846 mLock.lock();
847 if (mActive == 0) {
848 return status_t(STOPPED);
849 }
850 cblk->lock.lock();
851 }
852
853 if (cblk->flags & CBLK_INVALID_MSK) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700854 goto create_new_track;
855 }
Eric Laurenta553c252009-07-17 12:17:14 -0700856 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700857 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
859 // timing out when a loop has been set and we have already written upto loop end
860 // is a normal condition: no need to wake AudioFlinger up.
861 if (cblk->user < cblk->loopEnd) {
862 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
863 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700864 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800866 result = mAudioTrack->start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 cblk->lock.lock();
Eric Laurent421ddc02011-03-07 14:52:59 -0800868 if (result == DEAD_OBJECT) {
869 cblk->flags |= CBLK_INVALID_MSK;
870create_new_track:
871 result = restoreTrack_l(cblk, false);
872 }
873 if (result != NO_ERROR) {
874 LOGW("obtainBuffer create Track error %d", result);
875 cblk->lock.unlock();
876 return result;
877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879 cblk->waitTimeMs = 0;
880 }
Eric Laurenta553c252009-07-17 12:17:14 -0700881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800883 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 return TIMED_OUT;
885 }
886 }
887 // read the server count again
888 start_loop_here:
889 framesAvail = cblk->framesAvailable_l();
890 }
Eric Laurentbda74692009-11-04 08:27:26 -0800891 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 }
893
Eric Laurent4712baa2010-09-30 16:12:31 -0700894 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent421ddc02011-03-07 14:52:59 -0800895 if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
Eric Laurent4712baa2010-09-30 16:12:31 -0700896 cblk->flags &= ~CBLK_DISABLED_ON;
897 LOGW("obtainBuffer() track %p disabled, restarting", this);
898 mAudioTrack->start();
899 }
900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 if (framesReq > framesAvail) {
904 framesReq = framesAvail;
905 }
906
907 uint32_t u = cblk->user;
908 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
909
910 if (u + framesReq > bufferEnd) {
911 framesReq = bufferEnd - u;
912 }
913
Eric Laurenta553c252009-07-17 12:17:14 -0700914 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
915 audioBuffer->channelCount = mChannelCount;
916 audioBuffer->frameCount = framesReq;
917 audioBuffer->size = framesReq * cblk->frameSize;
918 if (AudioSystem::isLinearPCM(mFormat)) {
919 audioBuffer->format = AudioSystem::PCM_16_BIT;
920 } else {
921 audioBuffer->format = mFormat;
922 }
923 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 active = mActive;
925 return active ? status_t(NO_ERROR) : status_t(STOPPED);
926}
927
928void AudioTrack::releaseBuffer(Buffer* audioBuffer)
929{
Eric Laurent421ddc02011-03-07 14:52:59 -0800930 AutoMutex lock(mLock);
931 mCblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932}
933
934// -------------------------------------------------------------------------
935
936ssize_t AudioTrack::write(const void* buffer, size_t userSize)
937{
938
939 if (mSharedBuffer != 0) return INVALID_OPERATION;
940
941 if (ssize_t(userSize) < 0) {
942 // sanity-check. user is most-likely passing an error code.
943 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
944 buffer, userSize, userSize);
945 return BAD_VALUE;
946 }
947
948 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
949
Eric Laurent421ddc02011-03-07 14:52:59 -0800950 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
951 // while we are accessing the cblk
952 mLock.lock();
953 sp <IAudioTrack> audioTrack = mAudioTrack;
954 sp <IMemory> iMem = mCblkMemory;
955 mLock.unlock();
956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 ssize_t written = 0;
958 const int8_t *src = (const int8_t *)buffer;
959 Buffer audioBuffer;
960
961 do {
Eric Laurenta553c252009-07-17 12:17:14 -0700962 audioBuffer.frameCount = userSize/frameSize();
963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 // Calling obtainBuffer() with a negative wait count causes
965 // an (almost) infinite wait time.
966 status_t err = obtainBuffer(&audioBuffer, -1);
967 if (err < 0) {
968 // out of buffers, return #bytes written
969 if (err == status_t(NO_MORE_BUFFERS))
970 break;
971 return ssize_t(err);
972 }
973
974 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700975
Eric Laurent28ad42b2009-08-04 10:42:26 -0700976 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 // Divide capacity by 2 to take expansion into account
978 toWrite = audioBuffer.size>>1;
979 // 8 to 16 bit conversion
980 int count = toWrite;
981 int16_t *dst = (int16_t *)(audioBuffer.i8);
982 while(count--) {
983 *dst++ = (int16_t)(*src++^0x80) << 8;
984 }
Eric Laurent28ad42b2009-08-04 10:42:26 -0700985 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 toWrite = audioBuffer.size;
987 memcpy(audioBuffer.i8, src, toWrite);
988 src += toWrite;
989 }
990 userSize -= toWrite;
991 written += toWrite;
992
993 releaseBuffer(&audioBuffer);
994 } while (userSize);
995
996 return written;
997}
998
999// -------------------------------------------------------------------------
1000
1001bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1002{
1003 Buffer audioBuffer;
1004 uint32_t frames;
1005 size_t writtenSize;
1006
Eric Laurent421ddc02011-03-07 14:52:59 -08001007 mLock.lock();
1008 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1009 // while we are accessing the cblk
1010 sp <IAudioTrack> audioTrack = mAudioTrack;
1011 sp <IMemory> iMem = mCblkMemory;
1012 audio_track_cblk_t* cblk = mCblk;
1013 mLock.unlock();
1014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 // Manage underrun callback
Eric Laurent421ddc02011-03-07 14:52:59 -08001016 if (mActive && (cblk->framesReady() == 0)) {
1017 LOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
1018 if ((cblk->flags & CBLK_UNDERRUN_MSK) == CBLK_UNDERRUN_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 mCbf(EVENT_UNDERRUN, mUserData, 0);
Eric Laurent421ddc02011-03-07 14:52:59 -08001020 if (cblk->server == cblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001021 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 }
Eric Laurent421ddc02011-03-07 14:52:59 -08001023 cblk->flags |= CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 if (mSharedBuffer != 0) return false;
1025 }
1026 }
Eric Laurenta553c252009-07-17 12:17:14 -07001027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 // Manage loop end callback
Eric Laurent421ddc02011-03-07 14:52:59 -08001029 while (mLoopCount > cblk->loopCount) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 int loopCount = -1;
1031 mLoopCount--;
1032 if (mLoopCount >= 0) loopCount = mLoopCount;
1033
1034 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1035 }
1036
1037 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001038 if (!mMarkerReached && (mMarkerPosition > 0)) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001039 if (cblk->server >= mMarkerPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -07001041 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043 }
1044
1045 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -07001046 if (mUpdatePeriod > 0) {
Eric Laurent421ddc02011-03-07 14:52:59 -08001047 while (cblk->server >= mNewPosition) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1049 mNewPosition += mUpdatePeriod;
1050 }
1051 }
1052
1053 // If Shared buffer is used, no data is requested from client.
1054 if (mSharedBuffer != 0) {
1055 frames = 0;
1056 } else {
1057 frames = mRemainingFrames;
1058 }
1059
1060 do {
1061
1062 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -07001063
1064 // Calling obtainBuffer() with a wait count of 1
1065 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1066 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 status_t err = obtainBuffer(&audioBuffer, 1);
1068 if (err < NO_ERROR) {
1069 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -07001070 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 -08001071 return false;
1072 }
1073 break;
1074 }
1075 if (err == status_t(STOPPED)) return false;
1076
1077 // Divide buffer size by 2 to take into account the expansion
1078 // due to 8 to 16 bit conversion: the callback must fill only half
1079 // of the destination buffer
Eric Laurent28ad42b2009-08-04 10:42:26 -07001080 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 audioBuffer.size >>= 1;
1082 }
1083
1084 size_t reqSize = audioBuffer.size;
1085 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1086 writtenSize = audioBuffer.size;
1087
1088 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001089 if (ssize_t(writtenSize) <= 0) {
1090 // The callback is done filling buffers
1091 // Keep this thread going to handle timed events and
1092 // still try to get more data in intervals of WAIT_PERIOD_MS
1093 // but don't just loop and block the CPU, so wait
1094 usleep(WAIT_PERIOD_MS*1000);
1095 break;
1096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 if (writtenSize > reqSize) writtenSize = reqSize;
1098
Eric Laurent28ad42b2009-08-04 10:42:26 -07001099 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 // 8 to 16 bit conversion
1101 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1102 int count = writtenSize;
1103 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1104 while(count--) {
1105 *dst-- = (int16_t)(*src--^0x80) << 8;
1106 }
1107 writtenSize <<= 1;
1108 }
1109
1110 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001111 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1112 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1113 // 16 bit.
1114 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 frames -= audioBuffer.frameCount;
1117
1118 releaseBuffer(&audioBuffer);
1119 }
1120 while (frames);
1121
1122 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001123 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 } else {
1125 mRemainingFrames = frames;
1126 }
1127 return true;
1128}
1129
Eric Laurent421ddc02011-03-07 14:52:59 -08001130// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1131// the IAudioTrack and IMemory in case they are recreated here.
1132// If the IAudioTrack is successfully restored, the cblk pointer is updated
1133status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1134{
1135 status_t result;
1136
1137 if (!(cblk->flags & CBLK_RESTORING_MSK)) {
1138 LOGW("dead IAudioTrack, creating a new one from %s",
1139 fromStart ? "start()" : "obtainBuffer()");
1140
1141 cblk->flags |= CBLK_RESTORING_ON;
1142 // signal old cblk condition so that other threads waiting for available buffers stop
1143 // waiting now
1144 cblk->cv.broadcast();
1145 cblk->lock.unlock();
1146
1147 // if the new IAudioTrack is created, createTrack_l() will modify the
1148 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1149 // It will also delete the strong references on previous IAudioTrack and IMemory
1150 result = createTrack_l(mStreamType,
1151 cblk->sampleRate,
1152 mFormat,
1153 mChannelCount,
1154 mFrameCount,
1155 mFlags,
1156 mSharedBuffer,
1157 getOutput_l(),
1158 false);
1159
1160 if (result == NO_ERROR) {
1161 if (!fromStart) {
1162 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1163 }
1164 result = mAudioTrack->start();
1165 if (fromStart && result == NO_ERROR) {
1166 mNewPosition = mCblk->server + mUpdatePeriod;
1167 }
1168 }
1169 if (result != NO_ERROR) {
1170 mActive = false;
1171 }
1172
1173 // signal old cblk condition for other threads waiting for restore completion
1174 cblk->lock.lock();
1175 cblk->flags |= CBLK_RESTORED_MSK;
1176 cblk->cv.broadcast();
1177 cblk->lock.unlock();
1178 } else {
1179 if (!(cblk->flags & CBLK_RESTORED_MSK)) {
1180 LOGW("dead IAudioTrack, waiting for a new one");
1181 mLock.unlock();
1182 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
1183 cblk->lock.unlock();
1184 mLock.lock();
1185 } else {
1186 LOGW("dead IAudioTrack, already restored");
1187 result = NO_ERROR;
1188 cblk->lock.unlock();
1189 }
1190 if (result != NO_ERROR || mActive == 0) {
1191 result = status_t(STOPPED);
1192 }
1193 }
1194 LOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1195 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1196
1197 if (result == NO_ERROR) {
1198 // from now on we switch to the newly created cblk
1199 cblk = mCblk;
1200 }
1201 cblk->lock.lock();
1202
1203 LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d", result);
1204
1205 return result;
1206}
1207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1209{
1210
1211 const size_t SIZE = 256;
1212 char buffer[SIZE];
1213 String8 result;
1214
1215 result.append(" AudioTrack::dump\n");
1216 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1217 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001218 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 -08001219 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001220 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 -08001221 result.append(buffer);
1222 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1223 result.append(buffer);
1224 ::write(fd, result.string(), result.size());
1225 return NO_ERROR;
1226}
1227
1228// =========================================================================
1229
1230AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1231 : Thread(bCanCallJava), mReceiver(receiver)
1232{
1233}
1234
1235bool AudioTrack::AudioTrackThread::threadLoop()
1236{
1237 return mReceiver.processAudioBuffer(this);
1238}
1239
1240status_t AudioTrack::AudioTrackThread::readyToRun()
1241{
1242 return NO_ERROR;
1243}
1244
1245void AudioTrack::AudioTrackThread::onFirstRef()
1246{
1247}
1248
1249// =========================================================================
1250
1251audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001252 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1253 userBase(0), serverBase(0), buffers(0), frameCount(0),
1254 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurent65b65452010-06-01 23:49:17 -07001255 flags(0), sendLevel(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256{
1257}
1258
1259uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1260{
1261 uint32_t u = this->user;
1262
1263 u += frameCount;
1264 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001265 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1267 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1268 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1269 }
1270 } else if (u > this->server) {
1271 LOGW("stepServer occured after track reset");
1272 u = this->server;
1273 }
1274
1275 if (u >= userBase + this->frameCount) {
1276 userBase += this->frameCount;
1277 }
1278
1279 this->user = u;
1280
1281 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001282 flags &= ~CBLK_UNDERRUN_MSK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283
1284 return u;
1285}
1286
1287bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1288{
1289 // the code below simulates lock-with-timeout
1290 // we MUST do this to protect the AudioFlinger server
1291 // as this lock is shared with the client.
1292 status_t err;
1293
1294 err = lock.tryLock();
1295 if (err == -EBUSY) { // just wait a bit
1296 usleep(1000);
1297 err = lock.tryLock();
1298 }
1299 if (err != NO_ERROR) {
1300 // probably, the client just died.
1301 return false;
1302 }
1303
1304 uint32_t s = this->server;
1305
1306 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001307 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 // Mark that we have read the first buffer so that next time stepUser() is called
1309 // we switch to normal obtainBuffer() timeout period
1310 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001311 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 // It is possible that we receive a flush()
1314 // while the mixer is processing a block: in this case,
1315 // stepServer() is called After the flush() has reset u & s and
1316 // we have s > u
1317 if (s > this->user) {
1318 LOGW("stepServer occured after track reset");
1319 s = this->user;
1320 }
1321 }
1322
1323 if (s >= loopEnd) {
1324 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1325 s = loopStart;
1326 if (--loopCount == 0) {
1327 loopEnd = UINT_MAX;
1328 loopStart = UINT_MAX;
1329 }
1330 }
1331 if (s >= serverBase + this->frameCount) {
1332 serverBase += this->frameCount;
1333 }
1334
1335 this->server = s;
1336
Eric Laurent421ddc02011-03-07 14:52:59 -08001337 if (!(flags & CBLK_INVALID_MSK)) {
1338 cv.signal();
1339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 lock.unlock();
1341 return true;
1342}
1343
1344void* audio_track_cblk_t::buffer(uint32_t offset) const
1345{
Eric Laurenta553c252009-07-17 12:17:14 -07001346 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347}
1348
1349uint32_t audio_track_cblk_t::framesAvailable()
1350{
1351 Mutex::Autolock _l(lock);
1352 return framesAvailable_l();
1353}
1354
1355uint32_t audio_track_cblk_t::framesAvailable_l()
1356{
1357 uint32_t u = this->user;
1358 uint32_t s = this->server;
1359
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001360 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 uint32_t limit = (s < loopStart) ? s : loopStart;
1362 return limit + frameCount - u;
1363 } else {
1364 return frameCount + u - s;
1365 }
1366}
1367
1368uint32_t audio_track_cblk_t::framesReady()
1369{
1370 uint32_t u = this->user;
1371 uint32_t s = this->server;
1372
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001373 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 if (u < loopEnd) {
1375 return u - s;
1376 } else {
1377 Mutex::Autolock _l(lock);
1378 if (loopCount >= 0) {
1379 return (loopEnd - loopStart)*loopCount + u - s;
1380 } else {
1381 return UINT_MAX;
1382 }
1383 }
1384 } else {
1385 return s - u;
1386 }
1387}
1388
1389// -------------------------------------------------------------------------
1390
1391}; // namespace android
1392