blob: 0f2093a176dddda231301ea50f8077329ffef842 [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,
Eric Laurent619346f2010-06-21 09:27:30 -070095 frameCount, flags, cbf, user, notificationFrames,
96 0, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097}
98
99AudioTrack::AudioTrack(
100 int streamType,
101 uint32_t sampleRate,
102 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700103 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 const sp<IMemory>& sharedBuffer,
105 uint32_t flags,
106 callback_t cbf,
107 void* user,
Eric Laurent65b65452010-06-01 23:49:17 -0700108 int notificationFrames,
109 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 : mStatus(NO_INIT)
111{
Eric Laurenta553c252009-07-17 12:17:14 -0700112 mStatus = set(streamType, sampleRate, format, channels,
Eric Laurent619346f2010-06-21 09:27:30 -0700113 0, flags, cbf, user, notificationFrames,
114 sharedBuffer, false, sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115}
116
117AudioTrack::~AudioTrack()
118{
119 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
120
121 if (mStatus == NO_ERROR) {
122 // Make sure that callback function exits in the case where
123 // it is looping on buffer full condition in obtainBuffer().
124 // Otherwise the callback thread will never exit.
125 stop();
126 if (mAudioTrackThread != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 mAudioTrackThread->requestExitAndWait();
128 mAudioTrackThread.clear();
129 }
130 mAudioTrack.clear();
131 IPCThreadState::self()->flushCommands();
132 }
133}
134
135status_t AudioTrack::set(
136 int streamType,
137 uint32_t sampleRate,
138 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700139 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 int frameCount,
141 uint32_t flags,
142 callback_t cbf,
143 void* user,
144 int notificationFrames,
145 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -0700146 bool threadCanCallJava,
147 int sessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148{
149
150 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
151
Eric Laurentef028272009-04-21 07:56:33 -0700152 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 LOGE("Track already in use");
154 return INVALID_OPERATION;
155 }
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 int afSampleRate;
158 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
159 return NO_INIT;
160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 uint32_t afLatency;
162 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
163 return NO_INIT;
164 }
165
166 // handle default values first.
167 if (streamType == AudioSystem::DEFAULT) {
168 streamType = AudioSystem::MUSIC;
169 }
170 if (sampleRate == 0) {
171 sampleRate = afSampleRate;
172 }
173 // these below should probably come from the audioFlinger too...
174 if (format == 0) {
175 format = AudioSystem::PCM_16_BIT;
176 }
Eric Laurenta553c252009-07-17 12:17:14 -0700177 if (channels == 0) {
178 channels = AudioSystem::CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 }
180
181 // validate parameters
Eric Laurenta553c252009-07-17 12:17:14 -0700182 if (!AudioSystem::isValidFormat(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 LOGE("Invalid format");
184 return BAD_VALUE;
185 }
Eric Laurenta553c252009-07-17 12:17:14 -0700186
187 // force direct flag if format is not linear PCM
188 if (!AudioSystem::isLinearPCM(format)) {
189 flags |= AudioSystem::OUTPUT_FLAG_DIRECT;
190 }
191
192 if (!AudioSystem::isOutputChannel(channels)) {
193 LOGE("Invalid channel mask");
194 return BAD_VALUE;
195 }
196 uint32_t channelCount = AudioSystem::popCount(channels);
197
198 audio_io_handle_t output = AudioSystem::getOutput((AudioSystem::stream_type)streamType,
199 sampleRate, format, channels, (AudioSystem::output_flags)flags);
200
201 if (output == 0) {
202 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 return BAD_VALUE;
204 }
205
Eric Laurentbda74692009-11-04 08:27:26 -0800206 mVolume[LEFT] = 1.0f;
207 mVolume[RIGHT] = 1.0f;
Eric Laurent65b65452010-06-01 23:49:17 -0700208 mSendLevel = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700209 mFrameCount = frameCount;
210 mNotificationFramesReq = notificationFrames;
Eric Laurent65b65452010-06-01 23:49:17 -0700211 mSessionId = sessionId;
212
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
314 if (android_atomic_or(1, &mActive) == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -0800315 mNewPosition = mCblk->server + mUpdatePeriod;
316 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
317 mCblk->waitTimeMs = 0;
318 if (t != 0) {
319 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
320 } else {
321 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
322 }
323
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700324 if (mCblk->flags & CBLK_INVALID_MSK) {
325 LOGW("start() track %p invalidated, creating a new one", this);
326 // no need to clear the invalid flag as this cblk will not be used anymore
327 // force new track creation
328 status = DEAD_OBJECT;
329 } else {
330 status = mAudioTrack->start();
331 }
Eric Laurentbda74692009-11-04 08:27:26 -0800332 if (status == DEAD_OBJECT) {
333 LOGV("start() dead IAudioTrack: creating a new one");
334 status = createTrack(mStreamType, mCblk->sampleRate, mFormat, mChannelCount,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700335 mFrameCount, mFlags, mSharedBuffer, getOutput(), false);
Eric Laurent49f02be2009-11-19 09:00:56 -0800336 if (status == NO_ERROR) {
337 status = mAudioTrack->start();
338 if (status == NO_ERROR) {
339 mNewPosition = mCblk->server + mUpdatePeriod;
340 }
341 }
Eric Laurent059b4be2009-11-09 23:32:22 -0800342 }
343 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800344 LOGV("start() failed");
345 android_atomic_and(~1, &mActive);
Eric Laurent059b4be2009-11-09 23:32:22 -0800346 if (t != 0) {
347 t->requestExit();
348 } else {
349 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
350 }
Eric Laurentbda74692009-11-04 08:27:26 -0800351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 }
353
354 if (t != 0) {
355 t->mLock.unlock();
356 }
357}
358
359void AudioTrack::stop()
360{
361 sp<AudioTrackThread> t = mAudioTrackThread;
362
363 LOGV("stop %p", this);
364 if (t != 0) {
365 t->mLock.lock();
366 }
367
368 if (android_atomic_and(~1, &mActive) == 1) {
Eric Laurentef028272009-04-21 07:56:33 -0700369 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 mAudioTrack->stop();
371 // Cancel loops (If we are in the middle of a loop, playback
372 // would not stop until loopCount reaches 0).
373 setLoop(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700374 // the playback head position will reset to 0, so if a marker is set, we need
375 // to activate it again
376 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 // Force flush if a shared buffer is used otherwise audioflinger
378 // will not stop before end of buffer is reached.
379 if (mSharedBuffer != 0) {
380 flush();
381 }
382 if (t != 0) {
383 t->requestExit();
384 } else {
385 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
386 }
387 }
388
389 if (t != 0) {
390 t->mLock.unlock();
391 }
392}
393
394bool AudioTrack::stopped() const
395{
396 return !mActive;
397}
398
399void AudioTrack::flush()
400{
401 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700402
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700403 // clear playback marker and periodic update counter
404 mMarkerPosition = 0;
405 mMarkerReached = false;
406 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408
409 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 mAudioTrack->flush();
411 // Release AudioTrack callback thread in case it was waiting for new buffers
412 // in AudioTrack::obtainBuffer()
413 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 }
415}
416
417void AudioTrack::pause()
418{
419 LOGV("pause");
420 if (android_atomic_and(~1, &mActive) == 1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 mAudioTrack->pause();
422 }
423}
424
425void AudioTrack::mute(bool e)
426{
427 mAudioTrack->mute(e);
428 mMuted = e;
429}
430
431bool AudioTrack::muted() const
432{
433 return mMuted;
434}
435
Eric Laurent65b65452010-06-01 23:49:17 -0700436status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437{
Eric Laurent65b65452010-06-01 23:49:17 -0700438 if (left > 1.0f || right > 1.0f) {
439 return BAD_VALUE;
440 }
441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 mVolume[LEFT] = left;
443 mVolume[RIGHT] = right;
444
445 // write must be atomic
Eric Laurent65b65452010-06-01 23:49:17 -0700446 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
447
448 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449}
450
451void AudioTrack::getVolume(float* left, float* right)
452{
Eric Laurent65b65452010-06-01 23:49:17 -0700453 if (left != NULL) {
454 *left = mVolume[LEFT];
455 }
456 if (right != NULL) {
457 *right = mVolume[RIGHT];
458 }
459}
460
461status_t AudioTrack::setSendLevel(float level)
462{
463 if (level > 1.0f) {
464 return BAD_VALUE;
465 }
466
467 mSendLevel = level;
468
469 mCblk->sendLevel = uint16_t(level * 0x1000);
470
471 return NO_ERROR;
472}
473
474void AudioTrack::getSendLevel(float* level)
475{
476 if (level != NULL) {
477 *level = mSendLevel;
478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479}
480
Eric Laurent88e209d2009-07-07 07:10:45 -0700481status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482{
483 int afSamplingRate;
484
485 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700486 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
488 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700489 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490
Eric Laurent88e209d2009-07-07 07:10:45 -0700491 mCblk->sampleRate = rate;
492 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493}
494
495uint32_t AudioTrack::getSampleRate()
496{
Eric Laurent88e209d2009-07-07 07:10:45 -0700497 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498}
499
500status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
501{
502 audio_track_cblk_t* cblk = mCblk;
503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 Mutex::Autolock _l(cblk->lock);
505
506 if (loopCount == 0) {
507 cblk->loopStart = UINT_MAX;
508 cblk->loopEnd = UINT_MAX;
509 cblk->loopCount = 0;
510 mLoopCount = 0;
511 return NO_ERROR;
512 }
513
514 if (loopStart >= loopEnd ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700515 loopEnd - loopStart > cblk->frameCount) {
516 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 -0800517 return BAD_VALUE;
518 }
519
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700520 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700522 loopStart, loopEnd, cblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525
526 cblk->loopStart = loopStart;
527 cblk->loopEnd = loopEnd;
528 cblk->loopCount = loopCount;
529 mLoopCount = loopCount;
530
531 return NO_ERROR;
532}
533
534status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
535{
536 if (loopStart != 0) {
537 *loopStart = mCblk->loopStart;
538 }
539 if (loopEnd != 0) {
540 *loopEnd = mCblk->loopEnd;
541 }
542 if (loopCount != 0) {
543 if (mCblk->loopCount < 0) {
544 *loopCount = -1;
545 } else {
546 *loopCount = mCblk->loopCount;
547 }
548 }
549
550 return NO_ERROR;
551}
552
553status_t AudioTrack::setMarkerPosition(uint32_t marker)
554{
555 if (mCbf == 0) return INVALID_OPERATION;
556
557 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700558 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
560 return NO_ERROR;
561}
562
563status_t AudioTrack::getMarkerPosition(uint32_t *marker)
564{
565 if (marker == 0) return BAD_VALUE;
566
567 *marker = mMarkerPosition;
568
569 return NO_ERROR;
570}
571
572status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
573{
574 if (mCbf == 0) return INVALID_OPERATION;
575
576 uint32_t curPosition;
577 getPosition(&curPosition);
578 mNewPosition = curPosition + updatePeriod;
579 mUpdatePeriod = updatePeriod;
580
581 return NO_ERROR;
582}
583
584status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
585{
586 if (updatePeriod == 0) return BAD_VALUE;
587
588 *updatePeriod = mUpdatePeriod;
589
590 return NO_ERROR;
591}
592
593status_t AudioTrack::setPosition(uint32_t position)
594{
595 Mutex::Autolock _l(mCblk->lock);
596
597 if (!stopped()) return INVALID_OPERATION;
598
599 if (position > mCblk->user) return BAD_VALUE;
600
601 mCblk->server = position;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700602 mCblk->flags |= CBLK_FORCEREADY_ON;
Eric Laurenta553c252009-07-17 12:17:14 -0700603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 return NO_ERROR;
605}
606
607status_t AudioTrack::getPosition(uint32_t *position)
608{
609 if (position == 0) return BAD_VALUE;
610
611 *position = mCblk->server;
612
613 return NO_ERROR;
614}
615
616status_t AudioTrack::reload()
617{
618 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 flush();
621
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700622 mCblk->stepUser(mCblk->frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623
624 return NO_ERROR;
625}
626
Eric Laurenta553c252009-07-17 12:17:14 -0700627audio_io_handle_t AudioTrack::getOutput()
628{
629 return AudioSystem::getOutput((AudioSystem::stream_type)mStreamType,
630 mCblk->sampleRate, mFormat, mChannels, (AudioSystem::output_flags)mFlags);
631}
632
Eric Laurent65b65452010-06-01 23:49:17 -0700633int AudioTrack::getSessionId()
634{
635 return mSessionId;
636}
637
638status_t AudioTrack::attachAuxEffect(int effectId)
639{
640 return mAudioTrack->attachAuxEffect(effectId);
641}
642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643// -------------------------------------------------------------------------
644
Eric Laurentbda74692009-11-04 08:27:26 -0800645status_t AudioTrack::createTrack(
646 int streamType,
647 uint32_t sampleRate,
648 int format,
649 int channelCount,
650 int frameCount,
651 uint32_t flags,
652 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700653 audio_io_handle_t output,
654 bool enforceFrameCount)
Eric Laurentbda74692009-11-04 08:27:26 -0800655{
656 status_t status;
657 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
658 if (audioFlinger == 0) {
659 LOGE("Could not get audioflinger");
660 return NO_INIT;
661 }
662
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700663 int afSampleRate;
664 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
665 return NO_INIT;
666 }
667 int afFrameCount;
668 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
669 return NO_INIT;
670 }
671 uint32_t afLatency;
672 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
673 return NO_INIT;
674 }
675
676 mNotificationFramesAct = mNotificationFramesReq;
677 if (!AudioSystem::isLinearPCM(format)) {
678 if (sharedBuffer != 0) {
679 frameCount = sharedBuffer->size();
680 }
681 } else {
682 // Ensure that buffer depth covers at least audio hardware latency
683 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
684 if (minBufCount < 2) minBufCount = 2;
685
686 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
687
688 if (sharedBuffer == 0) {
689 if (frameCount == 0) {
690 frameCount = minFrameCount;
691 }
692 if (mNotificationFramesAct == 0) {
693 mNotificationFramesAct = frameCount/2;
694 }
695 // Make sure that application is notified with sufficient margin
696 // before underrun
697 if (mNotificationFramesAct > (uint32_t)frameCount/2) {
698 mNotificationFramesAct = frameCount/2;
699 }
700 if (frameCount < minFrameCount) {
701 if (enforceFrameCount) {
702 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
703 return BAD_VALUE;
704 } else {
705 frameCount = minFrameCount;
706 }
707 }
708 } else {
709 // Ensure that buffer alignment matches channelcount
710 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
711 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
712 return BAD_VALUE;
713 }
714 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
715 }
716 }
717
Eric Laurentbda74692009-11-04 08:27:26 -0800718 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
719 streamType,
720 sampleRate,
721 format,
722 channelCount,
723 frameCount,
724 ((uint16_t)flags) << 16,
725 sharedBuffer,
726 output,
Eric Laurent65b65452010-06-01 23:49:17 -0700727 &mSessionId,
Eric Laurentbda74692009-11-04 08:27:26 -0800728 &status);
729
730 if (track == 0) {
731 LOGE("AudioFlinger could not create track, status: %d", status);
732 return status;
733 }
734 sp<IMemory> cblk = track->getCblk();
735 if (cblk == 0) {
736 LOGE("Could not get control block");
737 return NO_INIT;
738 }
739 mAudioTrack.clear();
740 mAudioTrack = track;
741 mCblkMemory.clear();
742 mCblkMemory = cblk;
743 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700744 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurentbda74692009-11-04 08:27:26 -0800745 if (sharedBuffer == 0) {
746 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
747 } else {
748 mCblk->buffers = sharedBuffer->pointer();
749 // Force buffer full condition as data is already present in shared memory
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700750 mCblk->stepUser(mCblk->frameCount);
Eric Laurentbda74692009-11-04 08:27:26 -0800751 }
752
Eric Laurent65b65452010-06-01 23:49:17 -0700753 mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
754 mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
Eric Laurent49f02be2009-11-19 09:00:56 -0800755 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
756 mCblk->waitTimeMs = 0;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700757 mRemainingFrames = mNotificationFramesAct;
758 mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
Eric Laurentbda74692009-11-04 08:27:26 -0800759 return NO_ERROR;
760}
761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
763{
764 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 status_t result;
766 audio_track_cblk_t* cblk = mCblk;
767 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700768 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769
770 audioBuffer->frameCount = 0;
771 audioBuffer->size = 0;
772
773 uint32_t framesAvail = cblk->framesAvailable();
774
775 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800776 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 goto start_loop_here;
778 while (framesAvail == 0) {
779 active = mActive;
780 if (UNLIKELY(!active)) {
781 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800782 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 return NO_MORE_BUFFERS;
784 }
Eric Laurentbda74692009-11-04 08:27:26 -0800785 if (UNLIKELY(!waitCount)) {
786 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800788 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700789 if (!(cblk->flags & CBLK_INVALID_MSK)) {
790 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
791 }
792 if (cblk->flags & CBLK_INVALID_MSK) {
793 LOGW("obtainBuffer() track %p invalidated, creating a new one", this);
794 // no need to clear the invalid flag as this cblk will not be used anymore
795 cblk->lock.unlock();
796 goto create_new_track;
797 }
Eric Laurenta553c252009-07-17 12:17:14 -0700798 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700799 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
801 // timing out when a loop has been set and we have already written upto loop end
802 // is a normal condition: no need to wake AudioFlinger up.
803 if (cblk->user < cblk->loopEnd) {
804 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
805 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700806 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800808 result = mAudioTrack->start();
809 if (result == DEAD_OBJECT) {
810 LOGW("obtainBuffer() dead IAudioTrack: creating a new one");
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700811create_new_track:
Eric Laurentbda74692009-11-04 08:27:26 -0800812 result = createTrack(mStreamType, cblk->sampleRate, mFormat, mChannelCount,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700813 mFrameCount, mFlags, mSharedBuffer, getOutput(), false);
Eric Laurentbda74692009-11-04 08:27:26 -0800814 if (result == NO_ERROR) {
815 cblk = mCblk;
816 cblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
Eric Laurent49f02be2009-11-19 09:00:56 -0800817 mAudioTrack->start();
Eric Laurentbda74692009-11-04 08:27:26 -0800818 }
819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 }
822 cblk->waitTimeMs = 0;
823 }
Eric Laurenta553c252009-07-17 12:17:14 -0700824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800826 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 return TIMED_OUT;
828 }
829 }
830 // read the server count again
831 start_loop_here:
832 framesAvail = cblk->framesAvailable_l();
833 }
Eric Laurentbda74692009-11-04 08:27:26 -0800834 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
836
837 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 if (framesReq > framesAvail) {
840 framesReq = framesAvail;
841 }
842
843 uint32_t u = cblk->user;
844 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
845
846 if (u + framesReq > bufferEnd) {
847 framesReq = bufferEnd - u;
848 }
849
Eric Laurenta553c252009-07-17 12:17:14 -0700850 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
851 audioBuffer->channelCount = mChannelCount;
852 audioBuffer->frameCount = framesReq;
853 audioBuffer->size = framesReq * cblk->frameSize;
854 if (AudioSystem::isLinearPCM(mFormat)) {
855 audioBuffer->format = AudioSystem::PCM_16_BIT;
856 } else {
857 audioBuffer->format = mFormat;
858 }
859 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 active = mActive;
861 return active ? status_t(NO_ERROR) : status_t(STOPPED);
862}
863
864void AudioTrack::releaseBuffer(Buffer* audioBuffer)
865{
866 audio_track_cblk_t* cblk = mCblk;
867 cblk->stepUser(audioBuffer->frameCount);
868}
869
870// -------------------------------------------------------------------------
871
872ssize_t AudioTrack::write(const void* buffer, size_t userSize)
873{
874
875 if (mSharedBuffer != 0) return INVALID_OPERATION;
876
877 if (ssize_t(userSize) < 0) {
878 // sanity-check. user is most-likely passing an error code.
879 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
880 buffer, userSize, userSize);
881 return BAD_VALUE;
882 }
883
884 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
885
886 ssize_t written = 0;
887 const int8_t *src = (const int8_t *)buffer;
888 Buffer audioBuffer;
889
890 do {
Eric Laurenta553c252009-07-17 12:17:14 -0700891 audioBuffer.frameCount = userSize/frameSize();
892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 // Calling obtainBuffer() with a negative wait count causes
894 // an (almost) infinite wait time.
895 status_t err = obtainBuffer(&audioBuffer, -1);
896 if (err < 0) {
897 // out of buffers, return #bytes written
898 if (err == status_t(NO_MORE_BUFFERS))
899 break;
900 return ssize_t(err);
901 }
902
903 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700904
Eric Laurent28ad42b2009-08-04 10:42:26 -0700905 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 // Divide capacity by 2 to take expansion into account
907 toWrite = audioBuffer.size>>1;
908 // 8 to 16 bit conversion
909 int count = toWrite;
910 int16_t *dst = (int16_t *)(audioBuffer.i8);
911 while(count--) {
912 *dst++ = (int16_t)(*src++^0x80) << 8;
913 }
Eric Laurent28ad42b2009-08-04 10:42:26 -0700914 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 toWrite = audioBuffer.size;
916 memcpy(audioBuffer.i8, src, toWrite);
917 src += toWrite;
918 }
919 userSize -= toWrite;
920 written += toWrite;
921
922 releaseBuffer(&audioBuffer);
923 } while (userSize);
924
925 return written;
926}
927
928// -------------------------------------------------------------------------
929
930bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
931{
932 Buffer audioBuffer;
933 uint32_t frames;
934 size_t writtenSize;
935
936 // Manage underrun callback
937 if (mActive && (mCblk->framesReady() == 0)) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700938 LOGV("Underrun user: %x, server: %x, flags %04x", mCblk->user, mCblk->server, mCblk->flags);
939 if ((mCblk->flags & CBLK_UNDERRUN_MSK) == CBLK_UNDERRUN_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 mCbf(EVENT_UNDERRUN, mUserData, 0);
941 if (mCblk->server == mCblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -0700942 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 }
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700944 mCblk->flags |= CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 if (mSharedBuffer != 0) return false;
946 }
947 }
Eric Laurenta553c252009-07-17 12:17:14 -0700948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 // Manage loop end callback
950 while (mLoopCount > mCblk->loopCount) {
951 int loopCount = -1;
952 mLoopCount--;
953 if (mLoopCount >= 0) loopCount = mLoopCount;
954
955 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
956 }
957
958 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700959 if (!mMarkerReached && (mMarkerPosition > 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 if (mCblk->server >= mMarkerPosition) {
961 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700962 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 }
964 }
965
966 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -0700967 if (mUpdatePeriod > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 while (mCblk->server >= mNewPosition) {
969 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
970 mNewPosition += mUpdatePeriod;
971 }
972 }
973
974 // If Shared buffer is used, no data is requested from client.
975 if (mSharedBuffer != 0) {
976 frames = 0;
977 } else {
978 frames = mRemainingFrames;
979 }
980
981 do {
982
983 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -0700984
985 // Calling obtainBuffer() with a wait count of 1
986 // limits wait time to WAIT_PERIOD_MS. This prevents from being
987 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 status_t err = obtainBuffer(&audioBuffer, 1);
989 if (err < NO_ERROR) {
990 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -0700991 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 -0800992 return false;
993 }
994 break;
995 }
996 if (err == status_t(STOPPED)) return false;
997
998 // Divide buffer size by 2 to take into account the expansion
999 // due to 8 to 16 bit conversion: the callback must fill only half
1000 // of the destination buffer
Eric Laurent28ad42b2009-08-04 10:42:26 -07001001 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 audioBuffer.size >>= 1;
1003 }
1004
1005 size_t reqSize = audioBuffer.size;
1006 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1007 writtenSize = audioBuffer.size;
1008
1009 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -08001010 if (ssize_t(writtenSize) <= 0) {
1011 // The callback is done filling buffers
1012 // Keep this thread going to handle timed events and
1013 // still try to get more data in intervals of WAIT_PERIOD_MS
1014 // but don't just loop and block the CPU, so wait
1015 usleep(WAIT_PERIOD_MS*1000);
1016 break;
1017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 if (writtenSize > reqSize) writtenSize = reqSize;
1019
Eric Laurent28ad42b2009-08-04 10:42:26 -07001020 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 // 8 to 16 bit conversion
1022 const int8_t *src = audioBuffer.i8 + writtenSize-1;
1023 int count = writtenSize;
1024 int16_t *dst = audioBuffer.i16 + writtenSize-1;
1025 while(count--) {
1026 *dst-- = (int16_t)(*src--^0x80) << 8;
1027 }
1028 writtenSize <<= 1;
1029 }
1030
1031 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001032 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1033 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
1034 // 16 bit.
1035 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 frames -= audioBuffer.frameCount;
1038
1039 releaseBuffer(&audioBuffer);
1040 }
1041 while (frames);
1042
1043 if (frames == 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001044 mRemainingFrames = mNotificationFramesAct;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 } else {
1046 mRemainingFrames = frames;
1047 }
1048 return true;
1049}
1050
1051status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1052{
1053
1054 const size_t SIZE = 256;
1055 char buffer[SIZE];
1056 String8 result;
1057
1058 result.append(" AudioTrack::dump\n");
1059 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1060 result.append(buffer);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001061 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 -08001062 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -07001063 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 -08001064 result.append(buffer);
1065 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
1066 result.append(buffer);
1067 ::write(fd, result.string(), result.size());
1068 return NO_ERROR;
1069}
1070
1071// =========================================================================
1072
1073AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1074 : Thread(bCanCallJava), mReceiver(receiver)
1075{
1076}
1077
1078bool AudioTrack::AudioTrackThread::threadLoop()
1079{
1080 return mReceiver.processAudioBuffer(this);
1081}
1082
1083status_t AudioTrack::AudioTrackThread::readyToRun()
1084{
1085 return NO_ERROR;
1086}
1087
1088void AudioTrack::AudioTrackThread::onFirstRef()
1089{
1090}
1091
1092// =========================================================================
1093
1094audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -07001095 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1096 userBase(0), serverBase(0), buffers(0), frameCount(0),
1097 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
Eric Laurent65b65452010-06-01 23:49:17 -07001098 flags(0), sendLevel(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099{
1100}
1101
1102uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1103{
1104 uint32_t u = this->user;
1105
1106 u += frameCount;
1107 // Ensure that user is never ahead of server for AudioRecord
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001108 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1110 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1111 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1112 }
1113 } else if (u > this->server) {
1114 LOGW("stepServer occured after track reset");
1115 u = this->server;
1116 }
1117
1118 if (u >= userBase + this->frameCount) {
1119 userBase += this->frameCount;
1120 }
1121
1122 this->user = u;
1123
1124 // Clear flow control error condition as new data has been written/read to/from buffer.
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001125 flags &= ~CBLK_UNDERRUN_MSK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126
1127 return u;
1128}
1129
1130bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1131{
1132 // the code below simulates lock-with-timeout
1133 // we MUST do this to protect the AudioFlinger server
1134 // as this lock is shared with the client.
1135 status_t err;
1136
1137 err = lock.tryLock();
1138 if (err == -EBUSY) { // just wait a bit
1139 usleep(1000);
1140 err = lock.tryLock();
1141 }
1142 if (err != NO_ERROR) {
1143 // probably, the client just died.
1144 return false;
1145 }
1146
1147 uint32_t s = this->server;
1148
1149 s += frameCount;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001150 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 // Mark that we have read the first buffer so that next time stepUser() is called
1152 // we switch to normal obtainBuffer() timeout period
1153 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001154 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 // It is possible that we receive a flush()
1157 // while the mixer is processing a block: in this case,
1158 // stepServer() is called After the flush() has reset u & s and
1159 // we have s > u
1160 if (s > this->user) {
1161 LOGW("stepServer occured after track reset");
1162 s = this->user;
1163 }
1164 }
1165
1166 if (s >= loopEnd) {
1167 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1168 s = loopStart;
1169 if (--loopCount == 0) {
1170 loopEnd = UINT_MAX;
1171 loopStart = UINT_MAX;
1172 }
1173 }
1174 if (s >= serverBase + this->frameCount) {
1175 serverBase += this->frameCount;
1176 }
1177
1178 this->server = s;
1179
1180 cv.signal();
1181 lock.unlock();
1182 return true;
1183}
1184
1185void* audio_track_cblk_t::buffer(uint32_t offset) const
1186{
Eric Laurenta553c252009-07-17 12:17:14 -07001187 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188}
1189
1190uint32_t audio_track_cblk_t::framesAvailable()
1191{
1192 Mutex::Autolock _l(lock);
1193 return framesAvailable_l();
1194}
1195
1196uint32_t audio_track_cblk_t::framesAvailable_l()
1197{
1198 uint32_t u = this->user;
1199 uint32_t s = this->server;
1200
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001201 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 uint32_t limit = (s < loopStart) ? s : loopStart;
1203 return limit + frameCount - u;
1204 } else {
1205 return frameCount + u - s;
1206 }
1207}
1208
1209uint32_t audio_track_cblk_t::framesReady()
1210{
1211 uint32_t u = this->user;
1212 uint32_t s = this->server;
1213
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001214 if (flags & CBLK_DIRECTION_MSK) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 if (u < loopEnd) {
1216 return u - s;
1217 } else {
1218 Mutex::Autolock _l(lock);
1219 if (loopCount >= 0) {
1220 return (loopEnd - loopStart)*loopCount + u - s;
1221 } else {
1222 return UINT_MAX;
1223 }
1224 }
1225 } else {
1226 return s - u;
1227 }
1228}
1229
1230// -------------------------------------------------------------------------
1231
1232}; // namespace android
1233