blob: 2118f8f350c24b3eaa5da37db93433427225cae4 [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>
38#include <cutils/atomic.h>
39
40#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
41#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
42
43namespace android {
Chia-chi Yehbd240c22010-06-16 06:33:13 +080044// ---------------------------------------------------------------------------
45
46// static
47status_t AudioTrack::getMinFrameCount(
48 int* frameCount,
49 int streamType,
50 uint32_t sampleRate)
51{
52 int afSampleRate;
53 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
54 return NO_INIT;
55 }
56 int afFrameCount;
57 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
58 return NO_INIT;
59 }
60 uint32_t afLatency;
61 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
62 return NO_INIT;
63 }
64
65 // Ensure that buffer depth covers at least audio hardware latency
66 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
67 if (minBufCount < 2) minBufCount = 2;
68
69 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
70 afFrameCount * minBufCount * sampleRate / afSampleRate;
71 return NO_ERROR;
72}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
74// ---------------------------------------------------------------------------
75
76AudioTrack::AudioTrack()
77 : mStatus(NO_INIT)
78{
79}
80
81AudioTrack::AudioTrack(
82 int streamType,
83 uint32_t sampleRate,
84 int format,
Eric Laurenta553c252009-07-17 12:17:14 -070085 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 int frameCount,
87 uint32_t flags,
88 callback_t cbf,
89 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -070090 int notificationFrames,
91 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 : mStatus(NO_INIT)
93{
Eric Laurenta553c252009-07-17 12:17:14 -070094 mStatus = set(streamType, sampleRate, format, channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 frameCount, flags, cbf, user, notificationFrames, 0);
96}
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,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 0, flags, cbf, user, notificationFrames, sharedBuffer);
113}
114
115AudioTrack::~AudioTrack()
116{
117 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
118
119 if (mStatus == NO_ERROR) {
120 // Make sure that callback function exits in the case where
121 // it is looping on buffer full condition in obtainBuffer().
122 // Otherwise the callback thread will never exit.
123 stop();
124 if (mAudioTrackThread != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 mAudioTrackThread->requestExitAndWait();
126 mAudioTrackThread.clear();
127 }
128 mAudioTrack.clear();
129 IPCThreadState::self()->flushCommands();
130 }
131}
132
133status_t AudioTrack::set(
134 int streamType,
135 uint32_t sampleRate,
136 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700137 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 int frameCount,
139 uint32_t flags,
140 callback_t cbf,
141 void* user,
142 int notificationFrames,
143 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -0700144 bool threadCanCallJava,
145 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146{
147
148 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
149
Eric Laurentef028272009-04-21 07:56:33 -0700150 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 LOGE("Track already in use");
152 return INVALID_OPERATION;
153 }
154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 int afSampleRate;
156 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
157 return NO_INIT;
158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 uint32_t afLatency;
160 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
161 return NO_INIT;
162 }
163
164 // handle default values first.
165 if (streamType == AudioSystem::DEFAULT) {
166 streamType = AudioSystem::MUSIC;
167 }
168 if (sampleRate == 0) {
169 sampleRate = afSampleRate;
170 }
171 // these below should probably come from the audioFlinger too...
172 if (format == 0) {
173 format = AudioSystem::PCM_16_BIT;
174 }
Eric Laurenta553c252009-07-17 12:17:14 -0700175 if (channels == 0) {
176 channels = AudioSystem::CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 }
178
179 // validate parameters
Eric Laurenta553c252009-07-17 12:17:14 -0700180 if (!AudioSystem::isValidFormat(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 LOGE("Invalid format");
182 return BAD_VALUE;
183 }
Eric Laurenta553c252009-07-17 12:17:14 -0700184
185 // force direct flag if format is not linear PCM
186 if (!AudioSystem::isLinearPCM(format)) {
187 flags |= AudioSystem::OUTPUT_FLAG_DIRECT;
188 }
189
190 if (!AudioSystem::isOutputChannel(channels)) {
191 LOGE("Invalid channel mask");
192 return BAD_VALUE;
193 }
194 uint32_t channelCount = AudioSystem::popCount(channels);
195
196 audio_io_handle_t output = AudioSystem::getOutput((AudioSystem::stream_type)streamType,
197 sampleRate, format, channels, (AudioSystem::output_flags)flags);
198
199 if (output == 0) {
200 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 return BAD_VALUE;
202 }
203
Eric Laurentbda74692009-11-04 08:27:26 -0800204 mVolume[LEFT] = 1.0f;
205 mVolume[RIGHT] = 1.0f;
Eric Laurent65b65452010-06-01 23:49:17 -0700206 mSendLevel = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700207 mFrameCount = frameCount;
208 mNotificationFramesReq = notificationFrames;
Eric Laurent65b65452010-06-01 23:49:17 -0700209 mSessionId = sessionId;
210
Eric Laurentbda74692009-11-04 08:27:26 -0800211 // create the IAudioTrack
212 status_t status = createTrack(streamType, sampleRate, format, channelCount,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700213 frameCount, flags, sharedBuffer, output, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Eric Laurentbda74692009-11-04 08:27:26 -0800215 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 return status;
217 }
Eric Laurentbda74692009-11-04 08:27:26 -0800218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 if (cbf != 0) {
220 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
221 if (mAudioTrackThread == 0) {
222 LOGE("Could not create callback thread");
223 return NO_INIT;
224 }
225 }
226
227 mStatus = NO_ERROR;
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 mStreamType = streamType;
230 mFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -0700231 mChannels = channels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 mChannelCount = channelCount;
233 mSharedBuffer = sharedBuffer;
234 mMuted = false;
235 mActive = 0;
236 mCbf = cbf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 mUserData = user;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 mLoopCount = 0;
239 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700240 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 mNewPosition = 0;
242 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700243 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
245 return NO_ERROR;
246}
247
248status_t AudioTrack::initCheck() const
249{
250 return mStatus;
251}
252
253// -------------------------------------------------------------------------
254
255uint32_t AudioTrack::latency() const
256{
257 return mLatency;
258}
259
260int AudioTrack::streamType() const
261{
262 return mStreamType;
263}
264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265int AudioTrack::format() const
266{
267 return mFormat;
268}
269
270int AudioTrack::channelCount() const
271{
272 return mChannelCount;
273}
274
275uint32_t AudioTrack::frameCount() const
276{
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700277 return mCblk->frameCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278}
279
280int AudioTrack::frameSize() const
281{
Eric Laurenta553c252009-07-17 12:17:14 -0700282 if (AudioSystem::isLinearPCM(mFormat)) {
283 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
284 } else {
285 return sizeof(uint8_t);
286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287}
288
289sp<IMemory>& AudioTrack::sharedBuffer()
290{
291 return mSharedBuffer;
292}
293
294// -------------------------------------------------------------------------
295
296void AudioTrack::start()
297{
298 sp<AudioTrackThread> t = mAudioTrackThread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700299 status_t status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300
301 LOGV("start %p", this);
302 if (t != 0) {
303 if (t->exitPending()) {
304 if (t->requestExitAndWait() == WOULD_BLOCK) {
305 LOGE("AudioTrack::start called from thread");
306 return;
307 }
308 }
309 t->mLock.lock();
310 }
311
312 if (android_atomic_or(1, &mActive) == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -0800313 mNewPosition = mCblk->server + mUpdatePeriod;
314 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
315 mCblk->waitTimeMs = 0;
316 if (t != 0) {
317 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
318 } else {
319 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
320 }
321
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700322 if (mCblk->flags & CBLK_INVALID_MSK) {
323 LOGW("start() track %p invalidated, creating a new one", this);
324 // no need to clear the invalid flag as this cblk will not be used anymore
325 // force new track creation
326 status = DEAD_OBJECT;
327 } else {
328 status = mAudioTrack->start();
329 }
Eric Laurentbda74692009-11-04 08:27:26 -0800330 if (status == DEAD_OBJECT) {
331 LOGV("start() dead IAudioTrack: creating a new one");
332 status = createTrack(mStreamType, mCblk->sampleRate, mFormat, mChannelCount,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700333 mFrameCount, mFlags, mSharedBuffer, getOutput(), false);
Eric Laurent49f02be2009-11-19 09:00:56 -0800334 if (status == NO_ERROR) {
335 status = mAudioTrack->start();
336 if (status == NO_ERROR) {
337 mNewPosition = mCblk->server + mUpdatePeriod;
338 }
339 }
Eric Laurent059b4be2009-11-09 23:32:22 -0800340 }
341 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800342 LOGV("start() failed");
343 android_atomic_and(~1, &mActive);
Eric Laurent059b4be2009-11-09 23:32:22 -0800344 if (t != 0) {
345 t->requestExit();
346 } else {
347 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
348 }
Eric Laurentbda74692009-11-04 08:27:26 -0800349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 }
351
352 if (t != 0) {
353 t->mLock.unlock();
354 }
355}
356
357void AudioTrack::stop()
358{
359 sp<AudioTrackThread> t = mAudioTrackThread;
360
361 LOGV("stop %p", this);
362 if (t != 0) {
363 t->mLock.lock();
364 }
365
366 if (android_atomic_and(~1, &mActive) == 1) {
Eric Laurentef028272009-04-21 07:56:33 -0700367 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 mAudioTrack->stop();
369 // Cancel loops (If we are in the middle of a loop, playback
370 // would not stop until loopCount reaches 0).
371 setLoop(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700372 // the playback head position will reset to 0, so if a marker is set, we need
373 // to activate it again
374 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 // Force flush if a shared buffer is used otherwise audioflinger
376 // will not stop before end of buffer is reached.
377 if (mSharedBuffer != 0) {
378 flush();
379 }
380 if (t != 0) {
381 t->requestExit();
382 } else {
383 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
384 }
385 }
386
387 if (t != 0) {
388 t->mLock.unlock();
389 }
390}
391
392bool AudioTrack::stopped() const
393{
394 return !mActive;
395}
396
397void AudioTrack::flush()
398{
399 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700400
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700401 // clear playback marker and periodic update counter
402 mMarkerPosition = 0;
403 mMarkerReached = false;
404 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406
407 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 mAudioTrack->flush();
409 // Release AudioTrack callback thread in case it was waiting for new buffers
410 // in AudioTrack::obtainBuffer()
411 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 }
413}
414
415void AudioTrack::pause()
416{
417 LOGV("pause");
418 if (android_atomic_and(~1, &mActive) == 1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 mAudioTrack->pause();
420 }
421}
422
423void AudioTrack::mute(bool e)
424{
425 mAudioTrack->mute(e);
426 mMuted = e;
427}
428
429bool AudioTrack::muted() const
430{
431 return mMuted;
432}
433
Eric Laurent65b65452010-06-01 23:49:17 -0700434status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435{
Eric Laurent65b65452010-06-01 23:49:17 -0700436 if (left > 1.0f || right > 1.0f) {
437 return BAD_VALUE;
438 }
439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 mVolume[LEFT] = left;
441 mVolume[RIGHT] = right;
442
443 // write must be atomic
Eric Laurent65b65452010-06-01 23:49:17 -0700444 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
445
446 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447}
448
449void AudioTrack::getVolume(float* left, float* right)
450{
Eric Laurent65b65452010-06-01 23:49:17 -0700451 if (left != NULL) {
452 *left = mVolume[LEFT];
453 }
454 if (right != NULL) {
455 *right = mVolume[RIGHT];
456 }
457}
458
459status_t AudioTrack::setSendLevel(float level)
460{
461 if (level > 1.0f) {
462 return BAD_VALUE;
463 }
464
465 mSendLevel = level;
466
467 mCblk->sendLevel = uint16_t(level * 0x1000);
468
469 return NO_ERROR;
470}
471
472void AudioTrack::getSendLevel(float* level)
473{
474 if (level != NULL) {
475 *level = mSendLevel;
476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477}
478
Eric Laurent88e209d2009-07-07 07:10:45 -0700479status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480{
481 int afSamplingRate;
482
483 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700484 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 }
486 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700487 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488
Eric Laurent88e209d2009-07-07 07:10:45 -0700489 mCblk->sampleRate = rate;
490 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491}
492
493uint32_t AudioTrack::getSampleRate()
494{
Eric Laurent88e209d2009-07-07 07:10:45 -0700495 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496}
497
498status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
499{
500 audio_track_cblk_t* cblk = mCblk;
501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 Mutex::Autolock _l(cblk->lock);
503
504 if (loopCount == 0) {
505 cblk->loopStart = UINT_MAX;
506 cblk->loopEnd = UINT_MAX;
507 cblk->loopCount = 0;
508 mLoopCount = 0;
509 return NO_ERROR;
510 }
511
512 if (loopStart >= loopEnd ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700513 loopEnd - loopStart > cblk->frameCount) {
514 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 -0800515 return BAD_VALUE;
516 }
517
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700518 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700520 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523
524 cblk->loopStart = loopStart;
525 cblk->loopEnd = loopEnd;
526 cblk->loopCount = loopCount;
527 mLoopCount = loopCount;
528
529 return NO_ERROR;
530}
531
532status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
533{
534 if (loopStart != 0) {
535 *loopStart = mCblk->loopStart;
536 }
537 if (loopEnd != 0) {
538 *loopEnd = mCblk->loopEnd;
539 }
540 if (loopCount != 0) {
541 if (mCblk->loopCount < 0) {
542 *loopCount = -1;
543 } else {
544 *loopCount = mCblk->loopCount;
545 }
546 }
547
548 return NO_ERROR;
549}
550
551status_t AudioTrack::setMarkerPosition(uint32_t marker)
552{
553 if (mCbf == 0) return INVALID_OPERATION;
554
555 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700556 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557
558 return NO_ERROR;
559}
560
561status_t AudioTrack::getMarkerPosition(uint32_t *marker)
562{
563 if (marker == 0) return BAD_VALUE;
564
565 *marker = mMarkerPosition;
566
567 return NO_ERROR;
568}
569
570status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
571{
572 if (mCbf == 0) return INVALID_OPERATION;
573
574 uint32_t curPosition;
575 getPosition(&curPosition);
576 mNewPosition = curPosition + updatePeriod;
577 mUpdatePeriod = updatePeriod;
578
579 return NO_ERROR;
580}
581
582status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
583{
584 if (updatePeriod == 0) return BAD_VALUE;
585
586 *updatePeriod = mUpdatePeriod;
587
588 return NO_ERROR;
589}
590
591status_t AudioTrack::setPosition(uint32_t position)
592{
593 Mutex::Autolock _l(mCblk->lock);
594
595 if (!stopped()) return INVALID_OPERATION;
596
597 if (position > mCblk->user) return BAD_VALUE;
598
599 mCblk->server = position;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700600 mCblk->flags |= CBLK_FORCEREADY_ON;
Eric Laurenta553c252009-07-17 12:17:14 -0700601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 return NO_ERROR;
603}
604
605status_t AudioTrack::getPosition(uint32_t *position)
606{
607 if (position == 0) return BAD_VALUE;
608
609 *position = mCblk->server;
610
611 return NO_ERROR;
612}
613
614status_t AudioTrack::reload()
615{
616 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 flush();
619
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700620 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621
622 return NO_ERROR;
623}
624
Eric Laurenta553c252009-07-17 12:17:14 -0700625audio_io_handle_t AudioTrack::getOutput()
626{
627 return AudioSystem::getOutput((AudioSystem::stream_type)mStreamType,
628 mCblk->sampleRate, mFormat, mChannels, (AudioSystem::output_flags)mFlags);
629}
630
Eric Laurent65b65452010-06-01 23:49:17 -0700631int AudioTrack::getSessionId()
632{
633 return mSessionId;
634}
635
636status_t AudioTrack::attachAuxEffect(int effectId)
637{
638 return mAudioTrack->attachAuxEffect(effectId);
639}
640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641// -------------------------------------------------------------------------
642
Eric Laurentbda74692009-11-04 08:27:26 -0800643status_t AudioTrack::createTrack(
644 int streamType,
645 uint32_t sampleRate,
646 int format,
647 int channelCount,
648 int frameCount,
649 uint32_t flags,
650 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700651 audio_io_handle_t output,
652 bool enforceFrameCount)
Eric Laurentbda74692009-11-04 08:27:26 -0800653{
654 status_t status;
655 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
656 if (audioFlinger == 0) {
657 LOGE("Could not get audioflinger");
658 return NO_INIT;
659 }
660
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700661 int afSampleRate;
662 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
663 return NO_INIT;
664 }
665 int afFrameCount;
666 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
667 return NO_INIT;
668 }
669 uint32_t afLatency;
670 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
671 return NO_INIT;
672 }
673
674 mNotificationFramesAct = mNotificationFramesReq;
675 if (!AudioSystem::isLinearPCM(format)) {
676 if (sharedBuffer != 0) {
677 frameCount = sharedBuffer->size();
678 }
679 } else {
680 // Ensure that buffer depth covers at least audio hardware latency
681 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
682 if (minBufCount < 2) minBufCount = 2;
683
684 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
685
686 if (sharedBuffer == 0) {
687 if (frameCount == 0) {
688 frameCount = minFrameCount;
689 }
690 if (mNotificationFramesAct == 0) {
691 mNotificationFramesAct = frameCount/2;
692 }
693 // Make sure that application is notified with sufficient margin
694 // before underrun
695 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
696 mNotificationFramesAct = frameCount/2;
697 }
698 if (frameCount < minFrameCount) {
699 if (enforceFrameCount) {
700 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
701 return BAD_VALUE;
702 } else {
703 frameCount = minFrameCount;
704 }
705 }
706 } else {
707 // Ensure that buffer alignment matches channelcount
708 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
709 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
710 return BAD_VALUE;
711 }
712 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
713 }
714 }
715
Eric Laurentbda74692009-11-04 08:27:26 -0800716 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
717 streamType,
718 sampleRate,
719 format,
720 channelCount,
721 frameCount,
722 ((uint16_t)flags) << 16,
723 sharedBuffer,
724 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700725 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800726 &status);
727
728 if (track == 0) {
729 LOGE("AudioFlinger could not create track, status: %d", status);
730 return status;
731 }
732 sp<IMemory> cblk = track->getCblk();
733 if (cblk == 0) {
734 LOGE("Could not get control block");
735 return NO_INIT;
736 }
737 mAudioTrack.clear();
738 mAudioTrack = track;
739 mCblkMemory.clear();
740 mCblkMemory = cblk;
741 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700742 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurentbda74692009-11-04 08:27:26 -0800743 if (sharedBuffer == 0) {
744 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
745 } else {
746 mCblk->buffers = sharedBuffer->pointer();
747 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700748 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800749 }
750
Eric Laurent65b65452010-06-01 23:49:17 -0700751 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
752 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent49f02be2009-11-19 09:00:56 -0800753 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
754 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700755 mRemainingFrames = mNotificationFramesAct;
756 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800757 return NO_ERROR;
758}
759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
761{
762 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 status_t result;
764 audio_track_cblk_t* cblk = mCblk;
765 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700766 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767
768 audioBuffer->frameCount = 0;
769 audioBuffer->size = 0;
770
771 uint32_t framesAvail = cblk->framesAvailable();
772
773 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800774 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 goto start_loop_here;
776 while (framesAvail == 0) {
777 active = mActive;
778 if (UNLIKELY(!active)) {
779 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800780 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 return NO_MORE_BUFFERS;
782 }
Eric Laurentbda74692009-11-04 08:27:26 -0800783 if (UNLIKELY(!waitCount)) {
784 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800786 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700787 if (!(cblk->flags & CBLK_INVALID_MSK)) {
788 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
789 }
790 if (cblk->flags & CBLK_INVALID_MSK) {
791 LOGW("obtainBuffer() track %p invalidated, creating a new one", this);
792 // no need to clear the invalid flag as this cblk will not be used anymore
793 cblk->lock.unlock();
794 goto create_new_track;
795 }
Eric Laurenta553c252009-07-17 12:17:14 -0700796 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700797 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
799 // timing out when a loop has been set and we have already written upto loop end
800 // is a normal condition: no need to wake AudioFlinger up.
801 if (cblk->user < cblk->loopEnd) {
802 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
803 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700804 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800806 result = mAudioTrack->start();
807 if (result == DEAD_OBJECT) {
808 LOGW("obtainBuffer() dead IAudioTrack: creating a new one");
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700809create_new_track:
Eric Laurentbda74692009-11-04 08:27:26 -0800810 result = createTrack(mStreamType, cblk->sampleRate, mFormat, mChannelCount,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700811 mFrameCount, mFlags, mSharedBuffer, getOutput(), false);
Eric Laurentbda74692009-11-04 08:27:26 -0800812 if (result == NO_ERROR) {
813 cblk = mCblk;
814 cblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
Eric Laurent49f02be2009-11-19 09:00:56 -0800815 mAudioTrack->start();
Eric Laurentbda74692009-11-04 08:27:26 -0800816 }
817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 }
820 cblk->waitTimeMs = 0;
821 }
Eric Laurenta553c252009-07-17 12:17:14 -0700822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800824 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 return TIMED_OUT;
826 }
827 }
828 // read the server count again
829 start_loop_here:
830 framesAvail = cblk->framesAvailable_l();
831 }
Eric Laurentbda74692009-11-04 08:27:26 -0800832 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
834
835 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 if (framesReq > framesAvail) {
838 framesReq = framesAvail;
839 }
840
841 uint32_t u = cblk->user;
842 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
843
844 if (u + framesReq > bufferEnd) {
845 framesReq = bufferEnd - u;
846 }
847
Eric Laurenta553c252009-07-17 12:17:14 -0700848 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
849 audioBuffer->channelCount = mChannelCount;
850 audioBuffer->frameCount = framesReq;
851 audioBuffer->size = framesReq * cblk->frameSize;
852 if (AudioSystem::isLinearPCM(mFormat)) {
853 audioBuffer->format = AudioSystem::PCM_16_BIT;
854 } else {
855 audioBuffer->format = mFormat;
856 }
857 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 active = mActive;
859 return active ? status_t(NO_ERROR) : status_t(STOPPED);
860}
861
862void AudioTrack::releaseBuffer(Buffer* audioBuffer)
863{
864 audio_track_cblk_t* cblk = mCblk;
865 cblk->stepUser(audioBuffer->frameCount);
866}
867
868// -------------------------------------------------------------------------
869
870ssize_t AudioTrack::write(const void* buffer, size_t userSize)
871{
872
873 if (mSharedBuffer != 0) return INVALID_OPERATION;
874
875 if (ssize_t(userSize) < 0) {
876 // sanity-check. user is most-likely passing an error code.
877 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
878 buffer, userSize, userSize);
879 return BAD_VALUE;
880 }
881
882 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
883
884 ssize_t written = 0;
885 const int8_t *src = (const int8_t *)buffer;
886 Buffer audioBuffer;
887
888 do {
Eric Laurenta553c252009-07-17 12:17:14 -0700889 audioBuffer.frameCount = userSize/frameSize();
890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 // Calling obtainBuffer() with a negative wait count causes
892 // an (almost) infinite wait time.
893 status_t err = obtainBuffer(&audioBuffer, -1);
894 if (err < 0) {
895 // out of buffers, return #bytes written
896 if (err == status_t(NO_MORE_BUFFERS))
897 break;
898 return ssize_t(err);
899 }
900
901 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700902
Eric Laurent28ad42b2009-08-04 10:42:26 -0700903 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 // Divide capacity by 2 to take expansion into account
905 toWrite = audioBuffer.size>>1;
906 // 8 to 16 bit conversion
907 int count = toWrite;
908 int16_t *dst = (int16_t *)(audioBuffer.i8);
909 while(count--) {
910 *dst++ = (int16_t)(*src++^0x80) << 8;
911 }
Eric Laurent28ad42b2009-08-04 10:42:26 -0700912 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 toWrite = audioBuffer.size;
914 memcpy(audioBuffer.i8, src, toWrite);
915 src += toWrite;
916 }
917 userSize -= toWrite;
918 written += toWrite;
919
920 releaseBuffer(&audioBuffer);
921 } while (userSize);
922
923 return written;
924}
925
926// -------------------------------------------------------------------------
927
928bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
929{
930 Buffer audioBuffer;
931 uint32_t frames;
932 size_t writtenSize;
933
934 // Manage underrun callback
935 if (mActive && (mCblk->framesReady() == 0)) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700936 LOGV("Underrun user: %x, server: %x, flags %04x", mCblk->user, mCblk->server, mCblk->flags);
937 if ((mCblk->flags & CBLK_UNDERRUN_MSK) == CBLK_UNDERRUN_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 mCbf(EVENT_UNDERRUN, mUserData, 0);
939 if (mCblk->server == mCblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -0700940 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700942 mCblk->flags |= CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 if (mSharedBuffer != 0) return false;
944 }
945 }
Eric Laurenta553c252009-07-17 12:17:14 -0700946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 // Manage loop end callback
948 while (mLoopCount > mCblk->loopCount) {
949 int loopCount = -1;
950 mLoopCount--;
951 if (mLoopCount >= 0) loopCount = mLoopCount;
952
953 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
954 }
955
956 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700957 if (!mMarkerReached && (mMarkerPosition > 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 if (mCblk->server >= mMarkerPosition) {
959 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700960 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
962 }
963
964 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -0700965 if (mUpdatePeriod > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 while (mCblk->server >= mNewPosition) {
967 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
968 mNewPosition += mUpdatePeriod;
969 }
970 }
971
972 // If Shared buffer is used, no data is requested from client.
973 if (mSharedBuffer != 0) {
974 frames = 0;
975 } else {
976 frames = mRemainingFrames;
977 }
978
979 do {
980
981 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -0700982
983 // Calling obtainBuffer() with a wait count of 1
984 // limits wait time to WAIT_PERIOD_MS. This prevents from being
985 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 status_t err = obtainBuffer(&audioBuffer, 1);
987 if (err < NO_ERROR) {
988 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -0700989 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 -0800990 return false;
991 }
992 break;
993 }
994 if (err == status_t(STOPPED)) return false;
995
996 // Divide buffer size by 2 to take into account the expansion
997 // due to 8 to 16 bit conversion: the callback must fill only half
998 // of the destination buffer
Eric Laurent28ad42b2009-08-04 10:42:26 -0700999 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 audioBuffer.size >>= 1;
1001 }
1002
1003 size_t reqSize = audioBuffer.size;
1004 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1005 writtenSize = audioBuffer.size;
1006
1007 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001008 if (ssize_t(writtenSize) <= 0) {
1009 // The callback is done filling buffers
1010 // Keep this thread going to handle timed events and
1011 // still try to get more data in intervals of WAIT_PERIOD_MS
1012 // but don't just loop and block the CPU, so wait
1013 usleep(WAIT_PERIOD_MS*1000);
1014 break;
1015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 if (writtenSize > reqSize) writtenSize = reqSize;
1017
Eric Laurent28ad42b2009-08-04 10:42:26 -07001018 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 // 8 to 16 bit conversion
1020 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1021 int count = writtenSize;
1022 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1023 while(count--) {
1024 *dst-- = (int16_t)(*src--^0x80) << 8;
1025 }
1026 writtenSize <<= 1;
1027 }
1028
1029 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001030 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1031 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1032 // 16 bit.
1033 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 frames -= audioBuffer.frameCount;
1036
1037 releaseBuffer(&audioBuffer);
1038 }
1039 while (frames);
1040
1041 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001042 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 } else {
1044 mRemainingFrames = frames;
1045 }
1046 return true;
1047}
1048
1049status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1050{
1051
1052 const size_t SIZE = 256;
1053 char buffer[SIZE];
1054 String8 result;
1055
1056 result.append(" AudioTrack::dump\n");
1057 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1058 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001059 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 -08001060 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001061 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 -08001062 result.append(buffer);
1063 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1064 result.append(buffer);
1065 ::write(fd, result.string(), result.size());
1066 return NO_ERROR;
1067}
1068
1069// =========================================================================
1070
1071AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1072 : Thread(bCanCallJava), mReceiver(receiver)
1073{
1074}
1075
1076bool AudioTrack::AudioTrackThread::threadLoop()
1077{
1078 return mReceiver.processAudioBuffer(this);
1079}
1080
1081status_t AudioTrack::AudioTrackThread::readyToRun()
1082{
1083 return NO_ERROR;
1084}
1085
1086void AudioTrack::AudioTrackThread::onFirstRef()
1087{
1088}
1089
1090// =========================================================================
1091
1092audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001093 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1094 userBase(0), serverBase(0), buffers(0), frameCount(0),
1095 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurent65b65452010-06-01 23:49:17 -07001096 flags(0), sendLevel(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097{
1098}
1099
1100uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1101{
1102 uint32_t u = this->user;
1103
1104 u += frameCount;
1105 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001106 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1108 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1109 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1110 }
1111 } else if (u > this->server) {
1112 LOGW("stepServer occured after track reset");
1113 u = this->server;
1114 }
1115
1116 if (u >= userBase + this->frameCount) {
1117 userBase += this->frameCount;
1118 }
1119
1120 this->user = u;
1121
1122 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001123 flags &= ~CBLK_UNDERRUN_MSK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124
1125 return u;
1126}
1127
1128bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1129{
1130 // the code below simulates lock-with-timeout
1131 // we MUST do this to protect the AudioFlinger server
1132 // as this lock is shared with the client.
1133 status_t err;
1134
1135 err = lock.tryLock();
1136 if (err == -EBUSY) { // just wait a bit
1137 usleep(1000);
1138 err = lock.tryLock();
1139 }
1140 if (err != NO_ERROR) {
1141 // probably, the client just died.
1142 return false;
1143 }
1144
1145 uint32_t s = this->server;
1146
1147 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001148 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 // Mark that we have read the first buffer so that next time stepUser() is called
1150 // we switch to normal obtainBuffer() timeout period
1151 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001152 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 // It is possible that we receive a flush()
1155 // while the mixer is processing a block: in this case,
1156 // stepServer() is called After the flush() has reset u & s and
1157 // we have s > u
1158 if (s > this->user) {
1159 LOGW("stepServer occured after track reset");
1160 s = this->user;
1161 }
1162 }
1163
1164 if (s >= loopEnd) {
1165 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1166 s = loopStart;
1167 if (--loopCount == 0) {
1168 loopEnd = UINT_MAX;
1169 loopStart = UINT_MAX;
1170 }
1171 }
1172 if (s >= serverBase + this->frameCount) {
1173 serverBase += this->frameCount;
1174 }
1175
1176 this->server = s;
1177
1178 cv.signal();
1179 lock.unlock();
1180 return true;
1181}
1182
1183void* audio_track_cblk_t::buffer(uint32_t offset) const
1184{
Eric Laurenta553c252009-07-17 12:17:14 -07001185 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186}
1187
1188uint32_t audio_track_cblk_t::framesAvailable()
1189{
1190 Mutex::Autolock _l(lock);
1191 return framesAvailable_l();
1192}
1193
1194uint32_t audio_track_cblk_t::framesAvailable_l()
1195{
1196 uint32_t u = this->user;
1197 uint32_t s = this->server;
1198
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001199 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 uint32_t limit = (s < loopStart) ? s : loopStart;
1201 return limit + frameCount - u;
1202 } else {
1203 return frameCount + u - s;
1204 }
1205}
1206
1207uint32_t audio_track_cblk_t::framesReady()
1208{
1209 uint32_t u = this->user;
1210 uint32_t s = this->server;
1211
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001212 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 if (u < loopEnd) {
1214 return u - s;
1215 } else {
1216 Mutex::Autolock _l(lock);
1217 if (loopCount >= 0) {
1218 return (loopEnd - loopStart)*loopCount + u - s;
1219 } else {
1220 return UINT_MAX;
1221 }
1222 }
1223 } else {
1224 return s - u;
1225 }
1226}
1227
1228// -------------------------------------------------------------------------
1229
1230}; // namespace android
1231