blob: f9f8568c969a5513d343628b21d62885de52cb4a [file] [log] [blame]
The Android Open Source Project2729ea92008-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 Project7b5eb022008-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 Project2729ea92008-10-21 07:00:00 -07008**
The Android Open Source Project7b5eb022008-12-17 18:05:43 -08009** http://www.apache.org/licenses/LICENSE-2.0
The Android Open Source Project2729ea92008-10-21 07:00:00 -070010**
The Android Open Source Project7b5eb022008-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 Project2729ea92008-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 Project7b5eb022008-12-17 18:05:43 -080024#include <limits.h>
The Android Open Source Project2729ea92008-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 Project2729ea92008-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 Project7b5eb022008-12-17 18:05:43 -080058 int frameCount,
The Android Open Source Project2729ea92008-10-21 07:00:00 -070059 uint32_t flags,
The Android Open Source Project7b5eb022008-12-17 18:05:43 -080060 callback_t cbf,
61 void* user,
62 int notificationFrames)
The Android Open Source Project2729ea92008-10-21 07:00:00 -070063 : mStatus(NO_INIT)
64{
65 mStatus = set(streamType, sampleRate, format, channelCount,
The Android Open Source Project7b5eb022008-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 Project2729ea92008-10-21 07:00:00 -070083}
84
85AudioTrack::~AudioTrack()
86{
The Android Open Source Project7b5eb022008-12-17 18:05:43 -080087 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
88
The Android Open Source Project2729ea92008-10-21 07:00:00 -070089 if (mStatus == NO_ERROR) {
The Android Open Source Project7b5eb022008-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 Project2729ea92008-10-21 07:00:00 -070094 if (mAudioTrackThread != 0) {
The Android Open Source Project7b5eb022008-12-17 18:05:43 -080095 mCblk->cv.signal();
The Android Open Source Project2729ea92008-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 Project7b5eb022008-12-17 18:05:43 -0800109 int frameCount,
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700110 uint32_t flags,
The Android Open Source Project7b5eb022008-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 Project2729ea92008-10-21 07:00:00 -0700116{
117
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800118 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
119
The Android Open Source Project2729ea92008-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 Project7b5eb022008-12-17 18:05:43 -0800130 int afSampleRate;
131 if (AudioSystem::getOutputSamplingRate(&afSampleRate) != NO_ERROR) {
132 return NO_INIT;
133 }
134 int afFrameCount;
135 if (AudioSystem::getOutputFrameCount(&afFrameCount) != NO_ERROR) {
136 return NO_INIT;
137 }
138 uint32_t afLatency;
139 if (AudioSystem::getOutputLatency(&afLatency) != NO_ERROR) {
140 return NO_INIT;
141 }
142
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700143
144 // handle default values first.
145 if (streamType == DEFAULT) {
146 streamType = MUSIC;
147 }
148 if (sampleRate == 0) {
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800149 sampleRate = afSampleRate;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700150 }
151 // these below should probably come from the audioFlinger too...
152 if (format == 0) {
153 format = AudioSystem::PCM_16_BIT;
154 }
155 if (channelCount == 0) {
156 channelCount = 2;
157 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700158
159 // validate parameters
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800160 if (((format != AudioSystem::PCM_8_BIT) || mSharedBuffer != 0) &&
161 (format != AudioSystem::PCM_16_BIT)) {
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700162 LOGE("Invalid format");
163 return BAD_VALUE;
164 }
165 if (channelCount != 1 && channelCount != 2) {
166 LOGE("Invalid channel number");
167 return BAD_VALUE;
168 }
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800169
170 // Ensure that buffer depth covers at least audio hardware latency
171 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
172 // When playing from shared buffer, playback will start even if last audioflinger
173 // block is partly filled.
174 if (sharedBuffer != 0 && minBufCount > 1) {
175 minBufCount--;
176 }
177
178 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
179
180 if (sharedBuffer == 0) {
181 if (frameCount == 0) {
182 frameCount = minFrameCount;
183 }
184 if (notificationFrames == 0) {
185 notificationFrames = frameCount/2;
186 }
187 // Make sure that application is notified with sufficient margin
188 // before underrun
189 if (notificationFrames > frameCount/2) {
190 notificationFrames = frameCount/2;
191 }
192 } else {
193 // Ensure that buffer alignment matches channelcount
194 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
195 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
196 return BAD_VALUE;
197 }
198 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
199 }
200
201 if (frameCount < minFrameCount) {
202 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
203 return BAD_VALUE;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700204 }
205
206 // create the track
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800207 status_t status;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700208 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800209 streamType, sampleRate, format, channelCount, frameCount, flags, sharedBuffer, &status);
210
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700211 if (track == 0) {
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800212 LOGE("AudioFlinger could not create track, status: %d", status);
213 return status;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700214 }
215 sp<IMemory> cblk = track->getCblk();
216 if (cblk == 0) {
217 LOGE("Could not get control block");
218 return NO_INIT;
219 }
220 if (cbf != 0) {
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800221 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700222 if (mAudioTrackThread == 0) {
223 LOGE("Could not create callback thread");
224 return NO_INIT;
225 }
226 }
227
228 mStatus = NO_ERROR;
229
230 mAudioFlinger = audioFlinger;
231 mAudioTrack = track;
232 mCblkMemory = cblk;
233 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
The Android Open Source Projectcce8bd12009-01-09 17:51:23 -0800234 mCblk->out = 1;
235 // Update buffer size in case it has been limited by AudioFlinger during track creation
236 mFrameCount = mCblk->frameCount;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800237 if (sharedBuffer == 0) {
238 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
239 } else {
240 mCblk->buffers = sharedBuffer->pointer();
The Android Open Source Projectcce8bd12009-01-09 17:51:23 -0800241 // Force buffer full condition as data is already present in shared memory
242 mCblk->stepUser(mFrameCount);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800243 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700244 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
245 mVolume[LEFT] = 1.0f;
246 mVolume[RIGHT] = 1.0f;
247 mSampleRate = sampleRate;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700248 mStreamType = streamType;
249 mFormat = format;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700250 mChannelCount = channelCount;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800251 mSharedBuffer = sharedBuffer;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700252 mMuted = false;
253 mActive = 0;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700254 mCbf = cbf;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800255 mNotificationFrames = notificationFrames;
256 mRemainingFrames = notificationFrames;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700257 mUserData = user;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800258 mLatency = afLatency + (1000*mFrameCount) / mSampleRate;
259 mLoopCount = 0;
260 mMarkerPosition = 0;
261 mNewPosition = 0;
262 mUpdatePeriod = 0;
263
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700264 return NO_ERROR;
265}
266
267status_t AudioTrack::initCheck() const
268{
269 return mStatus;
270}
271
272// -------------------------------------------------------------------------
273
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800274uint32_t AudioTrack::latency() const
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700275{
276 return mLatency;
277}
278
279int AudioTrack::streamType() const
280{
281 return mStreamType;
282}
283
284uint32_t AudioTrack::sampleRate() const
285{
286 return mSampleRate;
287}
288
289int AudioTrack::format() const
290{
291 return mFormat;
292}
293
294int AudioTrack::channelCount() const
295{
296 return mChannelCount;
297}
298
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800299uint32_t AudioTrack::frameCount() const
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700300{
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800301 return mFrameCount;
302}
303
304int AudioTrack::frameSize() const
305{
306 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
307}
308
309sp<IMemory>& AudioTrack::sharedBuffer()
310{
311 return mSharedBuffer;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700312}
313
314// -------------------------------------------------------------------------
315
316void AudioTrack::start()
317{
318 sp<AudioTrackThread> t = mAudioTrackThread;
319
320 LOGV("start");
321 if (t != 0) {
322 if (t->exitPending()) {
323 if (t->requestExitAndWait() == WOULD_BLOCK) {
324 LOGE("AudioTrack::start called from thread");
325 return;
326 }
327 }
328 t->mLock.lock();
329 }
330
331 if (android_atomic_or(1, &mActive) == 0) {
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800332 mNewPosition = mCblk->server + mUpdatePeriod;
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800333 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
334 mCblk->waitTimeMs = 0;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700335 if (t != 0) {
336 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
337 } else {
338 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
339 }
340 mAudioTrack->start();
341 }
342
343 if (t != 0) {
344 t->mLock.unlock();
345 }
346}
347
348void AudioTrack::stop()
349{
350 sp<AudioTrackThread> t = mAudioTrackThread;
351
352 LOGV("stop");
353 if (t != 0) {
354 t->mLock.lock();
355 }
356
357 if (android_atomic_and(~1, &mActive) == 1) {
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700358 mAudioTrack->stop();
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800359 // Cancel loops (If we are in the middle of a loop, playback
360 // would not stop until loopCount reaches 0).
361 setLoop(0, 0, 0);
362 // Force flush if a shared buffer is used otherwise audioflinger
363 // will not stop before end of buffer is reached.
364 if (mSharedBuffer != 0) {
365 flush();
366 }
367 if (t != 0) {
368 t->requestExit();
369 } else {
370 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
371 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700372 }
373
374 if (t != 0) {
375 t->mLock.unlock();
376 }
377}
378
379bool AudioTrack::stopped() const
380{
381 return !mActive;
382}
383
384void AudioTrack::flush()
385{
386 LOGV("flush");
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800387
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700388 if (!mActive) {
389 mCblk->lock.lock();
390 mAudioTrack->flush();
391 // Release AudioTrack callback thread in case it was waiting for new buffers
392 // in AudioTrack::obtainBuffer()
393 mCblk->cv.signal();
394 mCblk->lock.unlock();
395 }
396}
397
398void AudioTrack::pause()
399{
400 LOGV("pause");
401 if (android_atomic_and(~1, &mActive) == 1) {
402 mActive = 0;
403 mAudioTrack->pause();
404 }
405}
406
407void AudioTrack::mute(bool e)
408{
409 mAudioTrack->mute(e);
410 mMuted = e;
411}
412
413bool AudioTrack::muted() const
414{
415 return mMuted;
416}
417
418void AudioTrack::setVolume(float left, float right)
419{
420 mVolume[LEFT] = left;
421 mVolume[RIGHT] = right;
422
423 // write must be atomic
424 mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000);
425}
426
427void AudioTrack::getVolume(float* left, float* right)
428{
429 *left = mVolume[LEFT];
430 *right = mVolume[RIGHT];
431}
432
433void AudioTrack::setSampleRate(int rate)
434{
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800435 int afSamplingRate;
436
437 if (AudioSystem::getOutputSamplingRate(&afSamplingRate) != NO_ERROR) {
438 return;
439 }
440 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
441 if (rate > afSamplingRate*2) rate = afSamplingRate*2;
442
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700443 if (rate > MAX_SAMPLE_RATE) rate = MAX_SAMPLE_RATE;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800444
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700445 mCblk->sampleRate = rate;
446}
447
448uint32_t AudioTrack::getSampleRate()
449{
450 return uint32_t(mCblk->sampleRate);
451}
452
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800453status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
454{
455 audio_track_cblk_t* cblk = mCblk;
456
457
458 Mutex::Autolock _l(cblk->lock);
459
460 if (loopCount == 0) {
461 cblk->loopStart = UINT_MAX;
462 cblk->loopEnd = UINT_MAX;
463 cblk->loopCount = 0;
464 mLoopCount = 0;
465 return NO_ERROR;
466 }
467
468 if (loopStart >= loopEnd ||
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800469 loopEnd - loopStart > mFrameCount) {
470 LOGW("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user);
471 return BAD_VALUE;
472 }
473 // TODO handle shared buffer here: limit loop end to framecount
474
475 cblk->loopStart = loopStart;
476 cblk->loopEnd = loopEnd;
477 cblk->loopCount = loopCount;
478 mLoopCount = loopCount;
479
480 return NO_ERROR;
481}
482
483status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
484{
485 if (loopStart != 0) {
486 *loopStart = mCblk->loopStart;
487 }
488 if (loopEnd != 0) {
489 *loopEnd = mCblk->loopEnd;
490 }
491 if (loopCount != 0) {
492 if (mCblk->loopCount < 0) {
493 *loopCount = -1;
494 } else {
495 *loopCount = mCblk->loopCount;
496 }
497 }
498
499 return NO_ERROR;
500}
501
502status_t AudioTrack::setMarkerPosition(uint32_t marker)
503{
504 if (mCbf == 0) return INVALID_OPERATION;
505
506 mMarkerPosition = marker;
507
508 return NO_ERROR;
509}
510
511status_t AudioTrack::getMarkerPosition(uint32_t *marker)
512{
513 if (marker == 0) return BAD_VALUE;
514
515 *marker = mMarkerPosition;
516
517 return NO_ERROR;
518}
519
520status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
521{
522 if (mCbf == 0) return INVALID_OPERATION;
523
524 uint32_t curPosition;
525 getPosition(&curPosition);
526 mNewPosition = curPosition + updatePeriod;
527 mUpdatePeriod = updatePeriod;
528
529 return NO_ERROR;
530}
531
532status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
533{
534 if (updatePeriod == 0) return BAD_VALUE;
535
536 *updatePeriod = mUpdatePeriod;
537
538 return NO_ERROR;
539}
540
541status_t AudioTrack::setPosition(uint32_t position)
542{
543 Mutex::Autolock _l(mCblk->lock);
544
545 if (!stopped()) return INVALID_OPERATION;
546
547 if (position > mCblk->user) return BAD_VALUE;
548
549 mCblk->server = position;
550 mCblk->forceReady = 1;
551
552 return NO_ERROR;
553}
554
555status_t AudioTrack::getPosition(uint32_t *position)
556{
557 if (position == 0) return BAD_VALUE;
558
559 *position = mCblk->server;
560
561 return NO_ERROR;
562}
563
564status_t AudioTrack::reload()
565{
566 if (!stopped()) return INVALID_OPERATION;
567
568 flush();
569
570 mCblk->stepUser(mFrameCount);
571
572 return NO_ERROR;
573}
574
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700575// -------------------------------------------------------------------------
576
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800577status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700578{
579 int active;
580 int timeout = 0;
581 status_t result;
582 audio_track_cblk_t* cblk = mCblk;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800583 uint32_t framesReq = audioBuffer->frameCount;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700584
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800585 audioBuffer->frameCount = 0;
586 audioBuffer->size = 0;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700587
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800588 uint32_t framesAvail = cblk->framesAvailable();
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700589
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800590 if (framesAvail == 0) {
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700591 Mutex::Autolock _l(cblk->lock);
592 goto start_loop_here;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800593 while (framesAvail == 0) {
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700594 active = mActive;
595 if (UNLIKELY(!active)) {
596 LOGV("Not active and NO_MORE_BUFFERS");
597 return NO_MORE_BUFFERS;
598 }
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800599 if (UNLIKELY(!waitCount))
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700600 return WOULD_BLOCK;
601 timeout = 0;
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800602 result = cblk->cv.waitRelative(cblk->lock, milliseconds(WAIT_PERIOD_MS));
603 if (__builtin_expect(result!=NO_ERROR, false)) {
604 cblk->waitTimeMs += WAIT_PERIOD_MS;
605 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
606 LOGW( "obtainBuffer timed out (is the CPU pegged?) "
607 "user=%08x, server=%08x", cblk->user, cblk->server);
608 mAudioTrack->start(); // FIXME: Wake up audioflinger
609 timeout = 1;
610 cblk->waitTimeMs = 0;
611 }
612 ;
613 if (--waitCount == 0) {
614 return TIMED_OUT;
615 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700616 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700617 // read the server count again
618 start_loop_here:
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800619 framesAvail = cblk->framesAvailable_l();
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700620 }
621 }
622
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800623 cblk->waitTimeMs = 0;
624
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800625 if (framesReq > framesAvail) {
626 framesReq = framesAvail;
627 }
628
629 uint32_t u = cblk->user;
630 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
631
632 if (u + framesReq > bufferEnd) {
633 framesReq = bufferEnd - u;
634 }
635
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700636 LOGW_IF(timeout,
637 "*** SERIOUS WARNING *** obtainBuffer() timed out "
638 "but didn't need to be locked. We recovered, but "
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800639 "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700640
641 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
642 audioBuffer->channelCount= mChannelCount;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800643 audioBuffer->format = AudioSystem::PCM_16_BIT;
644 audioBuffer->frameCount = framesReq;
645 audioBuffer->size = framesReq*mChannelCount*sizeof(int16_t);
646 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700647 active = mActive;
648 return active ? status_t(NO_ERROR) : status_t(STOPPED);
649}
650
651void AudioTrack::releaseBuffer(Buffer* audioBuffer)
652{
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700653 audio_track_cblk_t* cblk = mCblk;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800654 cblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700655}
656
657// -------------------------------------------------------------------------
658
659ssize_t AudioTrack::write(const void* buffer, size_t userSize)
660{
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800661
662 if (mSharedBuffer != 0) return INVALID_OPERATION;
663
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700664 if (ssize_t(userSize) < 0) {
665 // sanity-check. user is most-likely passing an error code.
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800666 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700667 buffer, userSize, userSize);
668 return BAD_VALUE;
669 }
670
671 LOGV("write %d bytes, mActive=%d", userSize, mActive);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800672
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700673 ssize_t written = 0;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800674 const int8_t *src = (const int8_t *)buffer;
675 Buffer audioBuffer;
676
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700677 do {
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800678 audioBuffer.frameCount = userSize/mChannelCount;
679 if (mFormat == AudioSystem::PCM_16_BIT) {
680 audioBuffer.frameCount >>= 1;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700681 }
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800682 // Calling obtainBuffer() with a negative wait count causes
683 // an (almost) infinite wait time.
684 status_t err = obtainBuffer(&audioBuffer, -1);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800685 if (err < 0) {
686 // out of buffers, return #bytes written
687 if (err == status_t(NO_MORE_BUFFERS))
688 break;
689 return ssize_t(err);
690 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700691
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800692 size_t toWrite;
693 if (mFormat == AudioSystem::PCM_8_BIT) {
694 // Divide capacity by 2 to take expansion into account
695 toWrite = audioBuffer.size>>1;
696 // 8 to 16 bit conversion
697 int count = toWrite;
698 int16_t *dst = (int16_t *)(audioBuffer.i8);
699 while(count--) {
700 *dst++ = (int16_t)(*src++^0x80) << 8;
701 }
702 }else {
703 toWrite = audioBuffer.size;
704 memcpy(audioBuffer.i8, src, toWrite);
705 src += toWrite;
706 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700707 userSize -= toWrite;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700708 written += toWrite;
709
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800710 releaseBuffer(&audioBuffer);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700711 } while (userSize);
712
713 return written;
714}
715
716// -------------------------------------------------------------------------
717
718bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
719{
720 Buffer audioBuffer;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800721 uint32_t frames;
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800722 size_t writtenSize;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700723
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800724 // Manage underrun callback
725 if (mActive && (mCblk->framesReady() == 0)) {
726 LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
727 if (mCblk->flowControlFlag == 0) {
728 mCbf(EVENT_UNDERRUN, mUserData, 0);
729 if (mCblk->server == mCblk->frameCount) {
730 mCbf(EVENT_BUFFER_END, mUserData, 0);
731 }
732 mCblk->flowControlFlag = 1;
733 if (mSharedBuffer != 0) return false;
734 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700735 }
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800736
737 // Manage loop end callback
738 while (mLoopCount > mCblk->loopCount) {
739 int loopCount = -1;
740 mLoopCount--;
741 if (mLoopCount >= 0) loopCount = mLoopCount;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700742
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800743 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
744 }
745
746 // Manage marker callback
747 if(mMarkerPosition > 0) {
748 if (mCblk->server >= mMarkerPosition) {
749 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
750 mMarkerPosition = 0;
751 }
752 }
753
754 // Manage new position callback
755 if(mUpdatePeriod > 0) {
756 while (mCblk->server >= mNewPosition) {
757 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
758 mNewPosition += mUpdatePeriod;
759 }
760 }
761
762 // If Shared buffer is used, no data is requested from client.
763 if (mSharedBuffer != 0) {
764 frames = 0;
765 } else {
766 frames = mRemainingFrames;
767 }
768
769 do {
770
771 audioBuffer.frameCount = frames;
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800772
773 // Calling obtainBuffer() with a wait count of 1
774 // limits wait time to WAIT_PERIOD_MS. This prevents from being
775 // stuck here not being able to handle timed events (position, markers, loops).
776 status_t err = obtainBuffer(&audioBuffer, 1);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800777 if (err < NO_ERROR) {
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800778 if (err != TIMED_OUT) {
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800779 LOGE("Error obtaining an audio buffer, giving up.");
780 return false;
781 }
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800782 break;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800783 }
784 if (err == status_t(STOPPED)) return false;
785
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800786 // Divide buffer size by 2 to take into account the expansion
787 // due to 8 to 16 bit conversion: the callback must fill only half
788 // of the destination buffer
789 if (mFormat == AudioSystem::PCM_8_BIT) {
790 audioBuffer.size >>= 1;
791 }
792
793 size_t reqSize = audioBuffer.size;
794 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
795 writtenSize = audioBuffer.size;
796
797 // Sanity check on returned size
798 if (ssize_t(writtenSize) <= 0) break;
799 if (writtenSize > reqSize) writtenSize = reqSize;
800
801 if (mFormat == AudioSystem::PCM_8_BIT) {
802 // 8 to 16 bit conversion
803 const int8_t *src = audioBuffer.i8 + writtenSize-1;
804 int count = writtenSize;
805 int16_t *dst = audioBuffer.i16 + writtenSize-1;
806 while(count--) {
807 *dst-- = (int16_t)(*src--^0x80) << 8;
808 }
809 writtenSize <<= 1;
810 }
811
812 audioBuffer.size = writtenSize;
813 audioBuffer.frameCount = writtenSize/mChannelCount/sizeof(int16_t);
814 frames -= audioBuffer.frameCount;
815
816 releaseBuffer(&audioBuffer);
817 }
818 while (frames);
819
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800820 if (frames == 0) {
821 mRemainingFrames = mNotificationFrames;
822 } else {
823 mRemainingFrames = frames;
824 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700825 return true;
826}
827
828status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
829{
830
831 const size_t SIZE = 256;
832 char buffer[SIZE];
833 String8 result;
834
835 result.append(" AudioTrack::dump\n");
836 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
837 result.append(buffer);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800838 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mFrameCount);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700839 result.append(buffer);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800840 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", mSampleRate, mStatus, mMuted);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700841 result.append(buffer);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800842 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700843 result.append(buffer);
844 ::write(fd, result.string(), result.size());
845 return NO_ERROR;
846}
847
848// =========================================================================
849
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800850AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
851 : Thread(bCanCallJava), mReceiver(receiver)
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700852{
853}
854
855bool AudioTrack::AudioTrackThread::threadLoop()
856{
857 return mReceiver.processAudioBuffer(this);
858}
859
860status_t AudioTrack::AudioTrackThread::readyToRun()
861{
862 return NO_ERROR;
863}
864
865void AudioTrack::AudioTrackThread::onFirstRef()
866{
867}
868
869// =========================================================================
870
871audio_track_cblk_t::audio_track_cblk_t()
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800872 : user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
873 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0)
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700874{
875}
876
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800877uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700878{
879 uint32_t u = this->user;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800880
881 u += frameCount;
882 // Ensure that user is never ahead of server for AudioRecord
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800883 if (out) {
884 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
885 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
886 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
887 }
888 } else if (u > this->server) {
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800889 LOGW("stepServer occured after track reset");
890 u = this->server;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700891 }
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800892
893 if (u >= userBase + this->frameCount) {
894 userBase += this->frameCount;
895 }
896
897 this->user = u;
898
899 // Clear flow control error condition as new data has been written/read to/from buffer.
900 flowControlFlag = 0;
901
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700902 return u;
903}
904
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800905bool audio_track_cblk_t::stepServer(uint32_t frameCount)
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700906{
907 // the code below simulates lock-with-timeout
908 // we MUST do this to protect the AudioFlinger server
909 // as this lock is shared with the client.
910 status_t err;
911
912 err = lock.tryLock();
913 if (err == -EBUSY) { // just wait a bit
914 usleep(1000);
915 err = lock.tryLock();
916 }
917 if (err != NO_ERROR) {
918 // probably, the client just died.
919 return false;
920 }
921
922 uint32_t s = this->server;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700923
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800924 s += frameCount;
The Android Open Source Projecte5198b62009-01-20 14:03:58 -0800925 if (out) {
926 // Mark that we have read the first buffer so that next time stepUser() is called
927 // we switch to normal obtainBuffer() timeout period
928 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
929 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS - 1;
930 }
931 // It is possible that we receive a flush()
932 // while the mixer is processing a block: in this case,
933 // stepServer() is called After the flush() has reset u & s and
934 // we have s > u
935 if (s > this->user) {
936 LOGW("stepServer occured after track reset");
937 s = this->user;
938 }
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800939 }
940
941 if (s >= loopEnd) {
942 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
943 s = loopStart;
944 if (--loopCount == 0) {
945 loopEnd = UINT_MAX;
946 loopStart = UINT_MAX;
947 }
948 }
949 if (s >= serverBase + this->frameCount) {
950 serverBase += this->frameCount;
951 }
952
953 this->server = s;
954
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700955 cv.signal();
956 lock.unlock();
957 return true;
958}
959
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800960void* audio_track_cblk_t::buffer(uint32_t offset) const
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700961{
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800962 return (int16_t *)this->buffers + (offset-userBase)*this->channels;
963}
964
965uint32_t audio_track_cblk_t::framesAvailable()
966{
967 Mutex::Autolock _l(lock);
968 return framesAvailable_l();
969}
970
971uint32_t audio_track_cblk_t::framesAvailable_l()
972{
973 uint32_t u = this->user;
974 uint32_t s = this->server;
975
976 if (out) {
The Android Open Source Projectcce8bd12009-01-09 17:51:23 -0800977 uint32_t limit = (s < loopStart) ? s : loopStart;
978 return limit + frameCount - u;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800979 } else {
980 return frameCount + u - s;
981 }
982}
983
984uint32_t audio_track_cblk_t::framesReady()
985{
986 uint32_t u = this->user;
987 uint32_t s = this->server;
988
989 if (out) {
990 if (u < loopEnd) {
991 return u - s;
992 } else {
993 Mutex::Autolock _l(lock);
994 if (loopCount >= 0) {
995 return (loopEnd - loopStart)*loopCount + u - s;
996 } else {
997 return UINT_MAX;
998 }
999 }
1000 } else {
1001 return s - u;
1002 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -07001003}
1004
1005// -------------------------------------------------------------------------
1006
1007}; // namespace android
1008