blob: c1bed59c62d185b10fe0c9c2c56cc8b0ed0350b2 [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 Laurentef028272009-04-21 07:56:33 -0700151 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 LOGE("Track already in use");
153 return INVALID_OPERATION;
154 }
155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 int afSampleRate;
157 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
158 return NO_INIT;
159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 uint32_t afLatency;
161 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
162 return NO_INIT;
163 }
164
165 // handle default values first.
166 if (streamType == AudioSystem::DEFAULT) {
167 streamType = AudioSystem::MUSIC;
168 }
169 if (sampleRate == 0) {
170 sampleRate = afSampleRate;
171 }
172 // these below should probably come from the audioFlinger too...
173 if (format == 0) {
174 format = AudioSystem::PCM_16_BIT;
175 }
Eric Laurenta553c252009-07-17 12:17:14 -0700176 if (channels == 0) {
177 channels = AudioSystem::CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 }
179
180 // validate parameters
Eric Laurenta553c252009-07-17 12:17:14 -0700181 if (!AudioSystem::isValidFormat(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 LOGE("Invalid format");
183 return BAD_VALUE;
184 }
Eric Laurenta553c252009-07-17 12:17:14 -0700185
186 // force direct flag if format is not linear PCM
187 if (!AudioSystem::isLinearPCM(format)) {
188 flags |= AudioSystem::OUTPUT_FLAG_DIRECT;
189 }
190
191 if (!AudioSystem::isOutputChannel(channels)) {
192 LOGE("Invalid channel mask");
193 return BAD_VALUE;
194 }
195 uint32_t channelCount = AudioSystem::popCount(channels);
196
197 audio_io_handle_t output = AudioSystem::getOutput((AudioSystem::stream_type)streamType,
198 sampleRate, format, channels, (AudioSystem::output_flags)flags);
199
200 if (output == 0) {
201 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 return BAD_VALUE;
203 }
204
Eric Laurentbda74692009-11-04 08:27:26 -0800205 mVolume[LEFT] = 1.0f;
206 mVolume[RIGHT] = 1.0f;
Eric Laurent65b65452010-06-01 23:49:17 -0700207 mSendLevel = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700208 mFrameCount = frameCount;
209 mNotificationFramesReq = notificationFrames;
Eric Laurent65b65452010-06-01 23:49:17 -0700210 mSessionId = sessionId;
Eric Laurent7070b362010-07-16 07:43:46 -0700211 mAuxEffectId = 0;
Eric Laurent65b65452010-06-01 23:49:17 -0700212
Eric Laurentbda74692009-11-04 08:27:26 -0800213 // create the IAudioTrack
214 status_t status = createTrack(streamType, sampleRate, format, channelCount,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700215 frameCount, flags, sharedBuffer, output, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
Eric Laurentbda74692009-11-04 08:27:26 -0800217 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 return status;
219 }
Eric Laurentbda74692009-11-04 08:27:26 -0800220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 if (cbf != 0) {
222 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
223 if (mAudioTrackThread == 0) {
224 LOGE("Could not create callback thread");
225 return NO_INIT;
226 }
227 }
228
229 mStatus = NO_ERROR;
230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 mStreamType = streamType;
232 mFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -0700233 mChannels = channels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 mChannelCount = channelCount;
235 mSharedBuffer = sharedBuffer;
236 mMuted = false;
237 mActive = 0;
238 mCbf = cbf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 mUserData = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 mLoopCount = 0;
241 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700242 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 mNewPosition = 0;
244 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700245 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246
247 return NO_ERROR;
248}
249
250status_t AudioTrack::initCheck() const
251{
252 return mStatus;
253}
254
255// -------------------------------------------------------------------------
256
257uint32_t AudioTrack::latency() const
258{
259 return mLatency;
260}
261
262int AudioTrack::streamType() const
263{
264 return mStreamType;
265}
266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267int AudioTrack::format() const
268{
269 return mFormat;
270}
271
272int AudioTrack::channelCount() const
273{
274 return mChannelCount;
275}
276
277uint32_t AudioTrack::frameCount() const
278{
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700279 return mCblk->frameCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280}
281
282int AudioTrack::frameSize() const
283{
Eric Laurenta553c252009-07-17 12:17:14 -0700284 if (AudioSystem::isLinearPCM(mFormat)) {
285 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
286 } else {
287 return sizeof(uint8_t);
288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289}
290
291sp<IMemory>& AudioTrack::sharedBuffer()
292{
293 return mSharedBuffer;
294}
295
296// -------------------------------------------------------------------------
297
298void AudioTrack::start()
299{
300 sp<AudioTrackThread> t = mAudioTrackThread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700301 status_t status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302
303 LOGV("start %p", this);
304 if (t != 0) {
305 if (t->exitPending()) {
306 if (t->requestExitAndWait() == WOULD_BLOCK) {
307 LOGE("AudioTrack::start called from thread");
308 return;
309 }
310 }
311 t->mLock.lock();
312 }
313
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800314 AutoMutex lock(mLock);
315 if (mActive == 0) {
316 mActive = 1;
Eric Laurent059b4be2009-11-09 23:32:22 -0800317 mNewPosition = mCblk->server + mUpdatePeriod;
318 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
319 mCblk->waitTimeMs = 0;
Eric Laurent4712baa2010-09-30 16:12:31 -0700320 mCblk->flags &= ~CBLK_DISABLED_ON;
Eric Laurent059b4be2009-11-09 23:32:22 -0800321 if (t != 0) {
322 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
323 } else {
324 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
325 }
326
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700327 if (mCblk->flags & CBLK_INVALID_MSK) {
328 LOGW("start() track %p invalidated, creating a new one", this);
329 // no need to clear the invalid flag as this cblk will not be used anymore
330 // force new track creation
331 status = DEAD_OBJECT;
332 } else {
333 status = mAudioTrack->start();
334 }
Eric Laurentbda74692009-11-04 08:27:26 -0800335 if (status == DEAD_OBJECT) {
336 LOGV("start() dead IAudioTrack: creating a new one");
337 status = createTrack(mStreamType, mCblk->sampleRate, mFormat, mChannelCount,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700338 mFrameCount, mFlags, mSharedBuffer, getOutput(), false);
Eric Laurent49f02be2009-11-19 09:00:56 -0800339 if (status == NO_ERROR) {
340 status = mAudioTrack->start();
341 if (status == NO_ERROR) {
342 mNewPosition = mCblk->server + mUpdatePeriod;
343 }
344 }
Eric Laurent059b4be2009-11-09 23:32:22 -0800345 }
346 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800347 LOGV("start() failed");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800348 mActive = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -0800349 if (t != 0) {
350 t->requestExit();
351 } else {
352 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
353 }
Eric Laurentbda74692009-11-04 08:27:26 -0800354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 }
356
357 if (t != 0) {
358 t->mLock.unlock();
359 }
360}
361
362void AudioTrack::stop()
363{
364 sp<AudioTrackThread> t = mAudioTrackThread;
365
366 LOGV("stop %p", this);
367 if (t != 0) {
368 t->mLock.lock();
369 }
370
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800371 AutoMutex lock(mLock);
372 if (mActive == 1) {
373 mActive = 0;
Eric Laurentef028272009-04-21 07:56:33 -0700374 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 mAudioTrack->stop();
376 // Cancel loops (If we are in the middle of a loop, playback
377 // would not stop until loopCount reaches 0).
378 setLoop(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700379 // the playback head position will reset to 0, so if a marker is set, we need
380 // to activate it again
381 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 // Force flush if a shared buffer is used otherwise audioflinger
383 // will not stop before end of buffer is reached.
384 if (mSharedBuffer != 0) {
385 flush();
386 }
387 if (t != 0) {
388 t->requestExit();
389 } else {
390 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
391 }
392 }
393
394 if (t != 0) {
395 t->mLock.unlock();
396 }
397}
398
399bool AudioTrack::stopped() const
400{
401 return !mActive;
402}
403
404void AudioTrack::flush()
405{
406 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700407
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700408 // clear playback marker and periodic update counter
409 mMarkerPosition = 0;
410 mMarkerReached = false;
411 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 mAudioTrack->flush();
415 // Release AudioTrack callback thread in case it was waiting for new buffers
416 // in AudioTrack::obtainBuffer()
417 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 }
419}
420
421void AudioTrack::pause()
422{
423 LOGV("pause");
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800424 AutoMutex lock(mLock);
425 if (mActive == 1) {
426 mActive = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 mAudioTrack->pause();
428 }
429}
430
431void AudioTrack::mute(bool e)
432{
433 mAudioTrack->mute(e);
434 mMuted = e;
435}
436
437bool AudioTrack::muted() const
438{
439 return mMuted;
440}
441
Eric Laurent65b65452010-06-01 23:49:17 -0700442status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443{
Eric Laurent65b65452010-06-01 23:49:17 -0700444 if (left > 1.0f || right > 1.0f) {
445 return BAD_VALUE;
446 }
447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 mVolume[LEFT] = left;
449 mVolume[RIGHT] = right;
450
451 // write must be atomic
Eric Laurent65b65452010-06-01 23:49:17 -0700452 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
453
454 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455}
456
457void AudioTrack::getVolume(float* left, float* right)
458{
Eric Laurent65b65452010-06-01 23:49:17 -0700459 if (left != NULL) {
460 *left = mVolume[LEFT];
461 }
462 if (right != NULL) {
463 *right = mVolume[RIGHT];
464 }
465}
466
Eric Laurent7070b362010-07-16 07:43:46 -0700467status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurent65b65452010-06-01 23:49:17 -0700468{
Eric Laurent7070b362010-07-16 07:43:46 -0700469 LOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurent65b65452010-06-01 23:49:17 -0700470 if (level > 1.0f) {
471 return BAD_VALUE;
472 }
473
474 mSendLevel = level;
475
476 mCblk->sendLevel = uint16_t(level * 0x1000);
477
478 return NO_ERROR;
479}
480
Eric Laurent7070b362010-07-16 07:43:46 -0700481void AudioTrack::getAuxEffectSendLevel(float* level)
Eric Laurent65b65452010-06-01 23:49:17 -0700482{
483 if (level != NULL) {
484 *level = mSendLevel;
485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486}
487
Eric Laurent88e209d2009-07-07 07:10:45 -0700488status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489{
490 int afSamplingRate;
491
492 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700493 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 }
495 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700496 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497
Eric Laurent88e209d2009-07-07 07:10:45 -0700498 mCblk->sampleRate = rate;
499 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500}
501
502uint32_t AudioTrack::getSampleRate()
503{
Eric Laurent88e209d2009-07-07 07:10:45 -0700504 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505}
506
507status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
508{
509 audio_track_cblk_t* cblk = mCblk;
510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 Mutex::Autolock _l(cblk->lock);
512
513 if (loopCount == 0) {
514 cblk->loopStart = UINT_MAX;
515 cblk->loopEnd = UINT_MAX;
516 cblk->loopCount = 0;
517 mLoopCount = 0;
518 return NO_ERROR;
519 }
520
521 if (loopStart >= loopEnd ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700522 loopEnd - loopStart > cblk->frameCount) {
523 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 -0800524 return BAD_VALUE;
525 }
526
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700527 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700529 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532
533 cblk->loopStart = loopStart;
534 cblk->loopEnd = loopEnd;
535 cblk->loopCount = loopCount;
536 mLoopCount = loopCount;
537
538 return NO_ERROR;
539}
540
541status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
542{
543 if (loopStart != 0) {
544 *loopStart = mCblk->loopStart;
545 }
546 if (loopEnd != 0) {
547 *loopEnd = mCblk->loopEnd;
548 }
549 if (loopCount != 0) {
550 if (mCblk->loopCount < 0) {
551 *loopCount = -1;
552 } else {
553 *loopCount = mCblk->loopCount;
554 }
555 }
556
557 return NO_ERROR;
558}
559
560status_t AudioTrack::setMarkerPosition(uint32_t marker)
561{
562 if (mCbf == 0) return INVALID_OPERATION;
563
564 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700565 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566
567 return NO_ERROR;
568}
569
570status_t AudioTrack::getMarkerPosition(uint32_t *marker)
571{
572 if (marker == 0) return BAD_VALUE;
573
574 *marker = mMarkerPosition;
575
576 return NO_ERROR;
577}
578
579status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
580{
581 if (mCbf == 0) return INVALID_OPERATION;
582
583 uint32_t curPosition;
584 getPosition(&curPosition);
585 mNewPosition = curPosition + updatePeriod;
586 mUpdatePeriod = updatePeriod;
587
588 return NO_ERROR;
589}
590
591status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
592{
593 if (updatePeriod == 0) return BAD_VALUE;
594
595 *updatePeriod = mUpdatePeriod;
596
597 return NO_ERROR;
598}
599
600status_t AudioTrack::setPosition(uint32_t position)
601{
602 Mutex::Autolock _l(mCblk->lock);
603
604 if (!stopped()) return INVALID_OPERATION;
605
606 if (position > mCblk->user) return BAD_VALUE;
607
608 mCblk->server = position;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700609 mCblk->flags |= CBLK_FORCEREADY_ON;
Eric Laurenta553c252009-07-17 12:17:14 -0700610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 return NO_ERROR;
612}
613
614status_t AudioTrack::getPosition(uint32_t *position)
615{
616 if (position == 0) return BAD_VALUE;
617
618 *position = mCblk->server;
619
620 return NO_ERROR;
621}
622
623status_t AudioTrack::reload()
624{
625 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 flush();
628
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700629 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630
631 return NO_ERROR;
632}
633
Eric Laurenta553c252009-07-17 12:17:14 -0700634audio_io_handle_t AudioTrack::getOutput()
635{
636 return AudioSystem::getOutput((AudioSystem::stream_type)mStreamType,
637 mCblk->sampleRate, mFormat, mChannels, (AudioSystem::output_flags)mFlags);
638}
639
Eric Laurent65b65452010-06-01 23:49:17 -0700640int AudioTrack::getSessionId()
641{
642 return mSessionId;
643}
644
645status_t AudioTrack::attachAuxEffect(int effectId)
646{
Eric Laurent7070b362010-07-16 07:43:46 -0700647 LOGV("attachAuxEffect(%d)", effectId);
648 status_t status = mAudioTrack->attachAuxEffect(effectId);
649 if (status == NO_ERROR) {
650 mAuxEffectId = effectId;
651 }
652 return status;
Eric Laurent65b65452010-06-01 23:49:17 -0700653}
654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655// -------------------------------------------------------------------------
656
Eric Laurentbda74692009-11-04 08:27:26 -0800657status_t AudioTrack::createTrack(
658 int streamType,
659 uint32_t sampleRate,
660 int format,
661 int channelCount,
662 int frameCount,
663 uint32_t flags,
664 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700665 audio_io_handle_t output,
666 bool enforceFrameCount)
Eric Laurentbda74692009-11-04 08:27:26 -0800667{
668 status_t status;
669 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
670 if (audioFlinger == 0) {
671 LOGE("Could not get audioflinger");
672 return NO_INIT;
673 }
674
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700675 int afSampleRate;
676 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
677 return NO_INIT;
678 }
679 int afFrameCount;
680 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
681 return NO_INIT;
682 }
683 uint32_t afLatency;
684 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
685 return NO_INIT;
686 }
687
688 mNotificationFramesAct = mNotificationFramesReq;
689 if (!AudioSystem::isLinearPCM(format)) {
690 if (sharedBuffer != 0) {
691 frameCount = sharedBuffer->size();
692 }
693 } else {
694 // Ensure that buffer depth covers at least audio hardware latency
695 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
696 if (minBufCount < 2) minBufCount = 2;
697
698 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
699
700 if (sharedBuffer == 0) {
701 if (frameCount == 0) {
702 frameCount = minFrameCount;
703 }
704 if (mNotificationFramesAct == 0) {
705 mNotificationFramesAct = frameCount/2;
706 }
707 // Make sure that application is notified with sufficient margin
708 // before underrun
709 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
710 mNotificationFramesAct = frameCount/2;
711 }
712 if (frameCount < minFrameCount) {
713 if (enforceFrameCount) {
714 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
715 return BAD_VALUE;
716 } else {
717 frameCount = minFrameCount;
718 }
719 }
720 } else {
721 // Ensure that buffer alignment matches channelcount
722 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
723 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
724 return BAD_VALUE;
725 }
726 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
727 }
728 }
729
Eric Laurentbda74692009-11-04 08:27:26 -0800730 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
731 streamType,
732 sampleRate,
733 format,
734 channelCount,
735 frameCount,
736 ((uint16_t)flags) << 16,
737 sharedBuffer,
738 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700739 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800740 &status);
741
742 if (track == 0) {
743 LOGE("AudioFlinger could not create track, status: %d", status);
744 return status;
745 }
746 sp<IMemory> cblk = track->getCblk();
747 if (cblk == 0) {
748 LOGE("Could not get control block");
749 return NO_INIT;
750 }
751 mAudioTrack.clear();
752 mAudioTrack = track;
753 mCblkMemory.clear();
754 mCblkMemory = cblk;
755 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700756 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurentbda74692009-11-04 08:27:26 -0800757 if (sharedBuffer == 0) {
758 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
759 } else {
760 mCblk->buffers = sharedBuffer->pointer();
761 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700762 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800763 }
764
Eric Laurent65b65452010-06-01 23:49:17 -0700765 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
766 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent7070b362010-07-16 07:43:46 -0700767 mAudioTrack->attachAuxEffect(mAuxEffectId);
Eric Laurent49f02be2009-11-19 09:00:56 -0800768 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
769 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700770 mRemainingFrames = mNotificationFramesAct;
771 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800772 return NO_ERROR;
773}
774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
776{
777 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 status_t result;
779 audio_track_cblk_t* cblk = mCblk;
780 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700781 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782
783 audioBuffer->frameCount = 0;
784 audioBuffer->size = 0;
785
786 uint32_t framesAvail = cblk->framesAvailable();
787
788 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800789 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 goto start_loop_here;
791 while (framesAvail == 0) {
792 active = mActive;
793 if (UNLIKELY(!active)) {
794 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800795 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 return NO_MORE_BUFFERS;
797 }
Eric Laurentbda74692009-11-04 08:27:26 -0800798 if (UNLIKELY(!waitCount)) {
799 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800801 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700802 if (!(cblk->flags & CBLK_INVALID_MSK)) {
803 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
804 }
805 if (cblk->flags & CBLK_INVALID_MSK) {
806 LOGW("obtainBuffer() track %p invalidated, creating a new one", this);
807 // no need to clear the invalid flag as this cblk will not be used anymore
808 cblk->lock.unlock();
809 goto create_new_track;
810 }
Eric Laurenta553c252009-07-17 12:17:14 -0700811 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700812 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
814 // timing out when a loop has been set and we have already written upto loop end
815 // is a normal condition: no need to wake AudioFlinger up.
816 if (cblk->user < cblk->loopEnd) {
817 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
818 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700819 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800821 result = mAudioTrack->start();
822 if (result == DEAD_OBJECT) {
823 LOGW("obtainBuffer() dead IAudioTrack: creating a new one");
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700824create_new_track:
Eric Laurentbda74692009-11-04 08:27:26 -0800825 result = createTrack(mStreamType, cblk->sampleRate, mFormat, mChannelCount,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700826 mFrameCount, mFlags, mSharedBuffer, getOutput(), false);
Eric Laurentbda74692009-11-04 08:27:26 -0800827 if (result == NO_ERROR) {
828 cblk = mCblk;
829 cblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
Eric Laurent49f02be2009-11-19 09:00:56 -0800830 mAudioTrack->start();
Eric Laurentbda74692009-11-04 08:27:26 -0800831 }
832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835 cblk->waitTimeMs = 0;
836 }
Eric Laurenta553c252009-07-17 12:17:14 -0700837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800839 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 return TIMED_OUT;
841 }
842 }
843 // read the server count again
844 start_loop_here:
845 framesAvail = cblk->framesAvailable_l();
846 }
Eric Laurentbda74692009-11-04 08:27:26 -0800847 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
849
Eric Laurent4712baa2010-09-30 16:12:31 -0700850 // restart track if it was disabled by audioflinger due to previous underrun
851 if (cblk->flags & CBLK_DISABLED_MSK) {
852 cblk->flags &= ~CBLK_DISABLED_ON;
853 LOGW("obtainBuffer() track %p disabled, restarting", this);
854 mAudioTrack->start();
855 }
856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 if (framesReq > framesAvail) {
860 framesReq = framesAvail;
861 }
862
863 uint32_t u = cblk->user;
864 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
865
866 if (u + framesReq > bufferEnd) {
867 framesReq = bufferEnd - u;
868 }
869
Eric Laurenta553c252009-07-17 12:17:14 -0700870 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
871 audioBuffer->channelCount = mChannelCount;
872 audioBuffer->frameCount = framesReq;
873 audioBuffer->size = framesReq * cblk->frameSize;
874 if (AudioSystem::isLinearPCM(mFormat)) {
875 audioBuffer->format = AudioSystem::PCM_16_BIT;
876 } else {
877 audioBuffer->format = mFormat;
878 }
879 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 active = mActive;
881 return active ? status_t(NO_ERROR) : status_t(STOPPED);
882}
883
884void AudioTrack::releaseBuffer(Buffer* audioBuffer)
885{
886 audio_track_cblk_t* cblk = mCblk;
887 cblk->stepUser(audioBuffer->frameCount);
888}
889
890// -------------------------------------------------------------------------
891
892ssize_t AudioTrack::write(const void* buffer, size_t userSize)
893{
894
895 if (mSharedBuffer != 0) return INVALID_OPERATION;
896
897 if (ssize_t(userSize) < 0) {
898 // sanity-check. user is most-likely passing an error code.
899 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
900 buffer, userSize, userSize);
901 return BAD_VALUE;
902 }
903
904 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
905
906 ssize_t written = 0;
907 const int8_t *src = (const int8_t *)buffer;
908 Buffer audioBuffer;
909
910 do {
Eric Laurenta553c252009-07-17 12:17:14 -0700911 audioBuffer.frameCount = userSize/frameSize();
912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 // Calling obtainBuffer() with a negative wait count causes
914 // an (almost) infinite wait time.
915 status_t err = obtainBuffer(&audioBuffer, -1);
916 if (err < 0) {
917 // out of buffers, return #bytes written
918 if (err == status_t(NO_MORE_BUFFERS))
919 break;
920 return ssize_t(err);
921 }
922
923 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700924
Eric Laurent28ad42b2009-08-04 10:42:26 -0700925 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 // Divide capacity by 2 to take expansion into account
927 toWrite = audioBuffer.size>>1;
928 // 8 to 16 bit conversion
929 int count = toWrite;
930 int16_t *dst = (int16_t *)(audioBuffer.i8);
931 while(count--) {
932 *dst++ = (int16_t)(*src++^0x80) << 8;
933 }
Eric Laurent28ad42b2009-08-04 10:42:26 -0700934 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 toWrite = audioBuffer.size;
936 memcpy(audioBuffer.i8, src, toWrite);
937 src += toWrite;
938 }
939 userSize -= toWrite;
940 written += toWrite;
941
942 releaseBuffer(&audioBuffer);
943 } while (userSize);
944
945 return written;
946}
947
948// -------------------------------------------------------------------------
949
950bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
951{
952 Buffer audioBuffer;
953 uint32_t frames;
954 size_t writtenSize;
955
956 // Manage underrun callback
957 if (mActive && (mCblk->framesReady() == 0)) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700958 LOGV("Underrun user: %x, server: %x, flags %04x", mCblk->user, mCblk->server, mCblk->flags);
959 if ((mCblk->flags & CBLK_UNDERRUN_MSK) == CBLK_UNDERRUN_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 mCbf(EVENT_UNDERRUN, mUserData, 0);
961 if (mCblk->server == mCblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -0700962 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700964 mCblk->flags |= CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 if (mSharedBuffer != 0) return false;
966 }
967 }
Eric Laurenta553c252009-07-17 12:17:14 -0700968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 // Manage loop end callback
970 while (mLoopCount > mCblk->loopCount) {
971 int loopCount = -1;
972 mLoopCount--;
973 if (mLoopCount >= 0) loopCount = mLoopCount;
974
975 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
976 }
977
978 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700979 if (!mMarkerReached && (mMarkerPosition > 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 if (mCblk->server >= mMarkerPosition) {
981 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700982 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 }
984 }
985
986 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -0700987 if (mUpdatePeriod > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 while (mCblk->server >= mNewPosition) {
989 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
990 mNewPosition += mUpdatePeriod;
991 }
992 }
993
994 // If Shared buffer is used, no data is requested from client.
995 if (mSharedBuffer != 0) {
996 frames = 0;
997 } else {
998 frames = mRemainingFrames;
999 }
1000
1001 do {
1002
1003 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -07001004
1005 // Calling obtainBuffer() with a wait count of 1
1006 // limits wait time to WAIT_PERIOD_MS. This prevents from being
1007 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 status_t err = obtainBuffer(&audioBuffer, 1);
1009 if (err < NO_ERROR) {
1010 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -07001011 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 -08001012 return false;
1013 }
1014 break;
1015 }
1016 if (err == status_t(STOPPED)) return false;
1017
1018 // Divide buffer size by 2 to take into account the expansion
1019 // due to 8 to 16 bit conversion: the callback must fill only half
1020 // of the destination buffer
Eric Laurent28ad42b2009-08-04 10:42:26 -07001021 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 audioBuffer.size >>= 1;
1023 }
1024
1025 size_t reqSize = audioBuffer.size;
1026 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1027 writtenSize = audioBuffer.size;
1028
1029 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001030 if (ssize_t(writtenSize) <= 0) {
1031 // The callback is done filling buffers
1032 // Keep this thread going to handle timed events and
1033 // still try to get more data in intervals of WAIT_PERIOD_MS
1034 // but don't just loop and block the CPU, so wait
1035 usleep(WAIT_PERIOD_MS*1000);
1036 break;
1037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 if (writtenSize > reqSize) writtenSize = reqSize;
1039
Eric Laurent28ad42b2009-08-04 10:42:26 -07001040 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 // 8 to 16 bit conversion
1042 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1043 int count = writtenSize;
1044 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1045 while(count--) {
1046 *dst-- = (int16_t)(*src--^0x80) << 8;
1047 }
1048 writtenSize <<= 1;
1049 }
1050
1051 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001052 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1053 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1054 // 16 bit.
1055 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 frames -= audioBuffer.frameCount;
1058
1059 releaseBuffer(&audioBuffer);
1060 }
1061 while (frames);
1062
1063 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001064 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 } else {
1066 mRemainingFrames = frames;
1067 }
1068 return true;
1069}
1070
1071status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1072{
1073
1074 const size_t SIZE = 256;
1075 char buffer[SIZE];
1076 String8 result;
1077
1078 result.append(" AudioTrack::dump\n");
1079 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1080 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001081 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 -08001082 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001083 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 -08001084 result.append(buffer);
1085 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1086 result.append(buffer);
1087 ::write(fd, result.string(), result.size());
1088 return NO_ERROR;
1089}
1090
1091// =========================================================================
1092
1093AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1094 : Thread(bCanCallJava), mReceiver(receiver)
1095{
1096}
1097
1098bool AudioTrack::AudioTrackThread::threadLoop()
1099{
1100 return mReceiver.processAudioBuffer(this);
1101}
1102
1103status_t AudioTrack::AudioTrackThread::readyToRun()
1104{
1105 return NO_ERROR;
1106}
1107
1108void AudioTrack::AudioTrackThread::onFirstRef()
1109{
1110}
1111
1112// =========================================================================
1113
1114audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001115 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1116 userBase(0), serverBase(0), buffers(0), frameCount(0),
1117 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurent65b65452010-06-01 23:49:17 -07001118 flags(0), sendLevel(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119{
1120}
1121
1122uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1123{
1124 uint32_t u = this->user;
1125
1126 u += frameCount;
1127 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001128 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1130 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1131 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1132 }
1133 } else if (u > this->server) {
1134 LOGW("stepServer occured after track reset");
1135 u = this->server;
1136 }
1137
1138 if (u >= userBase + this->frameCount) {
1139 userBase += this->frameCount;
1140 }
1141
1142 this->user = u;
1143
1144 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001145 flags &= ~CBLK_UNDERRUN_MSK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146
1147 return u;
1148}
1149
1150bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1151{
1152 // the code below simulates lock-with-timeout
1153 // we MUST do this to protect the AudioFlinger server
1154 // as this lock is shared with the client.
1155 status_t err;
1156
1157 err = lock.tryLock();
1158 if (err == -EBUSY) { // just wait a bit
1159 usleep(1000);
1160 err = lock.tryLock();
1161 }
1162 if (err != NO_ERROR) {
1163 // probably, the client just died.
1164 return false;
1165 }
1166
1167 uint32_t s = this->server;
1168
1169 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001170 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 // Mark that we have read the first buffer so that next time stepUser() is called
1172 // we switch to normal obtainBuffer() timeout period
1173 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001174 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 // It is possible that we receive a flush()
1177 // while the mixer is processing a block: in this case,
1178 // stepServer() is called After the flush() has reset u & s and
1179 // we have s > u
1180 if (s > this->user) {
1181 LOGW("stepServer occured after track reset");
1182 s = this->user;
1183 }
1184 }
1185
1186 if (s >= loopEnd) {
1187 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1188 s = loopStart;
1189 if (--loopCount == 0) {
1190 loopEnd = UINT_MAX;
1191 loopStart = UINT_MAX;
1192 }
1193 }
1194 if (s >= serverBase + this->frameCount) {
1195 serverBase += this->frameCount;
1196 }
1197
1198 this->server = s;
1199
1200 cv.signal();
1201 lock.unlock();
1202 return true;
1203}
1204
1205void* audio_track_cblk_t::buffer(uint32_t offset) const
1206{
Eric Laurenta553c252009-07-17 12:17:14 -07001207 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208}
1209
1210uint32_t audio_track_cblk_t::framesAvailable()
1211{
1212 Mutex::Autolock _l(lock);
1213 return framesAvailable_l();
1214}
1215
1216uint32_t audio_track_cblk_t::framesAvailable_l()
1217{
1218 uint32_t u = this->user;
1219 uint32_t s = this->server;
1220
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001221 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 uint32_t limit = (s < loopStart) ? s : loopStart;
1223 return limit + frameCount - u;
1224 } else {
1225 return frameCount + u - s;
1226 }
1227}
1228
1229uint32_t audio_track_cblk_t::framesReady()
1230{
1231 uint32_t u = this->user;
1232 uint32_t s = this->server;
1233
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001234 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 if (u < loopEnd) {
1236 return u - s;
1237 } else {
1238 Mutex::Autolock _l(lock);
1239 if (loopCount >= 0) {
1240 return (loopEnd - loopStart)*loopCount + u - s;
1241 } else {
1242 return UINT_MAX;
1243 }
1244 }
1245 } else {
1246 return s - u;
1247 }
1248}
1249
1250// -------------------------------------------------------------------------
1251
1252}; // namespace android
1253