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