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