blob: ce65312020ab6212dd9ace595b569d070aa72ec5 [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 Project2729ea92008-10-21 07:00:00 -0700333 if (t != 0) {
334 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
335 } else {
336 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
337 }
338 mAudioTrack->start();
339 }
340
341 if (t != 0) {
342 t->mLock.unlock();
343 }
344}
345
346void AudioTrack::stop()
347{
348 sp<AudioTrackThread> t = mAudioTrackThread;
349
350 LOGV("stop");
351 if (t != 0) {
352 t->mLock.lock();
353 }
354
355 if (android_atomic_and(~1, &mActive) == 1) {
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700356 mAudioTrack->stop();
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800357 // Cancel loops (If we are in the middle of a loop, playback
358 // would not stop until loopCount reaches 0).
359 setLoop(0, 0, 0);
360 // Force flush if a shared buffer is used otherwise audioflinger
361 // will not stop before end of buffer is reached.
362 if (mSharedBuffer != 0) {
363 flush();
364 }
365 if (t != 0) {
366 t->requestExit();
367 } else {
368 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
369 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700370 }
371
372 if (t != 0) {
373 t->mLock.unlock();
374 }
375}
376
377bool AudioTrack::stopped() const
378{
379 return !mActive;
380}
381
382void AudioTrack::flush()
383{
384 LOGV("flush");
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800385
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700386 if (!mActive) {
387 mCblk->lock.lock();
388 mAudioTrack->flush();
389 // Release AudioTrack callback thread in case it was waiting for new buffers
390 // in AudioTrack::obtainBuffer()
391 mCblk->cv.signal();
392 mCblk->lock.unlock();
393 }
394}
395
396void AudioTrack::pause()
397{
398 LOGV("pause");
399 if (android_atomic_and(~1, &mActive) == 1) {
400 mActive = 0;
401 mAudioTrack->pause();
402 }
403}
404
405void AudioTrack::mute(bool e)
406{
407 mAudioTrack->mute(e);
408 mMuted = e;
409}
410
411bool AudioTrack::muted() const
412{
413 return mMuted;
414}
415
416void AudioTrack::setVolume(float left, float right)
417{
418 mVolume[LEFT] = left;
419 mVolume[RIGHT] = right;
420
421 // write must be atomic
422 mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000);
423}
424
425void AudioTrack::getVolume(float* left, float* right)
426{
427 *left = mVolume[LEFT];
428 *right = mVolume[RIGHT];
429}
430
431void AudioTrack::setSampleRate(int rate)
432{
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800433 int afSamplingRate;
434
435 if (AudioSystem::getOutputSamplingRate(&afSamplingRate) != NO_ERROR) {
436 return;
437 }
438 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
439 if (rate > afSamplingRate*2) rate = afSamplingRate*2;
440
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700441 if (rate > MAX_SAMPLE_RATE) rate = MAX_SAMPLE_RATE;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800442
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700443 mCblk->sampleRate = rate;
444}
445
446uint32_t AudioTrack::getSampleRate()
447{
448 return uint32_t(mCblk->sampleRate);
449}
450
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800451status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
452{
453 audio_track_cblk_t* cblk = mCblk;
454
455
456 Mutex::Autolock _l(cblk->lock);
457
458 if (loopCount == 0) {
459 cblk->loopStart = UINT_MAX;
460 cblk->loopEnd = UINT_MAX;
461 cblk->loopCount = 0;
462 mLoopCount = 0;
463 return NO_ERROR;
464 }
465
466 if (loopStart >= loopEnd ||
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800467 loopEnd - loopStart > mFrameCount) {
468 LOGW("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user);
469 return BAD_VALUE;
470 }
471 // TODO handle shared buffer here: limit loop end to framecount
472
473 cblk->loopStart = loopStart;
474 cblk->loopEnd = loopEnd;
475 cblk->loopCount = loopCount;
476 mLoopCount = loopCount;
477
478 return NO_ERROR;
479}
480
481status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
482{
483 if (loopStart != 0) {
484 *loopStart = mCblk->loopStart;
485 }
486 if (loopEnd != 0) {
487 *loopEnd = mCblk->loopEnd;
488 }
489 if (loopCount != 0) {
490 if (mCblk->loopCount < 0) {
491 *loopCount = -1;
492 } else {
493 *loopCount = mCblk->loopCount;
494 }
495 }
496
497 return NO_ERROR;
498}
499
500status_t AudioTrack::setMarkerPosition(uint32_t marker)
501{
502 if (mCbf == 0) return INVALID_OPERATION;
503
504 mMarkerPosition = marker;
505
506 return NO_ERROR;
507}
508
509status_t AudioTrack::getMarkerPosition(uint32_t *marker)
510{
511 if (marker == 0) return BAD_VALUE;
512
513 *marker = mMarkerPosition;
514
515 return NO_ERROR;
516}
517
518status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
519{
520 if (mCbf == 0) return INVALID_OPERATION;
521
522 uint32_t curPosition;
523 getPosition(&curPosition);
524 mNewPosition = curPosition + updatePeriod;
525 mUpdatePeriod = updatePeriod;
526
527 return NO_ERROR;
528}
529
530status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
531{
532 if (updatePeriod == 0) return BAD_VALUE;
533
534 *updatePeriod = mUpdatePeriod;
535
536 return NO_ERROR;
537}
538
539status_t AudioTrack::setPosition(uint32_t position)
540{
541 Mutex::Autolock _l(mCblk->lock);
542
543 if (!stopped()) return INVALID_OPERATION;
544
545 if (position > mCblk->user) return BAD_VALUE;
546
547 mCblk->server = position;
548 mCblk->forceReady = 1;
549
550 return NO_ERROR;
551}
552
553status_t AudioTrack::getPosition(uint32_t *position)
554{
555 if (position == 0) return BAD_VALUE;
556
557 *position = mCblk->server;
558
559 return NO_ERROR;
560}
561
562status_t AudioTrack::reload()
563{
564 if (!stopped()) return INVALID_OPERATION;
565
566 flush();
567
568 mCblk->stepUser(mFrameCount);
569
570 return NO_ERROR;
571}
572
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700573// -------------------------------------------------------------------------
574
575status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, bool blocking)
576{
577 int active;
578 int timeout = 0;
579 status_t result;
580 audio_track_cblk_t* cblk = mCblk;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800581 uint32_t framesReq = audioBuffer->frameCount;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700582
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800583 audioBuffer->frameCount = 0;
584 audioBuffer->size = 0;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700585
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800586 uint32_t framesAvail = cblk->framesAvailable();
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700587
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800588 if (framesAvail == 0) {
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700589 Mutex::Autolock _l(cblk->lock);
590 goto start_loop_here;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800591 while (framesAvail == 0) {
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700592 active = mActive;
593 if (UNLIKELY(!active)) {
594 LOGV("Not active and NO_MORE_BUFFERS");
595 return NO_MORE_BUFFERS;
596 }
597 if (UNLIKELY(!blocking))
598 return WOULD_BLOCK;
599 timeout = 0;
600 result = cblk->cv.waitRelative(cblk->lock, seconds(1));
601 if (__builtin_expect(result!=NO_ERROR, false)) {
602 LOGW( "obtainBuffer timed out (is the CPU pegged?) "
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800603 "user=%08x, server=%08x", cblk->user, cblk->server);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700604 mAudioTrack->start(); // FIXME: Wake up audioflinger
605 timeout = 1;
606 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700607 // read the server count again
608 start_loop_here:
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800609 framesAvail = cblk->framesAvailable_l();
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700610 }
611 }
612
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800613 if (framesReq > framesAvail) {
614 framesReq = framesAvail;
615 }
616
617 uint32_t u = cblk->user;
618 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
619
620 if (u + framesReq > bufferEnd) {
621 framesReq = bufferEnd - u;
622 }
623
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700624 LOGW_IF(timeout,
625 "*** SERIOUS WARNING *** obtainBuffer() timed out "
626 "but didn't need to be locked. We recovered, but "
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800627 "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700628
629 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
630 audioBuffer->channelCount= mChannelCount;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800631 audioBuffer->format = AudioSystem::PCM_16_BIT;
632 audioBuffer->frameCount = framesReq;
633 audioBuffer->size = framesReq*mChannelCount*sizeof(int16_t);
634 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700635 active = mActive;
636 return active ? status_t(NO_ERROR) : status_t(STOPPED);
637}
638
639void AudioTrack::releaseBuffer(Buffer* audioBuffer)
640{
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700641 audio_track_cblk_t* cblk = mCblk;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800642 cblk->stepUser(audioBuffer->frameCount);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700643}
644
645// -------------------------------------------------------------------------
646
647ssize_t AudioTrack::write(const void* buffer, size_t userSize)
648{
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800649
650 if (mSharedBuffer != 0) return INVALID_OPERATION;
651
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700652 if (ssize_t(userSize) < 0) {
653 // sanity-check. user is most-likely passing an error code.
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800654 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700655 buffer, userSize, userSize);
656 return BAD_VALUE;
657 }
658
659 LOGV("write %d bytes, mActive=%d", userSize, mActive);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800660
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700661 ssize_t written = 0;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800662 const int8_t *src = (const int8_t *)buffer;
663 Buffer audioBuffer;
664
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700665 do {
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800666 audioBuffer.frameCount = userSize/mChannelCount;
667 if (mFormat == AudioSystem::PCM_16_BIT) {
668 audioBuffer.frameCount >>= 1;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700669 }
670
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800671 status_t err = obtainBuffer(&audioBuffer, true);
672 if (err < 0) {
673 // out of buffers, return #bytes written
674 if (err == status_t(NO_MORE_BUFFERS))
675 break;
676 return ssize_t(err);
677 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700678
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800679 size_t toWrite;
680 if (mFormat == AudioSystem::PCM_8_BIT) {
681 // Divide capacity by 2 to take expansion into account
682 toWrite = audioBuffer.size>>1;
683 // 8 to 16 bit conversion
684 int count = toWrite;
685 int16_t *dst = (int16_t *)(audioBuffer.i8);
686 while(count--) {
687 *dst++ = (int16_t)(*src++^0x80) << 8;
688 }
689 }else {
690 toWrite = audioBuffer.size;
691 memcpy(audioBuffer.i8, src, toWrite);
692 src += toWrite;
693 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700694 userSize -= toWrite;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700695 written += toWrite;
696
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800697 releaseBuffer(&audioBuffer);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700698 } while (userSize);
699
700 return written;
701}
702
703// -------------------------------------------------------------------------
704
705bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
706{
707 Buffer audioBuffer;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800708 uint32_t frames;
709 size_t writtenSize = 0;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700710
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800711 // Manage underrun callback
712 if (mActive && (mCblk->framesReady() == 0)) {
713 LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
714 if (mCblk->flowControlFlag == 0) {
715 mCbf(EVENT_UNDERRUN, mUserData, 0);
716 if (mCblk->server == mCblk->frameCount) {
717 mCbf(EVENT_BUFFER_END, mUserData, 0);
718 }
719 mCblk->flowControlFlag = 1;
720 if (mSharedBuffer != 0) return false;
721 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700722 }
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800723
724 // Manage loop end callback
725 while (mLoopCount > mCblk->loopCount) {
726 int loopCount = -1;
727 mLoopCount--;
728 if (mLoopCount >= 0) loopCount = mLoopCount;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700729
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800730 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
731 }
732
733 // Manage marker callback
734 if(mMarkerPosition > 0) {
735 if (mCblk->server >= mMarkerPosition) {
736 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
737 mMarkerPosition = 0;
738 }
739 }
740
741 // Manage new position callback
742 if(mUpdatePeriod > 0) {
743 while (mCblk->server >= mNewPosition) {
744 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
745 mNewPosition += mUpdatePeriod;
746 }
747 }
748
749 // If Shared buffer is used, no data is requested from client.
750 if (mSharedBuffer != 0) {
751 frames = 0;
752 } else {
753 frames = mRemainingFrames;
754 }
755
756 do {
757
758 audioBuffer.frameCount = frames;
759
760 status_t err = obtainBuffer(&audioBuffer, false);
761 if (err < NO_ERROR) {
762 if (err != WOULD_BLOCK) {
763 LOGE("Error obtaining an audio buffer, giving up.");
764 return false;
765 }
766 }
767 if (err == status_t(STOPPED)) return false;
768
769 if (audioBuffer.size == 0) break;
770
771 // Divide buffer size by 2 to take into account the expansion
772 // due to 8 to 16 bit conversion: the callback must fill only half
773 // of the destination buffer
774 if (mFormat == AudioSystem::PCM_8_BIT) {
775 audioBuffer.size >>= 1;
776 }
777
778 size_t reqSize = audioBuffer.size;
779 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
780 writtenSize = audioBuffer.size;
781
782 // Sanity check on returned size
783 if (ssize_t(writtenSize) <= 0) break;
784 if (writtenSize > reqSize) writtenSize = reqSize;
785
786 if (mFormat == AudioSystem::PCM_8_BIT) {
787 // 8 to 16 bit conversion
788 const int8_t *src = audioBuffer.i8 + writtenSize-1;
789 int count = writtenSize;
790 int16_t *dst = audioBuffer.i16 + writtenSize-1;
791 while(count--) {
792 *dst-- = (int16_t)(*src--^0x80) << 8;
793 }
794 writtenSize <<= 1;
795 }
796
797 audioBuffer.size = writtenSize;
798 audioBuffer.frameCount = writtenSize/mChannelCount/sizeof(int16_t);
799 frames -= audioBuffer.frameCount;
800
801 releaseBuffer(&audioBuffer);
802 }
803 while (frames);
804
805 // If no data was written, it is likely that obtainBuffer() did
806 // not find room in PCM buffer: we release the processor for
807 // a few millisecond before polling again for available room.
808 if (writtenSize == 0) {
809 usleep(5000);
810 }
811
812 if (frames == 0) {
813 mRemainingFrames = mNotificationFrames;
814 } else {
815 mRemainingFrames = frames;
816 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700817 return true;
818}
819
820status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
821{
822
823 const size_t SIZE = 256;
824 char buffer[SIZE];
825 String8 result;
826
827 result.append(" AudioTrack::dump\n");
828 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
829 result.append(buffer);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800830 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 -0700831 result.append(buffer);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800832 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", mSampleRate, mStatus, mMuted);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700833 result.append(buffer);
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800834 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700835 result.append(buffer);
836 ::write(fd, result.string(), result.size());
837 return NO_ERROR;
838}
839
840// =========================================================================
841
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800842AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
843 : Thread(bCanCallJava), mReceiver(receiver)
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700844{
845}
846
847bool AudioTrack::AudioTrackThread::threadLoop()
848{
849 return mReceiver.processAudioBuffer(this);
850}
851
852status_t AudioTrack::AudioTrackThread::readyToRun()
853{
854 return NO_ERROR;
855}
856
857void AudioTrack::AudioTrackThread::onFirstRef()
858{
859}
860
861// =========================================================================
862
863audio_track_cblk_t::audio_track_cblk_t()
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800864 : user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
865 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0)
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700866{
867}
868
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800869uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700870{
871 uint32_t u = this->user;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800872
873 u += frameCount;
874 // Ensure that user is never ahead of server for AudioRecord
875 if (!out && u > this->server) {
876 LOGW("stepServer occured after track reset");
877 u = this->server;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700878 }
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800879
880 if (u >= userBase + this->frameCount) {
881 userBase += this->frameCount;
882 }
883
884 this->user = u;
885
886 // Clear flow control error condition as new data has been written/read to/from buffer.
887 flowControlFlag = 0;
888
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700889 return u;
890}
891
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800892bool audio_track_cblk_t::stepServer(uint32_t frameCount)
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700893{
894 // the code below simulates lock-with-timeout
895 // we MUST do this to protect the AudioFlinger server
896 // as this lock is shared with the client.
897 status_t err;
898
899 err = lock.tryLock();
900 if (err == -EBUSY) { // just wait a bit
901 usleep(1000);
902 err = lock.tryLock();
903 }
904 if (err != NO_ERROR) {
905 // probably, the client just died.
906 return false;
907 }
908
909 uint32_t s = this->server;
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700910
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800911 s += frameCount;
912 // It is possible that we receive a flush()
913 // while the mixer is processing a block: in this case,
914 // stepServer() is called After the flush() has reset u & s and
915 // we have s > u
916 if (out && s > this->user) {
917 LOGW("stepServer occured after track reset");
918 s = this->user;
919 }
920
921 if (s >= loopEnd) {
922 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
923 s = loopStart;
924 if (--loopCount == 0) {
925 loopEnd = UINT_MAX;
926 loopStart = UINT_MAX;
927 }
928 }
929 if (s >= serverBase + this->frameCount) {
930 serverBase += this->frameCount;
931 }
932
933 this->server = s;
934
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700935 cv.signal();
936 lock.unlock();
937 return true;
938}
939
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800940void* audio_track_cblk_t::buffer(uint32_t offset) const
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700941{
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800942 return (int16_t *)this->buffers + (offset-userBase)*this->channels;
943}
944
945uint32_t audio_track_cblk_t::framesAvailable()
946{
947 Mutex::Autolock _l(lock);
948 return framesAvailable_l();
949}
950
951uint32_t audio_track_cblk_t::framesAvailable_l()
952{
953 uint32_t u = this->user;
954 uint32_t s = this->server;
955
956 if (out) {
The Android Open Source Projectcce8bd12009-01-09 17:51:23 -0800957 uint32_t limit = (s < loopStart) ? s : loopStart;
958 return limit + frameCount - u;
The Android Open Source Project7b5eb022008-12-17 18:05:43 -0800959 } else {
960 return frameCount + u - s;
961 }
962}
963
964uint32_t audio_track_cblk_t::framesReady()
965{
966 uint32_t u = this->user;
967 uint32_t s = this->server;
968
969 if (out) {
970 if (u < loopEnd) {
971 return u - s;
972 } else {
973 Mutex::Autolock _l(lock);
974 if (loopCount >= 0) {
975 return (loopEnd - loopStart)*loopCount + u - s;
976 } else {
977 return UINT_MAX;
978 }
979 }
980 } else {
981 return s - u;
982 }
The Android Open Source Project2729ea92008-10-21 07:00:00 -0700983}
984
985// -------------------------------------------------------------------------
986
987}; // namespace android
988