blob: 2274521d682ca69b0611e6700b990bd33849f866 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/* //device/extlibs/pv/android/AudioTrack.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08005** 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
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07008**
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08009** http://www.apache.org/licenses/LICENSE-2.0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070010**
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080011** 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
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070015** 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>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080024#include <limits.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070025
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>
35#include <utils/MemoryDealer.h>
36#include <utils/Parcel.h>
37#include <utils/IPCThreadState.h>
38#include <utils/Timers.h>
39#include <cutils/atomic.h>
40
41#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
42#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
43
44namespace android {
45
46// ---------------------------------------------------------------------------
47
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048AudioTrack::AudioTrack()
49 : mStatus(NO_INIT)
50{
51}
52
53AudioTrack::AudioTrack(
54 int streamType,
55 uint32_t sampleRate,
56 int format,
57 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080058 int frameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070059 uint32_t flags,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080060 callback_t cbf,
61 void* user,
62 int notificationFrames)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070063 : mStatus(NO_INIT)
64{
65 mStatus = set(streamType, sampleRate, format, channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080066 frameCount, flags, cbf, user, notificationFrames, 0);
67}
68
69AudioTrack::AudioTrack(
70 int streamType,
71 uint32_t sampleRate,
72 int format,
73 int channelCount,
74 const sp<IMemory>& sharedBuffer,
75 uint32_t flags,
76 callback_t cbf,
77 void* user,
78 int notificationFrames)
79 : mStatus(NO_INIT)
80{
81 mStatus = set(streamType, sampleRate, format, channelCount,
82 0, flags, cbf, user, notificationFrames, sharedBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070083}
84
85AudioTrack::~AudioTrack()
86{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080087 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
88
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070089 if (mStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080090 // Make sure that callback function exits in the case where
91 // it is looping on buffer full condition in obtainBuffer().
92 // Otherwise the callback thread will never exit.
93 stop();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070094 if (mAudioTrackThread != 0) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080095 mCblk->cv.signal();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070096 mAudioTrackThread->requestExitAndWait();
97 mAudioTrackThread.clear();
98 }
99 mAudioTrack.clear();
100 IPCThreadState::self()->flushCommands();
101 }
102}
103
104status_t AudioTrack::set(
105 int streamType,
106 uint32_t sampleRate,
107 int format,
108 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800109 int frameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700110 uint32_t flags,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800111 callback_t cbf,
112 void* user,
113 int notificationFrames,
114 const sp<IMemory>& sharedBuffer,
115 bool threadCanCallJava)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700116{
117
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800118 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
119
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700120 if (mAudioFlinger != 0) {
121 LOGE("Track already in use");
122 return INVALID_OPERATION;
123 }
124
125 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
126 if (audioFlinger == 0) {
127 LOGE("Could not get audioflinger");
128 return NO_INIT;
129 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800130 int afSampleRate;
The Android Open Source Projectda996f32009-02-13 12:57:50 -0800131 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800132 return NO_INIT;
133 }
134 int afFrameCount;
The Android Open Source Projectda996f32009-02-13 12:57:50 -0800135 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800136 return NO_INIT;
137 }
138 uint32_t afLatency;
The Android Open Source Projectda996f32009-02-13 12:57:50 -0800139 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800140 return NO_INIT;
141 }
142
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700143 // handle default values first.
The Android Open Source Projectda996f32009-02-13 12:57:50 -0800144 if (streamType == AudioSystem::DEFAULT) {
145 streamType = AudioSystem::MUSIC;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700146 }
147 if (sampleRate == 0) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800148 sampleRate = afSampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700149 }
150 // these below should probably come from the audioFlinger too...
151 if (format == 0) {
152 format = AudioSystem::PCM_16_BIT;
153 }
154 if (channelCount == 0) {
155 channelCount = 2;
156 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700157
158 // validate parameters
The Android Open Source Project3001a032009-02-19 10:57:31 -0800159 if (((format != AudioSystem::PCM_8_BIT) || sharedBuffer != 0) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800160 (format != AudioSystem::PCM_16_BIT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700161 LOGE("Invalid format");
162 return BAD_VALUE;
163 }
164 if (channelCount != 1 && channelCount != 2) {
165 LOGE("Invalid channel number");
166 return BAD_VALUE;
167 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800168
169 // Ensure that buffer depth covers at least audio hardware latency
170 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
The Android Open Source Project3dec7d52009-03-02 22:54:33 -0800171 if (minBufCount < 2) minBufCount = 2;
172
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800173 // When playing from shared buffer, playback will start even if last audioflinger
174 // block is partly filled.
175 if (sharedBuffer != 0 && minBufCount > 1) {
176 minBufCount--;
177 }
178
179 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
180
181 if (sharedBuffer == 0) {
182 if (frameCount == 0) {
183 frameCount = minFrameCount;
184 }
185 if (notificationFrames == 0) {
186 notificationFrames = frameCount/2;
187 }
188 // Make sure that application is notified with sufficient margin
189 // before underrun
190 if (notificationFrames > frameCount/2) {
191 notificationFrames = frameCount/2;
192 }
193 } else {
194 // Ensure that buffer alignment matches channelcount
195 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
196 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
197 return BAD_VALUE;
198 }
199 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
200 }
201
202 if (frameCount < minFrameCount) {
203 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
204 return BAD_VALUE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700205 }
206
207 // create the track
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800208 status_t status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700209 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800210 streamType, sampleRate, format, channelCount, frameCount, flags, sharedBuffer, &status);
211
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700212 if (track == 0) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800213 LOGE("AudioFlinger could not create track, status: %d", status);
214 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700215 }
216 sp<IMemory> cblk = track->getCblk();
217 if (cblk == 0) {
218 LOGE("Could not get control block");
219 return NO_INIT;
220 }
221 if (cbf != 0) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800222 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700223 if (mAudioTrackThread == 0) {
224 LOGE("Could not create callback thread");
225 return NO_INIT;
226 }
227 }
228
229 mStatus = NO_ERROR;
230
231 mAudioFlinger = audioFlinger;
232 mAudioTrack = track;
233 mCblkMemory = cblk;
234 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800235 mCblk->out = 1;
236 // Update buffer size in case it has been limited by AudioFlinger during track creation
237 mFrameCount = mCblk->frameCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800238 if (sharedBuffer == 0) {
239 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
240 } else {
241 mCblk->buffers = sharedBuffer->pointer();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800242 // Force buffer full condition as data is already present in shared memory
243 mCblk->stepUser(mFrameCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800244 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700245 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
246 mVolume[LEFT] = 1.0f;
247 mVolume[RIGHT] = 1.0f;
248 mSampleRate = sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700249 mStreamType = streamType;
250 mFormat = format;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700251 mChannelCount = channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800252 mSharedBuffer = sharedBuffer;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700253 mMuted = false;
254 mActive = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700255 mCbf = cbf;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800256 mNotificationFrames = notificationFrames;
257 mRemainingFrames = notificationFrames;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258 mUserData = user;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800259 mLatency = afLatency + (1000*mFrameCount) / mSampleRate;
260 mLoopCount = 0;
261 mMarkerPosition = 0;
262 mNewPosition = 0;
263 mUpdatePeriod = 0;
The Android Open Source Projectda996f32009-02-13 12:57:50 -0800264
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700265 return NO_ERROR;
266}
267
268status_t AudioTrack::initCheck() const
269{
270 return mStatus;
271}
272
273// -------------------------------------------------------------------------
274
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800275uint32_t AudioTrack::latency() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276{
277 return mLatency;
278}
279
280int AudioTrack::streamType() const
281{
282 return mStreamType;
283}
284
285uint32_t AudioTrack::sampleRate() const
286{
287 return mSampleRate;
288}
289
290int AudioTrack::format() const
291{
292 return mFormat;
293}
294
295int AudioTrack::channelCount() const
296{
297 return mChannelCount;
298}
299
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800300uint32_t AudioTrack::frameCount() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700301{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800302 return mFrameCount;
303}
304
305int AudioTrack::frameSize() const
306{
307 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
308}
309
310sp<IMemory>& AudioTrack::sharedBuffer()
311{
312 return mSharedBuffer;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700313}
314
315// -------------------------------------------------------------------------
316
317void AudioTrack::start()
318{
319 sp<AudioTrackThread> t = mAudioTrackThread;
320
321 LOGV("start");
322 if (t != 0) {
323 if (t->exitPending()) {
324 if (t->requestExitAndWait() == WOULD_BLOCK) {
325 LOGE("AudioTrack::start called from thread");
326 return;
327 }
328 }
329 t->mLock.lock();
330 }
331
332 if (android_atomic_or(1, &mActive) == 0) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800333 mNewPosition = mCblk->server + mUpdatePeriod;
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800334 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
335 mCblk->waitTimeMs = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700336 if (t != 0) {
337 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
338 } else {
339 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
340 }
341 mAudioTrack->start();
342 }
343
344 if (t != 0) {
345 t->mLock.unlock();
346 }
347}
348
349void AudioTrack::stop()
350{
351 sp<AudioTrackThread> t = mAudioTrackThread;
352
353 LOGV("stop");
354 if (t != 0) {
355 t->mLock.lock();
356 }
357
358 if (android_atomic_and(~1, &mActive) == 1) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700359 mAudioTrack->stop();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800360 // Cancel loops (If we are in the middle of a loop, playback
361 // would not stop until loopCount reaches 0).
362 setLoop(0, 0, 0);
363 // Force flush if a shared buffer is used otherwise audioflinger
364 // will not stop before end of buffer is reached.
365 if (mSharedBuffer != 0) {
366 flush();
367 }
368 if (t != 0) {
369 t->requestExit();
370 } else {
371 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
372 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700373 }
374
375 if (t != 0) {
376 t->mLock.unlock();
377 }
378}
379
380bool AudioTrack::stopped() const
381{
382 return !mActive;
383}
384
385void AudioTrack::flush()
386{
387 LOGV("flush");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800388
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700389 if (!mActive) {
390 mCblk->lock.lock();
391 mAudioTrack->flush();
392 // Release AudioTrack callback thread in case it was waiting for new buffers
393 // in AudioTrack::obtainBuffer()
394 mCblk->cv.signal();
395 mCblk->lock.unlock();
396 }
397}
398
399void AudioTrack::pause()
400{
401 LOGV("pause");
402 if (android_atomic_and(~1, &mActive) == 1) {
403 mActive = 0;
404 mAudioTrack->pause();
405 }
406}
407
408void AudioTrack::mute(bool e)
409{
410 mAudioTrack->mute(e);
411 mMuted = e;
412}
413
414bool AudioTrack::muted() const
415{
416 return mMuted;
417}
418
419void AudioTrack::setVolume(float left, float right)
420{
421 mVolume[LEFT] = left;
422 mVolume[RIGHT] = right;
423
424 // write must be atomic
425 mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000);
426}
427
428void AudioTrack::getVolume(float* left, float* right)
429{
430 *left = mVolume[LEFT];
431 *right = mVolume[RIGHT];
432}
433
434void AudioTrack::setSampleRate(int rate)
435{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800436 int afSamplingRate;
437
The Android Open Source Projectda996f32009-02-13 12:57:50 -0800438 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800439 return;
440 }
441 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
The Android Open Source Project3dec7d52009-03-02 22:54:33 -0800442 if (rate <= 0) rate = 1;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800443 if (rate > afSamplingRate*2) rate = afSamplingRate*2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700444 if (rate > MAX_SAMPLE_RATE) rate = MAX_SAMPLE_RATE;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800445
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700446 mCblk->sampleRate = rate;
447}
448
449uint32_t AudioTrack::getSampleRate()
450{
451 return uint32_t(mCblk->sampleRate);
452}
453
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800454status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
455{
456 audio_track_cblk_t* cblk = mCblk;
457
458
459 Mutex::Autolock _l(cblk->lock);
460
461 if (loopCount == 0) {
462 cblk->loopStart = UINT_MAX;
463 cblk->loopEnd = UINT_MAX;
464 cblk->loopCount = 0;
465 mLoopCount = 0;
466 return NO_ERROR;
467 }
468
469 if (loopStart >= loopEnd ||
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800470 loopEnd - loopStart > mFrameCount) {
The Android Open Source Project3dec7d52009-03-02 22:54:33 -0800471 LOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800472 return BAD_VALUE;
473 }
The Android Open Source Project3dec7d52009-03-02 22:54:33 -0800474
475 if ((mSharedBuffer != 0) && (loopEnd > mFrameCount)) {
476 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
477 loopStart, loopEnd, mFrameCount);
478 return BAD_VALUE;
479 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800480
481 cblk->loopStart = loopStart;
482 cblk->loopEnd = loopEnd;
483 cblk->loopCount = loopCount;
484 mLoopCount = loopCount;
485
486 return NO_ERROR;
487}
488
489status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
490{
491 if (loopStart != 0) {
492 *loopStart = mCblk->loopStart;
493 }
494 if (loopEnd != 0) {
495 *loopEnd = mCblk->loopEnd;
496 }
497 if (loopCount != 0) {
498 if (mCblk->loopCount < 0) {
499 *loopCount = -1;
500 } else {
501 *loopCount = mCblk->loopCount;
502 }
503 }
504
505 return NO_ERROR;
506}
507
508status_t AudioTrack::setMarkerPosition(uint32_t marker)
509{
510 if (mCbf == 0) return INVALID_OPERATION;
511
512 mMarkerPosition = marker;
513
514 return NO_ERROR;
515}
516
517status_t AudioTrack::getMarkerPosition(uint32_t *marker)
518{
519 if (marker == 0) return BAD_VALUE;
520
521 *marker = mMarkerPosition;
522
523 return NO_ERROR;
524}
525
526status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
527{
528 if (mCbf == 0) return INVALID_OPERATION;
529
530 uint32_t curPosition;
531 getPosition(&curPosition);
532 mNewPosition = curPosition + updatePeriod;
533 mUpdatePeriod = updatePeriod;
534
535 return NO_ERROR;
536}
537
538status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
539{
540 if (updatePeriod == 0) return BAD_VALUE;
541
542 *updatePeriod = mUpdatePeriod;
543
544 return NO_ERROR;
545}
546
547status_t AudioTrack::setPosition(uint32_t position)
548{
549 Mutex::Autolock _l(mCblk->lock);
550
551 if (!stopped()) return INVALID_OPERATION;
552
553 if (position > mCblk->user) return BAD_VALUE;
554
555 mCblk->server = position;
556 mCblk->forceReady = 1;
557
558 return NO_ERROR;
559}
560
561status_t AudioTrack::getPosition(uint32_t *position)
562{
563 if (position == 0) return BAD_VALUE;
564
565 *position = mCblk->server;
566
567 return NO_ERROR;
568}
569
570status_t AudioTrack::reload()
571{
572 if (!stopped()) return INVALID_OPERATION;
573
574 flush();
575
576 mCblk->stepUser(mFrameCount);
577
578 return NO_ERROR;
579}
580
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700581// -------------------------------------------------------------------------
582
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800583status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700584{
585 int active;
586 int timeout = 0;
587 status_t result;
588 audio_track_cblk_t* cblk = mCblk;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800589 uint32_t framesReq = audioBuffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700590
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800591 audioBuffer->frameCount = 0;
592 audioBuffer->size = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700593
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800594 uint32_t framesAvail = cblk->framesAvailable();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700595
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800596 if (framesAvail == 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700597 Mutex::Autolock _l(cblk->lock);
598 goto start_loop_here;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800599 while (framesAvail == 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700600 active = mActive;
601 if (UNLIKELY(!active)) {
602 LOGV("Not active and NO_MORE_BUFFERS");
603 return NO_MORE_BUFFERS;
604 }
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800605 if (UNLIKELY(!waitCount))
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700606 return WOULD_BLOCK;
607 timeout = 0;
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800608 result = cblk->cv.waitRelative(cblk->lock, milliseconds(WAIT_PERIOD_MS));
609 if (__builtin_expect(result!=NO_ERROR, false)) {
610 cblk->waitTimeMs += WAIT_PERIOD_MS;
611 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800612 // timing out when a loop has been set and we have already written upto loop end
613 // is a normal condition: no need to wake AudioFlinger up.
614 if (cblk->user < cblk->loopEnd) {
615 LOGW( "obtainBuffer timed out (is the CPU pegged?) "
616 "user=%08x, server=%08x", cblk->user, cblk->server);
617 mAudioFlinger->wakeUp();
618 timeout = 1;
619 }
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800620 cblk->waitTimeMs = 0;
621 }
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800622
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800623 if (--waitCount == 0) {
624 return TIMED_OUT;
625 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700626 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700627 // read the server count again
628 start_loop_here:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800629 framesAvail = cblk->framesAvailable_l();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700630 }
631 }
632
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800633 cblk->waitTimeMs = 0;
634
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800635 if (framesReq > framesAvail) {
636 framesReq = framesAvail;
637 }
638
639 uint32_t u = cblk->user;
640 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
641
642 if (u + framesReq > bufferEnd) {
643 framesReq = bufferEnd - u;
644 }
645
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700646 LOGW_IF(timeout,
647 "*** SERIOUS WARNING *** obtainBuffer() timed out "
648 "but didn't need to be locked. We recovered, but "
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800649 "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700650
651 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
652 audioBuffer->channelCount= mChannelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800653 audioBuffer->format = AudioSystem::PCM_16_BIT;
654 audioBuffer->frameCount = framesReq;
655 audioBuffer->size = framesReq*mChannelCount*sizeof(int16_t);
656 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700657 active = mActive;
658 return active ? status_t(NO_ERROR) : status_t(STOPPED);
659}
660
661void AudioTrack::releaseBuffer(Buffer* audioBuffer)
662{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700663 audio_track_cblk_t* cblk = mCblk;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800664 cblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700665}
666
667// -------------------------------------------------------------------------
668
669ssize_t AudioTrack::write(const void* buffer, size_t userSize)
670{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800671
672 if (mSharedBuffer != 0) return INVALID_OPERATION;
673
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700674 if (ssize_t(userSize) < 0) {
675 // sanity-check. user is most-likely passing an error code.
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800676 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700677 buffer, userSize, userSize);
678 return BAD_VALUE;
679 }
680
681 LOGV("write %d bytes, mActive=%d", userSize, mActive);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800682
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700683 ssize_t written = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800684 const int8_t *src = (const int8_t *)buffer;
685 Buffer audioBuffer;
686
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700687 do {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800688 audioBuffer.frameCount = userSize/mChannelCount;
689 if (mFormat == AudioSystem::PCM_16_BIT) {
690 audioBuffer.frameCount >>= 1;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700691 }
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800692 // Calling obtainBuffer() with a negative wait count causes
693 // an (almost) infinite wait time.
694 status_t err = obtainBuffer(&audioBuffer, -1);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800695 if (err < 0) {
696 // out of buffers, return #bytes written
697 if (err == status_t(NO_MORE_BUFFERS))
698 break;
699 return ssize_t(err);
700 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700701
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800702 size_t toWrite;
703 if (mFormat == AudioSystem::PCM_8_BIT) {
704 // Divide capacity by 2 to take expansion into account
705 toWrite = audioBuffer.size>>1;
706 // 8 to 16 bit conversion
707 int count = toWrite;
708 int16_t *dst = (int16_t *)(audioBuffer.i8);
709 while(count--) {
710 *dst++ = (int16_t)(*src++^0x80) << 8;
711 }
712 }else {
713 toWrite = audioBuffer.size;
714 memcpy(audioBuffer.i8, src, toWrite);
715 src += toWrite;
716 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700717 userSize -= toWrite;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700718 written += toWrite;
719
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800720 releaseBuffer(&audioBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700721 } while (userSize);
722
723 return written;
724}
725
726// -------------------------------------------------------------------------
727
728bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
729{
730 Buffer audioBuffer;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800731 uint32_t frames;
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800732 size_t writtenSize;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700733
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800734 // Manage underrun callback
735 if (mActive && (mCblk->framesReady() == 0)) {
736 LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
737 if (mCblk->flowControlFlag == 0) {
738 mCbf(EVENT_UNDERRUN, mUserData, 0);
739 if (mCblk->server == mCblk->frameCount) {
740 mCbf(EVENT_BUFFER_END, mUserData, 0);
741 }
742 mCblk->flowControlFlag = 1;
743 if (mSharedBuffer != 0) return false;
744 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700745 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800746
747 // Manage loop end callback
748 while (mLoopCount > mCblk->loopCount) {
749 int loopCount = -1;
750 mLoopCount--;
751 if (mLoopCount >= 0) loopCount = mLoopCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700752
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800753 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
754 }
755
756 // Manage marker callback
757 if(mMarkerPosition > 0) {
758 if (mCblk->server >= mMarkerPosition) {
759 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
760 mMarkerPosition = 0;
761 }
762 }
763
764 // Manage new position callback
765 if(mUpdatePeriod > 0) {
766 while (mCblk->server >= mNewPosition) {
767 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
768 mNewPosition += mUpdatePeriod;
769 }
770 }
771
772 // If Shared buffer is used, no data is requested from client.
773 if (mSharedBuffer != 0) {
774 frames = 0;
775 } else {
776 frames = mRemainingFrames;
777 }
778
779 do {
780
781 audioBuffer.frameCount = frames;
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800782
783 // Calling obtainBuffer() with a wait count of 1
784 // limits wait time to WAIT_PERIOD_MS. This prevents from being
785 // stuck here not being able to handle timed events (position, markers, loops).
786 status_t err = obtainBuffer(&audioBuffer, 1);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800787 if (err < NO_ERROR) {
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800788 if (err != TIMED_OUT) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800789 LOGE("Error obtaining an audio buffer, giving up.");
790 return false;
791 }
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800792 break;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800793 }
794 if (err == status_t(STOPPED)) return false;
795
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800796 // Divide buffer size by 2 to take into account the expansion
797 // due to 8 to 16 bit conversion: the callback must fill only half
798 // of the destination buffer
799 if (mFormat == AudioSystem::PCM_8_BIT) {
800 audioBuffer.size >>= 1;
801 }
802
803 size_t reqSize = audioBuffer.size;
804 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
805 writtenSize = audioBuffer.size;
806
807 // Sanity check on returned size
808 if (ssize_t(writtenSize) <= 0) break;
809 if (writtenSize > reqSize) writtenSize = reqSize;
810
811 if (mFormat == AudioSystem::PCM_8_BIT) {
812 // 8 to 16 bit conversion
813 const int8_t *src = audioBuffer.i8 + writtenSize-1;
814 int count = writtenSize;
815 int16_t *dst = audioBuffer.i16 + writtenSize-1;
816 while(count--) {
817 *dst-- = (int16_t)(*src--^0x80) << 8;
818 }
819 writtenSize <<= 1;
820 }
821
822 audioBuffer.size = writtenSize;
823 audioBuffer.frameCount = writtenSize/mChannelCount/sizeof(int16_t);
824 frames -= audioBuffer.frameCount;
825
826 releaseBuffer(&audioBuffer);
827 }
828 while (frames);
829
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800830 if (frames == 0) {
831 mRemainingFrames = mNotificationFrames;
832 } else {
833 mRemainingFrames = frames;
834 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700835 return true;
836}
837
838status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
839{
840
841 const size_t SIZE = 256;
842 char buffer[SIZE];
843 String8 result;
844
845 result.append(" AudioTrack::dump\n");
846 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
847 result.append(buffer);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800848 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700849 result.append(buffer);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800850 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", mSampleRate, mStatus, mMuted);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700851 result.append(buffer);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800852 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700853 result.append(buffer);
854 ::write(fd, result.string(), result.size());
855 return NO_ERROR;
856}
857
858// =========================================================================
859
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800860AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
861 : Thread(bCanCallJava), mReceiver(receiver)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700862{
863}
864
865bool AudioTrack::AudioTrackThread::threadLoop()
866{
867 return mReceiver.processAudioBuffer(this);
868}
869
870status_t AudioTrack::AudioTrackThread::readyToRun()
871{
872 return NO_ERROR;
873}
874
875void AudioTrack::AudioTrackThread::onFirstRef()
876{
877}
878
879// =========================================================================
880
881audio_track_cblk_t::audio_track_cblk_t()
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800882 : user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
883 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700884{
885}
886
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800887uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700888{
889 uint32_t u = this->user;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800890
891 u += frameCount;
892 // Ensure that user is never ahead of server for AudioRecord
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800893 if (out) {
894 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
895 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
896 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
897 }
898 } else if (u > this->server) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800899 LOGW("stepServer occured after track reset");
900 u = this->server;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700901 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800902
903 if (u >= userBase + this->frameCount) {
904 userBase += this->frameCount;
905 }
906
907 this->user = u;
908
909 // Clear flow control error condition as new data has been written/read to/from buffer.
910 flowControlFlag = 0;
911
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700912 return u;
913}
914
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800915bool audio_track_cblk_t::stepServer(uint32_t frameCount)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700916{
917 // the code below simulates lock-with-timeout
918 // we MUST do this to protect the AudioFlinger server
919 // as this lock is shared with the client.
920 status_t err;
921
922 err = lock.tryLock();
923 if (err == -EBUSY) { // just wait a bit
924 usleep(1000);
925 err = lock.tryLock();
926 }
927 if (err != NO_ERROR) {
928 // probably, the client just died.
929 return false;
930 }
931
932 uint32_t s = this->server;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700933
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800934 s += frameCount;
The Android Open Source Project22f7dfd2009-01-20 14:03:58 -0800935 if (out) {
936 // Mark that we have read the first buffer so that next time stepUser() is called
937 // we switch to normal obtainBuffer() timeout period
938 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
939 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS - 1;
940 }
941 // It is possible that we receive a flush()
942 // while the mixer is processing a block: in this case,
943 // stepServer() is called After the flush() has reset u & s and
944 // we have s > u
945 if (s > this->user) {
946 LOGW("stepServer occured after track reset");
947 s = this->user;
948 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800949 }
950
951 if (s >= loopEnd) {
952 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
953 s = loopStart;
954 if (--loopCount == 0) {
955 loopEnd = UINT_MAX;
956 loopStart = UINT_MAX;
957 }
958 }
959 if (s >= serverBase + this->frameCount) {
960 serverBase += this->frameCount;
961 }
962
963 this->server = s;
964
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700965 cv.signal();
966 lock.unlock();
967 return true;
968}
969
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800970void* audio_track_cblk_t::buffer(uint32_t offset) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700971{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800972 return (int16_t *)this->buffers + (offset-userBase)*this->channels;
973}
974
975uint32_t audio_track_cblk_t::framesAvailable()
976{
977 Mutex::Autolock _l(lock);
978 return framesAvailable_l();
979}
980
981uint32_t audio_track_cblk_t::framesAvailable_l()
982{
983 uint32_t u = this->user;
984 uint32_t s = this->server;
985
986 if (out) {
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800987 uint32_t limit = (s < loopStart) ? s : loopStart;
988 return limit + frameCount - u;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800989 } else {
990 return frameCount + u - s;
991 }
992}
993
994uint32_t audio_track_cblk_t::framesReady()
995{
996 uint32_t u = this->user;
997 uint32_t s = this->server;
998
999 if (out) {
1000 if (u < loopEnd) {
1001 return u - s;
1002 } else {
1003 Mutex::Autolock _l(lock);
1004 if (loopCount >= 0) {
1005 return (loopEnd - loopStart)*loopCount + u - s;
1006 } else {
1007 return UINT_MAX;
1008 }
1009 }
1010 } else {
1011 return s - u;
1012 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001013}
1014
1015// -------------------------------------------------------------------------
1016
1017}; // namespace android
1018