blob: e79f336f8549e676e66c4e93980f34c81827d97f [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>
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
48AudioTrack::AudioTrack()
49 : mStatus(NO_INIT)
50{
51}
52
53AudioTrack::AudioTrack(
54 int streamType,
55 uint32_t sampleRate,
56 int format,
57 int channelCount,
58 int frameCount,
59 uint32_t flags,
60 callback_t cbf,
61 void* user,
62 int notificationFrames)
63 : mStatus(NO_INIT)
64{
65 mStatus = set(streamType, sampleRate, format, channelCount,
66 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);
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) {
95 mCblk->cv.signal();
96 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,
109 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
120 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 }
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 }
154 if (channelCount == 0) {
155 channelCount = 2;
156 }
157
158 // validate parameters
159 if (((format != AudioSystem::PCM_8_BIT) || sharedBuffer != 0) &&
160 (format != AudioSystem::PCM_16_BIT)) {
161 LOGE("Invalid format");
162 return BAD_VALUE;
163 }
164 if (channelCount != 1 && channelCount != 2) {
165 LOGE("Invalid channel number");
166 return BAD_VALUE;
167 }
168
169 // Ensure that buffer depth covers at least audio hardware latency
170 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
171 if (minBufCount < 2) minBufCount = 2;
172
173 // When playing from shared buffer, playback will start even if last audioflinger
174 // block is partly filled.
175 if (sharedBuffer != 0 && minBufCount > 1) {
176 minBufCount--;
177 }
178
179 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
180
181 if (sharedBuffer == 0) {
182 if (frameCount == 0) {
183 frameCount = minFrameCount;
184 }
185 if (notificationFrames == 0) {
186 notificationFrames = frameCount/2;
187 }
188 // Make sure that application is notified with sufficient margin
189 // before underrun
190 if (notificationFrames > frameCount/2) {
191 notificationFrames = frameCount/2;
192 }
193 } else {
194 // Ensure that buffer alignment matches channelcount
195 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
196 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
197 return BAD_VALUE;
198 }
199 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
200 }
201
202 if (frameCount < minFrameCount) {
203 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
204 return BAD_VALUE;
205 }
206
207 // create the track
208 status_t status;
209 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
210 streamType, sampleRate, format, channelCount, frameCount, flags, sharedBuffer, &status);
211
212 if (track == 0) {
213 LOGE("AudioFlinger could not create track, status: %d", status);
214 return status;
215 }
216 sp<IMemory> cblk = track->getCblk();
217 if (cblk == 0) {
218 LOGE("Could not get control block");
219 return NO_INIT;
220 }
221 if (cbf != 0) {
222 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
223 if (mAudioTrackThread == 0) {
224 LOGE("Could not create callback thread");
225 return NO_INIT;
226 }
227 }
228
229 mStatus = NO_ERROR;
230
231 mAudioFlinger = audioFlinger;
232 mAudioTrack = track;
233 mCblkMemory = cblk;
234 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
235 mCblk->out = 1;
236 // Update buffer size in case it has been limited by AudioFlinger during track creation
237 mFrameCount = mCblk->frameCount;
238 if (sharedBuffer == 0) {
239 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
240 } else {
241 mCblk->buffers = sharedBuffer->pointer();
242 // Force buffer full condition as data is already present in shared memory
243 mCblk->stepUser(mFrameCount);
244 }
245 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
246 mVolume[LEFT] = 1.0f;
247 mVolume[RIGHT] = 1.0f;
248 mSampleRate = sampleRate;
249 mStreamType = streamType;
250 mFormat = format;
251 mChannelCount = channelCount;
252 mSharedBuffer = sharedBuffer;
253 mMuted = false;
254 mActive = 0;
255 mCbf = cbf;
256 mNotificationFrames = notificationFrames;
257 mRemainingFrames = notificationFrames;
258 mUserData = user;
259 mLatency = afLatency + (1000*mFrameCount) / mSampleRate;
260 mLoopCount = 0;
261 mMarkerPosition = 0;
262 mNewPosition = 0;
263 mUpdatePeriod = 0;
264
265 return NO_ERROR;
266}
267
268status_t AudioTrack::initCheck() const
269{
270 return mStatus;
271}
272
273// -------------------------------------------------------------------------
274
275uint32_t AudioTrack::latency() const
276{
277 return mLatency;
278}
279
280int AudioTrack::streamType() const
281{
282 return mStreamType;
283}
284
285uint32_t AudioTrack::sampleRate() const
286{
287 return mSampleRate;
288}
289
290int AudioTrack::format() const
291{
292 return mFormat;
293}
294
295int AudioTrack::channelCount() const
296{
297 return mChannelCount;
298}
299
300uint32_t AudioTrack::frameCount() const
301{
302 return mFrameCount;
303}
304
305int AudioTrack::frameSize() const
306{
307 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
308}
309
310sp<IMemory>& AudioTrack::sharedBuffer()
311{
312 return mSharedBuffer;
313}
314
315// -------------------------------------------------------------------------
316
317void AudioTrack::start()
318{
319 sp<AudioTrackThread> t = mAudioTrackThread;
320
321 LOGV("start %p", this);
322 if (t != 0) {
323 if (t->exitPending()) {
324 if (t->requestExitAndWait() == WOULD_BLOCK) {
325 LOGE("AudioTrack::start called from thread");
326 return;
327 }
328 }
329 t->mLock.lock();
330 }
331
332 if (android_atomic_or(1, &mActive) == 0) {
333 mNewPosition = mCblk->server + mUpdatePeriod;
334 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
335 mCblk->waitTimeMs = 0;
336 if (t != 0) {
337 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
338 } else {
339 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
340 }
341 mAudioTrack->start();
342 }
343
344 if (t != 0) {
345 t->mLock.unlock();
346 }
347}
348
349void AudioTrack::stop()
350{
351 sp<AudioTrackThread> t = mAudioTrackThread;
352
353 LOGV("stop %p", this);
354 if (t != 0) {
355 t->mLock.lock();
356 }
357
358 if (android_atomic_and(~1, &mActive) == 1) {
359 mAudioTrack->stop();
360 // Cancel loops (If we are in the middle of a loop, playback
361 // would not stop until loopCount reaches 0).
362 setLoop(0, 0, 0);
363 // Force flush if a shared buffer is used otherwise audioflinger
364 // will not stop before end of buffer is reached.
365 if (mSharedBuffer != 0) {
366 flush();
367 }
368 if (t != 0) {
369 t->requestExit();
370 } else {
371 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
372 }
373 }
374
375 if (t != 0) {
376 t->mLock.unlock();
377 }
378}
379
380bool AudioTrack::stopped() const
381{
382 return !mActive;
383}
384
385void AudioTrack::flush()
386{
387 LOGV("flush");
388
389 if (!mActive) {
390 mCblk->lock.lock();
391 mAudioTrack->flush();
392 // Release AudioTrack callback thread in case it was waiting for new buffers
393 // in AudioTrack::obtainBuffer()
394 mCblk->cv.signal();
395 mCblk->lock.unlock();
396 }
397}
398
399void AudioTrack::pause()
400{
401 LOGV("pause");
402 if (android_atomic_and(~1, &mActive) == 1) {
403 mActive = 0;
404 mAudioTrack->pause();
405 }
406}
407
408void AudioTrack::mute(bool e)
409{
410 mAudioTrack->mute(e);
411 mMuted = e;
412}
413
414bool AudioTrack::muted() const
415{
416 return mMuted;
417}
418
419void AudioTrack::setVolume(float left, float right)
420{
421 mVolume[LEFT] = left;
422 mVolume[RIGHT] = right;
423
424 // write must be atomic
425 mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000);
426}
427
428void AudioTrack::getVolume(float* left, float* right)
429{
430 *left = mVolume[LEFT];
431 *right = mVolume[RIGHT];
432}
433
434void AudioTrack::setSampleRate(int rate)
435{
436 int afSamplingRate;
437
438 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
439 return;
440 }
441 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
442 if (rate <= 0) rate = 1;
443 if (rate > afSamplingRate*2) rate = afSamplingRate*2;
444 if (rate > MAX_SAMPLE_RATE) rate = MAX_SAMPLE_RATE;
445
446 mCblk->sampleRate = rate;
447}
448
449uint32_t AudioTrack::getSampleRate()
450{
451 return uint32_t(mCblk->sampleRate);
452}
453
454status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
455{
456 audio_track_cblk_t* cblk = mCblk;
457
458
459 Mutex::Autolock _l(cblk->lock);
460
461 if (loopCount == 0) {
462 cblk->loopStart = UINT_MAX;
463 cblk->loopEnd = UINT_MAX;
464 cblk->loopCount = 0;
465 mLoopCount = 0;
466 return NO_ERROR;
467 }
468
469 if (loopStart >= loopEnd ||
470 loopEnd - loopStart > mFrameCount) {
471 LOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user);
472 return BAD_VALUE;
473 }
474
475 if ((mSharedBuffer != 0) && (loopEnd > mFrameCount)) {
476 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
477 loopStart, loopEnd, mFrameCount);
478 return BAD_VALUE;
479 }
480
481 cblk->loopStart = loopStart;
482 cblk->loopEnd = loopEnd;
483 cblk->loopCount = loopCount;
484 mLoopCount = loopCount;
485
486 return NO_ERROR;
487}
488
489status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
490{
491 if (loopStart != 0) {
492 *loopStart = mCblk->loopStart;
493 }
494 if (loopEnd != 0) {
495 *loopEnd = mCblk->loopEnd;
496 }
497 if (loopCount != 0) {
498 if (mCblk->loopCount < 0) {
499 *loopCount = -1;
500 } else {
501 *loopCount = mCblk->loopCount;
502 }
503 }
504
505 return NO_ERROR;
506}
507
508status_t AudioTrack::setMarkerPosition(uint32_t marker)
509{
510 if (mCbf == 0) return INVALID_OPERATION;
511
512 mMarkerPosition = marker;
513
514 return NO_ERROR;
515}
516
517status_t AudioTrack::getMarkerPosition(uint32_t *marker)
518{
519 if (marker == 0) return BAD_VALUE;
520
521 *marker = mMarkerPosition;
522
523 return NO_ERROR;
524}
525
526status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
527{
528 if (mCbf == 0) return INVALID_OPERATION;
529
530 uint32_t curPosition;
531 getPosition(&curPosition);
532 mNewPosition = curPosition + updatePeriod;
533 mUpdatePeriod = updatePeriod;
534
535 return NO_ERROR;
536}
537
538status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
539{
540 if (updatePeriod == 0) return BAD_VALUE;
541
542 *updatePeriod = mUpdatePeriod;
543
544 return NO_ERROR;
545}
546
547status_t AudioTrack::setPosition(uint32_t position)
548{
549 Mutex::Autolock _l(mCblk->lock);
550
551 if (!stopped()) return INVALID_OPERATION;
552
553 if (position > mCblk->user) return BAD_VALUE;
554
555 mCblk->server = position;
556 mCblk->forceReady = 1;
557
558 return NO_ERROR;
559}
560
561status_t AudioTrack::getPosition(uint32_t *position)
562{
563 if (position == 0) return BAD_VALUE;
564
565 *position = mCblk->server;
566
567 return NO_ERROR;
568}
569
570status_t AudioTrack::reload()
571{
572 if (!stopped()) return INVALID_OPERATION;
573
574 flush();
575
576 mCblk->stepUser(mFrameCount);
577
578 return NO_ERROR;
579}
580
581// -------------------------------------------------------------------------
582
583status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
584{
585 int active;
586 int timeout = 0;
587 status_t result;
588 audio_track_cblk_t* cblk = mCblk;
589 uint32_t framesReq = audioBuffer->frameCount;
590
591 audioBuffer->frameCount = 0;
592 audioBuffer->size = 0;
593
594 uint32_t framesAvail = cblk->framesAvailable();
595
596 if (framesAvail == 0) {
597 Mutex::Autolock _l(cblk->lock);
598 goto start_loop_here;
599 while (framesAvail == 0) {
600 active = mActive;
601 if (UNLIKELY(!active)) {
602 LOGV("Not active and NO_MORE_BUFFERS");
603 return NO_MORE_BUFFERS;
604 }
605 if (UNLIKELY(!waitCount))
606 return WOULD_BLOCK;
607 timeout = 0;
608 result = cblk->cv.waitRelative(cblk->lock, milliseconds(WAIT_PERIOD_MS));
609 if (__builtin_expect(result!=NO_ERROR, false)) {
610 cblk->waitTimeMs += WAIT_PERIOD_MS;
611 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
612 // timing out when a loop has been set and we have already written upto loop end
613 // is a normal condition: no need to wake AudioFlinger up.
614 if (cblk->user < cblk->loopEnd) {
615 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
616 "user=%08x, server=%08x", this, cblk->user, cblk->server);
617 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
618 cblk->lock.unlock();
619 mAudioTrack->start();
620 cblk->lock.lock();
621 timeout = 1;
622 }
623 cblk->waitTimeMs = 0;
624 }
625
626 if (--waitCount == 0) {
627 return TIMED_OUT;
628 }
629 }
630 // read the server count again
631 start_loop_here:
632 framesAvail = cblk->framesAvailable_l();
633 }
634 }
635
636 cblk->waitTimeMs = 0;
637
638 if (framesReq > framesAvail) {
639 framesReq = framesAvail;
640 }
641
642 uint32_t u = cblk->user;
643 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
644
645 if (u + framesReq > bufferEnd) {
646 framesReq = bufferEnd - u;
647 }
648
649 LOGW_IF(timeout,
650 "*** SERIOUS WARNING *** obtainBuffer() timed out "
651 "but didn't need to be locked. We recovered, but "
652 "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server);
653
654 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
655 audioBuffer->channelCount= mChannelCount;
656 audioBuffer->format = AudioSystem::PCM_16_BIT;
657 audioBuffer->frameCount = framesReq;
658 audioBuffer->size = framesReq*mChannelCount*sizeof(int16_t);
659 audioBuffer->raw = (int8_t *)cblk->buffer(u);
660 active = mActive;
661 return active ? status_t(NO_ERROR) : status_t(STOPPED);
662}
663
664void AudioTrack::releaseBuffer(Buffer* audioBuffer)
665{
666 audio_track_cblk_t* cblk = mCblk;
667 cblk->stepUser(audioBuffer->frameCount);
668}
669
670// -------------------------------------------------------------------------
671
672ssize_t AudioTrack::write(const void* buffer, size_t userSize)
673{
674
675 if (mSharedBuffer != 0) return INVALID_OPERATION;
676
677 if (ssize_t(userSize) < 0) {
678 // sanity-check. user is most-likely passing an error code.
679 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
680 buffer, userSize, userSize);
681 return BAD_VALUE;
682 }
683
684 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
685
686 ssize_t written = 0;
687 const int8_t *src = (const int8_t *)buffer;
688 Buffer audioBuffer;
689
690 do {
691 audioBuffer.frameCount = userSize/mChannelCount;
692 if (mFormat == AudioSystem::PCM_16_BIT) {
693 audioBuffer.frameCount >>= 1;
694 }
695 // Calling obtainBuffer() with a negative wait count causes
696 // an (almost) infinite wait time.
697 status_t err = obtainBuffer(&audioBuffer, -1);
698 if (err < 0) {
699 // out of buffers, return #bytes written
700 if (err == status_t(NO_MORE_BUFFERS))
701 break;
702 return ssize_t(err);
703 }
704
705 size_t toWrite;
706 if (mFormat == AudioSystem::PCM_8_BIT) {
707 // Divide capacity by 2 to take expansion into account
708 toWrite = audioBuffer.size>>1;
709 // 8 to 16 bit conversion
710 int count = toWrite;
711 int16_t *dst = (int16_t *)(audioBuffer.i8);
712 while(count--) {
713 *dst++ = (int16_t)(*src++^0x80) << 8;
714 }
715 }else {
716 toWrite = audioBuffer.size;
717 memcpy(audioBuffer.i8, src, toWrite);
718 src += toWrite;
719 }
720 userSize -= toWrite;
721 written += toWrite;
722
723 releaseBuffer(&audioBuffer);
724 } while (userSize);
725
726 return written;
727}
728
729// -------------------------------------------------------------------------
730
731bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
732{
733 Buffer audioBuffer;
734 uint32_t frames;
735 size_t writtenSize;
736
737 // Manage underrun callback
738 if (mActive && (mCblk->framesReady() == 0)) {
739 LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
740 if (mCblk->flowControlFlag == 0) {
741 mCbf(EVENT_UNDERRUN, mUserData, 0);
742 if (mCblk->server == mCblk->frameCount) {
743 mCbf(EVENT_BUFFER_END, mUserData, 0);
744 }
745 mCblk->flowControlFlag = 1;
746 if (mSharedBuffer != 0) return false;
747 }
748 }
749
750 // Manage loop end callback
751 while (mLoopCount > mCblk->loopCount) {
752 int loopCount = -1;
753 mLoopCount--;
754 if (mLoopCount >= 0) loopCount = mLoopCount;
755
756 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
757 }
758
759 // Manage marker callback
760 if(mMarkerPosition > 0) {
761 if (mCblk->server >= mMarkerPosition) {
762 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
763 mMarkerPosition = 0;
764 }
765 }
766
767 // Manage new position callback
768 if(mUpdatePeriod > 0) {
769 while (mCblk->server >= mNewPosition) {
770 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
771 mNewPosition += mUpdatePeriod;
772 }
773 }
774
775 // If Shared buffer is used, no data is requested from client.
776 if (mSharedBuffer != 0) {
777 frames = 0;
778 } else {
779 frames = mRemainingFrames;
780 }
781
782 do {
783
784 audioBuffer.frameCount = frames;
785
786 // Calling obtainBuffer() with a wait count of 1
787 // limits wait time to WAIT_PERIOD_MS. This prevents from being
788 // stuck here not being able to handle timed events (position, markers, loops).
789 status_t err = obtainBuffer(&audioBuffer, 1);
790 if (err < NO_ERROR) {
791 if (err != TIMED_OUT) {
792 LOGE("Error obtaining an audio buffer, giving up.");
793 return false;
794 }
795 break;
796 }
797 if (err == status_t(STOPPED)) return false;
798
799 // Divide buffer size by 2 to take into account the expansion
800 // due to 8 to 16 bit conversion: the callback must fill only half
801 // of the destination buffer
802 if (mFormat == AudioSystem::PCM_8_BIT) {
803 audioBuffer.size >>= 1;
804 }
805
806 size_t reqSize = audioBuffer.size;
807 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
808 writtenSize = audioBuffer.size;
809
810 // Sanity check on returned size
811 if (ssize_t(writtenSize) <= 0) break;
812 if (writtenSize > reqSize) writtenSize = reqSize;
813
814 if (mFormat == AudioSystem::PCM_8_BIT) {
815 // 8 to 16 bit conversion
816 const int8_t *src = audioBuffer.i8 + writtenSize-1;
817 int count = writtenSize;
818 int16_t *dst = audioBuffer.i16 + writtenSize-1;
819 while(count--) {
820 *dst-- = (int16_t)(*src--^0x80) << 8;
821 }
822 writtenSize <<= 1;
823 }
824
825 audioBuffer.size = writtenSize;
826 audioBuffer.frameCount = writtenSize/mChannelCount/sizeof(int16_t);
827 frames -= audioBuffer.frameCount;
828
829 releaseBuffer(&audioBuffer);
830 }
831 while (frames);
832
833 if (frames == 0) {
834 mRemainingFrames = mNotificationFrames;
835 } else {
836 mRemainingFrames = frames;
837 }
838 return true;
839}
840
841status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
842{
843
844 const size_t SIZE = 256;
845 char buffer[SIZE];
846 String8 result;
847
848 result.append(" AudioTrack::dump\n");
849 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
850 result.append(buffer);
851 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mFrameCount);
852 result.append(buffer);
853 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", mSampleRate, mStatus, mMuted);
854 result.append(buffer);
855 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
856 result.append(buffer);
857 ::write(fd, result.string(), result.size());
858 return NO_ERROR;
859}
860
861// =========================================================================
862
863AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
864 : Thread(bCanCallJava), mReceiver(receiver)
865{
866}
867
868bool AudioTrack::AudioTrackThread::threadLoop()
869{
870 return mReceiver.processAudioBuffer(this);
871}
872
873status_t AudioTrack::AudioTrackThread::readyToRun()
874{
875 return NO_ERROR;
876}
877
878void AudioTrack::AudioTrackThread::onFirstRef()
879{
880}
881
882// =========================================================================
883
884audio_track_cblk_t::audio_track_cblk_t()
885 : user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
886 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0)
887{
888}
889
890uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
891{
892 uint32_t u = this->user;
893
894 u += frameCount;
895 // Ensure that user is never ahead of server for AudioRecord
896 if (out) {
897 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
898 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
899 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
900 }
901 } else if (u > this->server) {
902 LOGW("stepServer occured after track reset");
903 u = this->server;
904 }
905
906 if (u >= userBase + this->frameCount) {
907 userBase += this->frameCount;
908 }
909
910 this->user = u;
911
912 // Clear flow control error condition as new data has been written/read to/from buffer.
913 flowControlFlag = 0;
914
915 return u;
916}
917
918bool audio_track_cblk_t::stepServer(uint32_t frameCount)
919{
920 // the code below simulates lock-with-timeout
921 // we MUST do this to protect the AudioFlinger server
922 // as this lock is shared with the client.
923 status_t err;
924
925 err = lock.tryLock();
926 if (err == -EBUSY) { // just wait a bit
927 usleep(1000);
928 err = lock.tryLock();
929 }
930 if (err != NO_ERROR) {
931 // probably, the client just died.
932 return false;
933 }
934
935 uint32_t s = this->server;
936
937 s += frameCount;
938 if (out) {
939 // Mark that we have read the first buffer so that next time stepUser() is called
940 // we switch to normal obtainBuffer() timeout period
941 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
942 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS - 1;
943 }
944 // It is possible that we receive a flush()
945 // while the mixer is processing a block: in this case,
946 // stepServer() is called After the flush() has reset u & s and
947 // we have s > u
948 if (s > this->user) {
949 LOGW("stepServer occured after track reset");
950 s = this->user;
951 }
952 }
953
954 if (s >= loopEnd) {
955 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
956 s = loopStart;
957 if (--loopCount == 0) {
958 loopEnd = UINT_MAX;
959 loopStart = UINT_MAX;
960 }
961 }
962 if (s >= serverBase + this->frameCount) {
963 serverBase += this->frameCount;
964 }
965
966 this->server = s;
967
968 cv.signal();
969 lock.unlock();
970 return true;
971}
972
973void* audio_track_cblk_t::buffer(uint32_t offset) const
974{
975 return (int16_t *)this->buffers + (offset-userBase)*this->channels;
976}
977
978uint32_t audio_track_cblk_t::framesAvailable()
979{
980 Mutex::Autolock _l(lock);
981 return framesAvailable_l();
982}
983
984uint32_t audio_track_cblk_t::framesAvailable_l()
985{
986 uint32_t u = this->user;
987 uint32_t s = this->server;
988
989 if (out) {
990 uint32_t limit = (s < loopStart) ? s : loopStart;
991 return limit + frameCount - u;
992 } else {
993 return frameCount + u - s;
994 }
995}
996
997uint32_t audio_track_cblk_t::framesReady()
998{
999 uint32_t u = this->user;
1000 uint32_t s = this->server;
1001
1002 if (out) {
1003 if (u < loopEnd) {
1004 return u - s;
1005 } else {
1006 Mutex::Autolock _l(lock);
1007 if (loopCount >= 0) {
1008 return (loopEnd - loopStart)*loopCount + u - s;
1009 } else {
1010 return UINT_MAX;
1011 }
1012 }
1013 } else {
1014 return s - u;
1015 }
1016}
1017
1018// -------------------------------------------------------------------------
1019
1020}; // namespace android
1021