blob: b147d256fdf6e7e0ff707c99a27d848f18ef7fa1 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/* //device/extlibs/pv/android/AudioTrack.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "AudioTrack"
21
22#include <stdint.h>
23#include <sys/types.h>
24#include <limits.h>
25
26#include <sched.h>
27#include <sys/resource.h>
28
29#include <private/media/AudioTrackShared.h>
30
31#include <media/AudioSystem.h>
32#include <media/AudioTrack.h>
33
34#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070035#include <binder/MemoryDealer.h>
36#include <binder/Parcel.h>
37#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038#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
48AudioTrack::AudioTrack()
49 : mStatus(NO_INIT)
50{
51}
52
53AudioTrack::AudioTrack(
54 int streamType,
55 uint32_t sampleRate,
56 int format,
Eric Laurenta553c252009-07-17 12:17:14 -070057 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 int frameCount,
59 uint32_t flags,
60 callback_t cbf,
61 void* user,
62 int notificationFrames)
63 : mStatus(NO_INIT)
64{
Eric Laurenta553c252009-07-17 12:17:14 -070065 mStatus = set(streamType, sampleRate, format, channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 frameCount, flags, cbf, user, notificationFrames, 0);
67}
68
69AudioTrack::AudioTrack(
70 int streamType,
71 uint32_t sampleRate,
72 int format,
Eric Laurenta553c252009-07-17 12:17:14 -070073 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 const sp<IMemory>& sharedBuffer,
75 uint32_t flags,
76 callback_t cbf,
77 void* user,
78 int notificationFrames)
79 : mStatus(NO_INIT)
80{
Eric Laurenta553c252009-07-17 12:17:14 -070081 mStatus = set(streamType, sampleRate, format, channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 0, flags, cbf, user, notificationFrames, sharedBuffer);
83}
84
85AudioTrack::~AudioTrack()
86{
87 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
88
89 if (mStatus == NO_ERROR) {
90 // 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();
94 if (mAudioTrackThread != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 mAudioTrackThread->requestExitAndWait();
96 mAudioTrackThread.clear();
97 }
98 mAudioTrack.clear();
99 IPCThreadState::self()->flushCommands();
Eric Laurenta553c252009-07-17 12:17:14 -0700100 AudioSystem::releaseOutput(getOutput());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 }
102}
103
104status_t AudioTrack::set(
105 int streamType,
106 uint32_t sampleRate,
107 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700108 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 int frameCount,
110 uint32_t flags,
111 callback_t cbf,
112 void* user,
113 int notificationFrames,
114 const sp<IMemory>& sharedBuffer,
115 bool threadCanCallJava)
116{
117
118 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
119
Eric Laurentef028272009-04-21 07:56:33 -0700120 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 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 }
130 int afSampleRate;
131 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
132 return NO_INIT;
133 }
134 int afFrameCount;
135 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
136 return NO_INIT;
137 }
138 uint32_t afLatency;
139 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
140 return NO_INIT;
141 }
142
143 // handle default values first.
144 if (streamType == AudioSystem::DEFAULT) {
145 streamType = AudioSystem::MUSIC;
146 }
147 if (sampleRate == 0) {
148 sampleRate = afSampleRate;
149 }
150 // these below should probably come from the audioFlinger too...
151 if (format == 0) {
152 format = AudioSystem::PCM_16_BIT;
153 }
Eric Laurenta553c252009-07-17 12:17:14 -0700154 if (channels == 0) {
155 channels = AudioSystem::CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 }
157
158 // validate parameters
Eric Laurenta553c252009-07-17 12:17:14 -0700159 if (!AudioSystem::isValidFormat(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 LOGE("Invalid format");
161 return BAD_VALUE;
162 }
Eric Laurenta553c252009-07-17 12:17:14 -0700163
164 // force direct flag if format is not linear PCM
165 if (!AudioSystem::isLinearPCM(format)) {
166 flags |= AudioSystem::OUTPUT_FLAG_DIRECT;
167 }
168
169 if (!AudioSystem::isOutputChannel(channels)) {
170 LOGE("Invalid channel mask");
171 return BAD_VALUE;
172 }
173 uint32_t channelCount = AudioSystem::popCount(channels);
174
175 audio_io_handle_t output = AudioSystem::getOutput((AudioSystem::stream_type)streamType,
176 sampleRate, format, channels, (AudioSystem::output_flags)flags);
177
178 if (output == 0) {
179 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 return BAD_VALUE;
181 }
182
Eric Laurenta553c252009-07-17 12:17:14 -0700183 if (!AudioSystem::isLinearPCM(format)) {
184 if (sharedBuffer != 0) {
185 frameCount = sharedBuffer->size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 }
187 } else {
Eric Laurenta553c252009-07-17 12:17:14 -0700188 // Ensure that buffer depth covers at least audio hardware latency
189 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
190 if (minBufCount < 2) minBufCount = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Eric Laurenta553c252009-07-17 12:17:14 -0700192 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
193
194 if (sharedBuffer == 0) {
195 if (frameCount == 0) {
196 frameCount = minFrameCount;
197 }
198 if (notificationFrames == 0) {
199 notificationFrames = frameCount/2;
200 }
201 // Make sure that application is notified with sufficient margin
202 // before underrun
203 if (notificationFrames > frameCount/2) {
204 notificationFrames = frameCount/2;
205 }
206 if (frameCount < minFrameCount) {
207 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
208 return BAD_VALUE;
209 }
210 } else {
211 // Ensure that buffer alignment matches channelcount
212 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
213 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
214 return BAD_VALUE;
215 }
216 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 }
219
220 // create the track
221 status_t status;
222 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
Eric Laurenta553c252009-07-17 12:17:14 -0700223 streamType,
224 sampleRate,
225 format,
226 channelCount,
227 frameCount,
228 ((uint16_t)flags) << 16,
229 sharedBuffer,
230 output,
231 &status);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
233 if (track == 0) {
234 LOGE("AudioFlinger could not create track, status: %d", status);
235 return status;
236 }
237 sp<IMemory> cblk = track->getCblk();
238 if (cblk == 0) {
239 LOGE("Could not get control block");
240 return NO_INIT;
241 }
242 if (cbf != 0) {
243 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
244 if (mAudioTrackThread == 0) {
245 LOGE("Could not create callback thread");
246 return NO_INIT;
247 }
248 }
249
250 mStatus = NO_ERROR;
251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 mAudioTrack = track;
253 mCblkMemory = cblk;
254 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
255 mCblk->out = 1;
256 // Update buffer size in case it has been limited by AudioFlinger during track creation
257 mFrameCount = mCblk->frameCount;
258 if (sharedBuffer == 0) {
259 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
260 } else {
261 mCblk->buffers = sharedBuffer->pointer();
262 // Force buffer full condition as data is already present in shared memory
263 mCblk->stepUser(mFrameCount);
264 }
265 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
266 mVolume[LEFT] = 1.0f;
267 mVolume[RIGHT] = 1.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 mStreamType = streamType;
269 mFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -0700270 mChannels = channels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 mChannelCount = channelCount;
272 mSharedBuffer = sharedBuffer;
273 mMuted = false;
274 mActive = 0;
275 mCbf = cbf;
276 mNotificationFrames = notificationFrames;
277 mRemainingFrames = notificationFrames;
278 mUserData = user;
Eric Laurent88e209d2009-07-07 07:10:45 -0700279 mLatency = afLatency + (1000*mFrameCount) / sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 mLoopCount = 0;
281 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700282 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 mNewPosition = 0;
284 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700285 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286
287 return NO_ERROR;
288}
289
290status_t AudioTrack::initCheck() const
291{
292 return mStatus;
293}
294
295// -------------------------------------------------------------------------
296
297uint32_t AudioTrack::latency() const
298{
299 return mLatency;
300}
301
302int AudioTrack::streamType() const
303{
304 return mStreamType;
305}
306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307int AudioTrack::format() const
308{
309 return mFormat;
310}
311
312int AudioTrack::channelCount() const
313{
314 return mChannelCount;
315}
316
317uint32_t AudioTrack::frameCount() const
318{
319 return mFrameCount;
320}
321
322int AudioTrack::frameSize() const
323{
Eric Laurenta553c252009-07-17 12:17:14 -0700324 if (AudioSystem::isLinearPCM(mFormat)) {
325 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
326 } else {
327 return sizeof(uint8_t);
328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329}
330
331sp<IMemory>& AudioTrack::sharedBuffer()
332{
333 return mSharedBuffer;
334}
335
336// -------------------------------------------------------------------------
337
338void AudioTrack::start()
339{
340 sp<AudioTrackThread> t = mAudioTrackThread;
341
342 LOGV("start %p", this);
343 if (t != 0) {
344 if (t->exitPending()) {
345 if (t->requestExitAndWait() == WOULD_BLOCK) {
346 LOGE("AudioTrack::start called from thread");
347 return;
348 }
349 }
350 t->mLock.lock();
351 }
352
353 if (android_atomic_or(1, &mActive) == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -0700354 AudioSystem::startOutput(getOutput(), (AudioSystem::stream_type)mStreamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 mNewPosition = mCblk->server + mUpdatePeriod;
356 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
357 mCblk->waitTimeMs = 0;
358 if (t != 0) {
359 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
360 } else {
361 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
362 }
363 mAudioTrack->start();
364 }
365
366 if (t != 0) {
367 t->mLock.unlock();
368 }
369}
370
371void AudioTrack::stop()
372{
373 sp<AudioTrackThread> t = mAudioTrackThread;
374
375 LOGV("stop %p", this);
376 if (t != 0) {
377 t->mLock.lock();
378 }
379
380 if (android_atomic_and(~1, &mActive) == 1) {
Eric Laurentef028272009-04-21 07:56:33 -0700381 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 mAudioTrack->stop();
383 // Cancel loops (If we are in the middle of a loop, playback
384 // would not stop until loopCount reaches 0).
385 setLoop(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700386 // the playback head position will reset to 0, so if a marker is set, we need
387 // to activate it again
388 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 // Force flush if a shared buffer is used otherwise audioflinger
390 // will not stop before end of buffer is reached.
391 if (mSharedBuffer != 0) {
392 flush();
393 }
394 if (t != 0) {
395 t->requestExit();
396 } else {
397 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
398 }
Eric Laurenta553c252009-07-17 12:17:14 -0700399 AudioSystem::stopOutput(getOutput(), (AudioSystem::stream_type)mStreamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 }
401
402 if (t != 0) {
403 t->mLock.unlock();
404 }
405}
406
407bool AudioTrack::stopped() const
408{
409 return !mActive;
410}
411
412void AudioTrack::flush()
413{
414 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700415
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700416 // clear playback marker and periodic update counter
417 mMarkerPosition = 0;
418 mMarkerReached = false;
419 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421
422 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 mAudioTrack->flush();
424 // Release AudioTrack callback thread in case it was waiting for new buffers
425 // in AudioTrack::obtainBuffer()
426 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 }
428}
429
430void AudioTrack::pause()
431{
432 LOGV("pause");
433 if (android_atomic_and(~1, &mActive) == 1) {
434 mActive = 0;
435 mAudioTrack->pause();
Eric Laurenta553c252009-07-17 12:17:14 -0700436 AudioSystem::stopOutput(getOutput(), (AudioSystem::stream_type)mStreamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 }
438}
439
440void AudioTrack::mute(bool e)
441{
442 mAudioTrack->mute(e);
443 mMuted = e;
444}
445
446bool AudioTrack::muted() const
447{
448 return mMuted;
449}
450
451void AudioTrack::setVolume(float left, float right)
452{
453 mVolume[LEFT] = left;
454 mVolume[RIGHT] = right;
455
456 // write must be atomic
457 mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000);
458}
459
460void AudioTrack::getVolume(float* left, float* right)
461{
462 *left = mVolume[LEFT];
463 *right = mVolume[RIGHT];
464}
465
Eric Laurent88e209d2009-07-07 07:10:45 -0700466status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467{
468 int afSamplingRate;
469
470 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700471 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 }
473 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700474 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475
Eric Laurent88e209d2009-07-07 07:10:45 -0700476 mCblk->sampleRate = rate;
477 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478}
479
480uint32_t AudioTrack::getSampleRate()
481{
Eric Laurent88e209d2009-07-07 07:10:45 -0700482 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483}
484
485status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
486{
487 audio_track_cblk_t* cblk = mCblk;
488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 Mutex::Autolock _l(cblk->lock);
490
491 if (loopCount == 0) {
492 cblk->loopStart = UINT_MAX;
493 cblk->loopEnd = UINT_MAX;
494 cblk->loopCount = 0;
495 mLoopCount = 0;
496 return NO_ERROR;
497 }
498
499 if (loopStart >= loopEnd ||
500 loopEnd - loopStart > mFrameCount) {
501 LOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user);
502 return BAD_VALUE;
503 }
504
505 if ((mSharedBuffer != 0) && (loopEnd > mFrameCount)) {
506 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
507 loopStart, loopEnd, mFrameCount);
508 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510
511 cblk->loopStart = loopStart;
512 cblk->loopEnd = loopEnd;
513 cblk->loopCount = loopCount;
514 mLoopCount = loopCount;
515
516 return NO_ERROR;
517}
518
519status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
520{
521 if (loopStart != 0) {
522 *loopStart = mCblk->loopStart;
523 }
524 if (loopEnd != 0) {
525 *loopEnd = mCblk->loopEnd;
526 }
527 if (loopCount != 0) {
528 if (mCblk->loopCount < 0) {
529 *loopCount = -1;
530 } else {
531 *loopCount = mCblk->loopCount;
532 }
533 }
534
535 return NO_ERROR;
536}
537
538status_t AudioTrack::setMarkerPosition(uint32_t marker)
539{
540 if (mCbf == 0) return INVALID_OPERATION;
541
542 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700543 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544
545 return NO_ERROR;
546}
547
548status_t AudioTrack::getMarkerPosition(uint32_t *marker)
549{
550 if (marker == 0) return BAD_VALUE;
551
552 *marker = mMarkerPosition;
553
554 return NO_ERROR;
555}
556
557status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
558{
559 if (mCbf == 0) return INVALID_OPERATION;
560
561 uint32_t curPosition;
562 getPosition(&curPosition);
563 mNewPosition = curPosition + updatePeriod;
564 mUpdatePeriod = updatePeriod;
565
566 return NO_ERROR;
567}
568
569status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
570{
571 if (updatePeriod == 0) return BAD_VALUE;
572
573 *updatePeriod = mUpdatePeriod;
574
575 return NO_ERROR;
576}
577
578status_t AudioTrack::setPosition(uint32_t position)
579{
580 Mutex::Autolock _l(mCblk->lock);
581
582 if (!stopped()) return INVALID_OPERATION;
583
584 if (position > mCblk->user) return BAD_VALUE;
585
586 mCblk->server = position;
587 mCblk->forceReady = 1;
Eric Laurenta553c252009-07-17 12:17:14 -0700588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 return NO_ERROR;
590}
591
592status_t AudioTrack::getPosition(uint32_t *position)
593{
594 if (position == 0) return BAD_VALUE;
595
596 *position = mCblk->server;
597
598 return NO_ERROR;
599}
600
601status_t AudioTrack::reload()
602{
603 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 flush();
606
607 mCblk->stepUser(mFrameCount);
608
609 return NO_ERROR;
610}
611
Eric Laurenta553c252009-07-17 12:17:14 -0700612audio_io_handle_t AudioTrack::getOutput()
613{
614 return AudioSystem::getOutput((AudioSystem::stream_type)mStreamType,
615 mCblk->sampleRate, mFormat, mChannels, (AudioSystem::output_flags)mFlags);
616}
617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618// -------------------------------------------------------------------------
619
620status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
621{
622 int active;
623 int timeout = 0;
624 status_t result;
625 audio_track_cblk_t* cblk = mCblk;
626 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700627 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628
629 audioBuffer->frameCount = 0;
630 audioBuffer->size = 0;
631
632 uint32_t framesAvail = cblk->framesAvailable();
633
634 if (framesAvail == 0) {
635 Mutex::Autolock _l(cblk->lock);
636 goto start_loop_here;
637 while (framesAvail == 0) {
638 active = mActive;
639 if (UNLIKELY(!active)) {
640 LOGV("Not active and NO_MORE_BUFFERS");
641 return NO_MORE_BUFFERS;
642 }
643 if (UNLIKELY(!waitCount))
644 return WOULD_BLOCK;
645 timeout = 0;
Eric Laurentef028272009-04-21 07:56:33 -0700646 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenta553c252009-07-17 12:17:14 -0700647 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700648 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
650 // timing out when a loop has been set and we have already written upto loop end
651 // is a normal condition: no need to wake AudioFlinger up.
652 if (cblk->user < cblk->loopEnd) {
653 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
654 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700655 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 cblk->lock.unlock();
657 mAudioTrack->start();
658 cblk->lock.lock();
659 timeout = 1;
660 }
661 cblk->waitTimeMs = 0;
662 }
Eric Laurenta553c252009-07-17 12:17:14 -0700663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 if (--waitCount == 0) {
665 return TIMED_OUT;
666 }
667 }
668 // read the server count again
669 start_loop_here:
670 framesAvail = cblk->framesAvailable_l();
671 }
672 }
673
674 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 if (framesReq > framesAvail) {
677 framesReq = framesAvail;
678 }
679
680 uint32_t u = cblk->user;
681 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
682
683 if (u + framesReq > bufferEnd) {
684 framesReq = bufferEnd - u;
685 }
686
687 LOGW_IF(timeout,
688 "*** SERIOUS WARNING *** obtainBuffer() timed out "
689 "but didn't need to be locked. We recovered, but "
690 "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server);
691
Eric Laurenta553c252009-07-17 12:17:14 -0700692 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
693 audioBuffer->channelCount = mChannelCount;
694 audioBuffer->frameCount = framesReq;
695 audioBuffer->size = framesReq * cblk->frameSize;
696 if (AudioSystem::isLinearPCM(mFormat)) {
697 audioBuffer->format = AudioSystem::PCM_16_BIT;
698 } else {
699 audioBuffer->format = mFormat;
700 }
701 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 active = mActive;
703 return active ? status_t(NO_ERROR) : status_t(STOPPED);
704}
705
706void AudioTrack::releaseBuffer(Buffer* audioBuffer)
707{
708 audio_track_cblk_t* cblk = mCblk;
709 cblk->stepUser(audioBuffer->frameCount);
710}
711
712// -------------------------------------------------------------------------
713
714ssize_t AudioTrack::write(const void* buffer, size_t userSize)
715{
716
717 if (mSharedBuffer != 0) return INVALID_OPERATION;
718
719 if (ssize_t(userSize) < 0) {
720 // sanity-check. user is most-likely passing an error code.
721 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
722 buffer, userSize, userSize);
723 return BAD_VALUE;
724 }
725
726 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
727
728 ssize_t written = 0;
729 const int8_t *src = (const int8_t *)buffer;
730 Buffer audioBuffer;
731
732 do {
Eric Laurenta553c252009-07-17 12:17:14 -0700733 audioBuffer.frameCount = userSize/frameSize();
734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 // Calling obtainBuffer() with a negative wait count causes
736 // an (almost) infinite wait time.
737 status_t err = obtainBuffer(&audioBuffer, -1);
738 if (err < 0) {
739 // out of buffers, return #bytes written
740 if (err == status_t(NO_MORE_BUFFERS))
741 break;
742 return ssize_t(err);
743 }
744
745 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 if (mFormat == AudioSystem::PCM_8_BIT) {
748 // Divide capacity by 2 to take expansion into account
749 toWrite = audioBuffer.size>>1;
750 // 8 to 16 bit conversion
751 int count = toWrite;
752 int16_t *dst = (int16_t *)(audioBuffer.i8);
753 while(count--) {
754 *dst++ = (int16_t)(*src++^0x80) << 8;
755 }
756 }else {
757 toWrite = audioBuffer.size;
758 memcpy(audioBuffer.i8, src, toWrite);
759 src += toWrite;
760 }
761 userSize -= toWrite;
762 written += toWrite;
763
764 releaseBuffer(&audioBuffer);
765 } while (userSize);
766
767 return written;
768}
769
770// -------------------------------------------------------------------------
771
772bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
773{
774 Buffer audioBuffer;
775 uint32_t frames;
776 size_t writtenSize;
777
778 // Manage underrun callback
779 if (mActive && (mCblk->framesReady() == 0)) {
780 LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
781 if (mCblk->flowControlFlag == 0) {
782 mCbf(EVENT_UNDERRUN, mUserData, 0);
783 if (mCblk->server == mCblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -0700784 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 }
786 mCblk->flowControlFlag = 1;
787 if (mSharedBuffer != 0) return false;
788 }
789 }
Eric Laurenta553c252009-07-17 12:17:14 -0700790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 // Manage loop end callback
792 while (mLoopCount > mCblk->loopCount) {
793 int loopCount = -1;
794 mLoopCount--;
795 if (mLoopCount >= 0) loopCount = mLoopCount;
796
797 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
798 }
799
800 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700801 if (!mMarkerReached && (mMarkerPosition > 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 if (mCblk->server >= mMarkerPosition) {
803 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700804 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 }
806 }
807
808 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -0700809 if (mUpdatePeriod > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 while (mCblk->server >= mNewPosition) {
811 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
812 mNewPosition += mUpdatePeriod;
813 }
814 }
815
816 // If Shared buffer is used, no data is requested from client.
817 if (mSharedBuffer != 0) {
818 frames = 0;
819 } else {
820 frames = mRemainingFrames;
821 }
822
823 do {
824
825 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -0700826
827 // Calling obtainBuffer() with a wait count of 1
828 // limits wait time to WAIT_PERIOD_MS. This prevents from being
829 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 status_t err = obtainBuffer(&audioBuffer, 1);
831 if (err < NO_ERROR) {
832 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -0700833 LOGE_IF(err != status_t(NO_MORE_BUFFERS), "Error obtaining an audio buffer, giving up.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 return false;
835 }
836 break;
837 }
838 if (err == status_t(STOPPED)) return false;
839
840 // Divide buffer size by 2 to take into account the expansion
841 // due to 8 to 16 bit conversion: the callback must fill only half
842 // of the destination buffer
843 if (mFormat == AudioSystem::PCM_8_BIT) {
844 audioBuffer.size >>= 1;
845 }
846
847 size_t reqSize = audioBuffer.size;
848 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
849 writtenSize = audioBuffer.size;
850
851 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -0800852 if (ssize_t(writtenSize) <= 0) {
853 // The callback is done filling buffers
854 // Keep this thread going to handle timed events and
855 // still try to get more data in intervals of WAIT_PERIOD_MS
856 // but don't just loop and block the CPU, so wait
857 usleep(WAIT_PERIOD_MS*1000);
858 break;
859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 if (writtenSize > reqSize) writtenSize = reqSize;
861
862 if (mFormat == AudioSystem::PCM_8_BIT) {
863 // 8 to 16 bit conversion
864 const int8_t *src = audioBuffer.i8 + writtenSize-1;
865 int count = writtenSize;
866 int16_t *dst = audioBuffer.i16 + writtenSize-1;
867 while(count--) {
868 *dst-- = (int16_t)(*src--^0x80) << 8;
869 }
870 writtenSize <<= 1;
871 }
872
873 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -0700874 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
875 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
876 // 16 bit.
877 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 frames -= audioBuffer.frameCount;
880
881 releaseBuffer(&audioBuffer);
882 }
883 while (frames);
884
885 if (frames == 0) {
886 mRemainingFrames = mNotificationFrames;
887 } else {
888 mRemainingFrames = frames;
889 }
890 return true;
891}
892
893status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
894{
895
896 const size_t SIZE = 256;
897 char buffer[SIZE];
898 String8 result;
899
900 result.append(" AudioTrack::dump\n");
901 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
902 result.append(buffer);
903 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mFrameCount);
904 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -0700905 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 result.append(buffer);
907 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
908 result.append(buffer);
909 ::write(fd, result.string(), result.size());
910 return NO_ERROR;
911}
912
913// =========================================================================
914
915AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
916 : Thread(bCanCallJava), mReceiver(receiver)
917{
918}
919
920bool AudioTrack::AudioTrackThread::threadLoop()
921{
922 return mReceiver.processAudioBuffer(this);
923}
924
925status_t AudioTrack::AudioTrackThread::readyToRun()
926{
927 return NO_ERROR;
928}
929
930void AudioTrack::AudioTrackThread::onFirstRef()
931{
932}
933
934// =========================================================================
935
936audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopianfb4f2662009-07-13 21:59:37 -0700937 : lock(Mutex::SHARED), user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0)
939{
940}
941
942uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
943{
944 uint32_t u = this->user;
945
946 u += frameCount;
947 // Ensure that user is never ahead of server for AudioRecord
948 if (out) {
949 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
950 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
951 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
952 }
953 } else if (u > this->server) {
954 LOGW("stepServer occured after track reset");
955 u = this->server;
956 }
957
958 if (u >= userBase + this->frameCount) {
959 userBase += this->frameCount;
960 }
961
962 this->user = u;
963
964 // Clear flow control error condition as new data has been written/read to/from buffer.
965 flowControlFlag = 0;
966
967 return u;
968}
969
970bool audio_track_cblk_t::stepServer(uint32_t frameCount)
971{
972 // the code below simulates lock-with-timeout
973 // we MUST do this to protect the AudioFlinger server
974 // as this lock is shared with the client.
975 status_t err;
976
977 err = lock.tryLock();
978 if (err == -EBUSY) { // just wait a bit
979 usleep(1000);
980 err = lock.tryLock();
981 }
982 if (err != NO_ERROR) {
983 // probably, the client just died.
984 return false;
985 }
986
987 uint32_t s = this->server;
988
989 s += frameCount;
990 if (out) {
991 // Mark that we have read the first buffer so that next time stepUser() is called
992 // we switch to normal obtainBuffer() timeout period
993 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
994 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -0700995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 // It is possible that we receive a flush()
997 // while the mixer is processing a block: in this case,
998 // stepServer() is called After the flush() has reset u & s and
999 // we have s > u
1000 if (s > this->user) {
1001 LOGW("stepServer occured after track reset");
1002 s = this->user;
1003 }
1004 }
1005
1006 if (s >= loopEnd) {
1007 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1008 s = loopStart;
1009 if (--loopCount == 0) {
1010 loopEnd = UINT_MAX;
1011 loopStart = UINT_MAX;
1012 }
1013 }
1014 if (s >= serverBase + this->frameCount) {
1015 serverBase += this->frameCount;
1016 }
1017
1018 this->server = s;
1019
1020 cv.signal();
1021 lock.unlock();
1022 return true;
1023}
1024
1025void* audio_track_cblk_t::buffer(uint32_t offset) const
1026{
Eric Laurenta553c252009-07-17 12:17:14 -07001027 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028}
1029
1030uint32_t audio_track_cblk_t::framesAvailable()
1031{
1032 Mutex::Autolock _l(lock);
1033 return framesAvailable_l();
1034}
1035
1036uint32_t audio_track_cblk_t::framesAvailable_l()
1037{
1038 uint32_t u = this->user;
1039 uint32_t s = this->server;
1040
1041 if (out) {
1042 uint32_t limit = (s < loopStart) ? s : loopStart;
1043 return limit + frameCount - u;
1044 } else {
1045 return frameCount + u - s;
1046 }
1047}
1048
1049uint32_t audio_track_cblk_t::framesReady()
1050{
1051 uint32_t u = this->user;
1052 uint32_t s = this->server;
1053
1054 if (out) {
1055 if (u < loopEnd) {
1056 return u - s;
1057 } else {
1058 Mutex::Autolock _l(lock);
1059 if (loopCount >= 0) {
1060 return (loopEnd - loopStart)*loopCount + u - s;
1061 } else {
1062 return UINT_MAX;
1063 }
1064 }
1065 } else {
1066 return s - u;
1067 }
1068}
1069
1070// -------------------------------------------------------------------------
1071
1072}; // namespace android
1073