AudioTrackShared.h revision ad3af3305f024bcbbd55c894a4995e449498e1ba
12910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner/*
2fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner * Copyright (C) 2007 The Android Open Source Project
32910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner *
42910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner * Licensed under the Apache License, Version 2.0 (the "License");
52910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner * you may not use this file except in compliance with the License.
62910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner * You may obtain a copy of the License at
72910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner *
82910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner *      http://www.apache.org/licenses/LICENSE-2.0
92910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner *
102910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner * Unless required by applicable law or agreed to in writing, software
112910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner * distributed under the License is distributed on an "AS IS" BASIS,
12fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
136af6765e2f3bc930d0dce21d752bea570a1b1362David 'Digit' Turner * See the License for the specific language governing permissions and
141c31e3e43ce4cca85a707dfff631e5e102fdecedDavid 'Digit' Turner * limitations under the License.
151c31e3e43ce4cca85a707dfff631e5e102fdecedDavid 'Digit' Turner */
162910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
172910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#ifndef ANDROID_AUDIO_TRACK_SHARED_H
182910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#define ANDROID_AUDIO_TRACK_SHARED_H
192910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
202910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#include <stdint.h>
212910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#include <sys/types.h>
222910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
232910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#include <utils/threads.h>
242910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#include <utils/Log.h>
252910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#include <utils/RefBase.h>
262910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#include <media/nbaio/roundup.h>
272910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#include <media/SingleStateQueue.h>
282910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#include <private/media/StaticAudioTrackState.h>
292910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
30910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turnernamespace android {
312910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
322910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner// ----------------------------------------------------------------------------
332910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
34aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner#define CBLK_UNDERRUN   0x01 // set by server immediately on output underrun, cleared by client
352910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#define CBLK_FORCEREADY 0x02 // set: track is considered ready immediately by AudioFlinger,
362910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                             // clear: track is ready when buffer full
372910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#define CBLK_INVALID    0x04 // track buffer invalidated by AudioFlinger, need to re-create
382910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#define CBLK_DISABLED   0x08 // output track disabled by AudioFlinger due to underrun,
392910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                             // need to re-start.  Unlike CBLK_UNDERRUN, this is not set
402910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                             // immediately, but only after a long string of underruns.
412910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner// 0x10 unused
422910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#define CBLK_LOOP_CYCLE 0x20 // set by server each time a loop cycle other than final one completes
432910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#define CBLK_LOOP_FINAL 0x40 // set by server when the final loop cycle completes
442910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#define CBLK_BUFFER_END 0x80 // set by server when the position reaches end of buffer if not looping
45910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner#define CBLK_OVERRUN   0x100 // set by server immediately on input overrun, cleared by client
46910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner#define CBLK_INTERRUPT 0x200 // set by client on interrupt(), cleared by client in obtainBuffer()
472910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#define CBLK_STREAM_END_DONE 0x400 // set by server on render completion, cleared by client
482910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
492910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner//EL_FIXME 20 seconds may not be enough and must be reconciled with new obtainBuffer implementation
502910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner#define MAX_RUN_OFFLOADED_TIMEOUT_MS 20000 //assuming upto a maximum of 20 seconds of offloaded
51fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner
522910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turnerstruct AudioTrackSharedStreaming {
53910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner    // similar to NBAIO MonoPipe
54910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner    // in continuously incrementing frame units, take modulo buffer size, which must be a power of 2
552910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner    volatile int32_t mFront;    // read by server
562910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner    volatile int32_t mRear;     // write by client
572910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner    volatile int32_t mFlush;    // incremented by client to indicate a request to flush;
582910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                                // server notices and discards all data between mFront and mRear
592910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner    volatile uint32_t mUnderrunFrames;  // server increments for each unavailable but desired frame
602910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner};
612910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
622910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turnertypedef SingleStateQueue<StaticAudioTrackState> StaticAudioTrackSingleStateQueue;
632910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
64910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turnerstruct AudioTrackSharedStatic {
652910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner    StaticAudioTrackSingleStateQueue::Shared
662910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                    mSingleStateQueue;
672910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner    size_t          mBufferPosition;    // updated asynchronously by server,
682910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                                        // "for entertainment purposes only"
692910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner};
702910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
71fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner// ----------------------------------------------------------------------------
722910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
732910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner// Important: do not add any virtual methods, including ~
74910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turnerstruct audio_track_cblk_t
752910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner{
762910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                // Since the control block is always located in shared memory, this constructor
77fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                // is only used for placement new().  It is never used for regular new() or stack.
78fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                            audio_track_cblk_t();
79fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                /*virtual*/ ~audio_track_cblk_t() { }
802910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
812910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                friend class Proxy;
822910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                friend class ClientProxy;
83910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                friend class AudioTrackClientProxy;
84fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                friend class AudioRecordClientProxy;
85fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                friend class ServerProxy;
86fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                friend class AudioTrackServerProxy;
87fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                friend class AudioRecordServerProxy;
88fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner
89910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner    // The data members are grouped so that members accessed frequently and in the same context
90fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner    // are in the same line of data cache.
91fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner
92fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner    volatile    uint32_t    server;     // updated asynchronously by server,
93fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                                        // "for entertainment purposes only"
94fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner
95fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                size_t      frameCount_;    // used during creation to pass actual track buffer size
96fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                                            // from AudioFlinger to client, and not referenced again
97fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                                            // FIXME remove here and replace by createTrack() in/out
98fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                                            // parameter
99fd4c0076b7470f5962ff462bae9cd9f208e059b7David Turner                                            // renamed to "_" to detect incorrect use
100910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
101910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner    volatile    int32_t     mFutex;     // event flag: down (P) by client,
102910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                                        // up (V) by server or binderDied() or interrupt()
103910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner#define CBLK_FUTEX_WAKE 1               // if event flag bit is set, then a deferred wake is pending
104910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
105910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turnerprivate:
106910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
107910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                size_t      mMinimum;       // server wakes up client if available >= mMinimum
108910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
109910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                // Channel volumes are fixed point U4.12, so 0x1000 means 1.0.
110910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                // Left channel is in [0:15], right channel is in [16:31].
111910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                // Always read and write the combined pair atomically.
112910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                // For AudioTrack only, not used by AudioRecord.
113910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                uint32_t    mVolumeLR;
114910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
115910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                uint32_t    mSampleRate;    // AudioTrack only: client's requested sample rate in Hz
116910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                                            // or 0 == default. Write-only client, read-only server.
117910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
118910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                // client write-only, server read-only
119910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                uint16_t    mSendLevel;      // Fixed point U4.12 so 0x1000 means 1.0
120910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
121910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                uint8_t     mPad2;           // unused
122910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
123910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turnerpublic:
124910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                // read-only for client, server writes once at initialization and is then read-only
125910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                uint8_t     mName;           // normal tracks: track name, fast tracks: track index
126910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
127910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner    volatile    int32_t     flags;
128910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
129910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                // Cache line boundary (32 bytes)
130910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner
131910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turnerpublic:
1322910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                union {
1332910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                    AudioTrackSharedStreaming   mStreaming;
1342910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                    AudioTrackSharedStatic      mStatic;
135910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner                    int                         mAlign[8];
1362910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                } u;
1372910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
1382910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner                // Cache line boundary (32 bytes)
1392910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner};
1402910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
1412910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner// ----------------------------------------------------------------------------
1422910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
1432910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner// Proxy for shared memory control block, to isolate callers from needing to know the details.
1442910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner// There is exactly one ClientProxy and one ServerProxy per shared memory control block.
1452910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner// The proxies are located in normal memory, and are not multi-thread safe within a given side.
1462910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turnerclass Proxy : public RefBase {
1472910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turnerprotected:
1482910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner    Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, bool isOut,
1492910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner            bool clientInServer);
1502910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner    virtual ~Proxy() { }
1512910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner
1522910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turnerpublic:
1532910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner    struct Buffer {
154910aea96b67d7f0357f586c47f20848ec435aa1bDavid 'Digit' Turner        size_t  mFrameCount;            // number of frames available in this buffer
155aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner        void*   mRaw;                   // pointer to first frame
1562910f183ddd5286911bc1e3499ea93cb57de8b75David 'Digit' Turner        size_t  mNonContig;             // number of additional non-contiguous frames available
157    };
158
159protected:
160    // These refer to shared memory, and are virtual addresses with respect to the current process.
161    // They may have different virtual addresses within the other process.
162    audio_track_cblk_t* const   mCblk;  // the control block
163    void* const     mBuffers;           // starting address of buffers
164
165    const size_t    mFrameCount;        // not necessarily a power of 2
166    const size_t    mFrameSize;         // in bytes
167    const size_t    mFrameCountP2;      // mFrameCount rounded to power of 2, streaming mode
168    const bool      mIsOut;             // true for AudioTrack, false for AudioRecord
169    const bool      mClientInServer;    // true for OutputTrack, false for AudioTrack & AudioRecord
170    bool            mIsShutdown;        // latch set to true when shared memory corruption detected
171};
172
173// ----------------------------------------------------------------------------
174
175// Proxy seen by AudioTrack client and AudioRecord client
176class ClientProxy : public Proxy {
177protected:
178    ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
179            bool isOut, bool clientInServer);
180    virtual ~ClientProxy() { }
181
182public:
183    static const struct timespec kForever;
184    static const struct timespec kNonBlocking;
185
186    // Obtain a buffer with filled frames (reading) or empty frames (writing).
187    // It is permitted to call obtainBuffer() multiple times in succession, without any intervening
188    // calls to releaseBuffer().  In that case, the final obtainBuffer() is the one that effectively
189    // sets or extends the unreleased frame count.
190    // On entry:
191    //  buffer->mFrameCount should be initialized to maximum number of desired frames,
192    //      which must be > 0.
193    //  buffer->mNonContig is unused.
194    //  buffer->mRaw is unused.
195    //  requested is the requested timeout in local monotonic delta time units:
196    //      NULL or &kNonBlocking means non-blocking (zero timeout).
197    //      &kForever means block forever (infinite timeout).
198    //      Other values mean a specific timeout in local monotonic delta time units.
199    //  elapsed is a pointer to a location that will hold the total local monotonic time that
200    //      elapsed while blocked, or NULL if not needed.
201    // On exit:
202    //  buffer->mFrameCount has the actual number of contiguous available frames,
203    //      which is always 0 when the return status != NO_ERROR.
204    //  buffer->mNonContig is the number of additional non-contiguous available frames.
205    //  buffer->mRaw is a pointer to the first available frame,
206    //      or NULL when buffer->mFrameCount == 0.
207    // The return status is one of:
208    //  NO_ERROR    Success, buffer->mFrameCount > 0.
209    //  WOULD_BLOCK Non-blocking mode and no frames are available.
210    //  TIMED_OUT   Timeout occurred before any frames became available.
211    //              This can happen even for infinite timeout, due to a spurious wakeup.
212    //              In this case, the caller should investigate and then re-try as appropriate.
213    //  DEAD_OBJECT Server has died or invalidated, caller should destroy this proxy and re-create.
214    //  -EINTR      Call has been interrupted.  Look around to see why, and then perhaps try again.
215    //  NO_INIT     Shared memory is corrupt.
216    //  BAD_VALUE   On entry buffer == NULL or buffer->mFrameCount == 0.
217    status_t    obtainBuffer(Buffer* buffer, const struct timespec *requested = NULL,
218            struct timespec *elapsed = NULL);
219
220    // Release (some of) the frames last obtained.
221    // On entry, buffer->mFrameCount should have the number of frames to release,
222    // which must (cumulatively) be <= the number of frames last obtained but not yet released.
223    // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer().
224    // It is permitted to call releaseBuffer() multiple times to release the frames in chunks.
225    // On exit:
226    //  buffer->mFrameCount is zero.
227    //  buffer->mRaw is NULL.
228    void        releaseBuffer(Buffer* buffer);
229
230    // Call after detecting server's death
231    void        binderDied();
232
233    // Call to force an obtainBuffer() to return quickly with -EINTR
234    void        interrupt();
235
236    size_t      getPosition() {
237        return mEpoch + mCblk->server;
238    }
239
240    void        setEpoch(size_t epoch) {
241        mEpoch = epoch;
242    }
243
244    void        setMinimum(size_t minimum) {
245        mCblk->mMinimum = minimum;
246    }
247
248    // Return the number of frames that would need to be obtained and released
249    // in order for the client to be aligned at start of buffer
250    virtual size_t  getMisalignment();
251
252    size_t      getEpoch() const {
253        return mEpoch;
254    }
255
256private:
257    size_t      mEpoch;
258};
259
260// ----------------------------------------------------------------------------
261
262// Proxy used by AudioTrack client, which also includes AudioFlinger::PlaybackThread::OutputTrack
263class AudioTrackClientProxy : public ClientProxy {
264public:
265    AudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
266            size_t frameSize, bool clientInServer = false)
267        : ClientProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/,
268          clientInServer) { }
269    virtual ~AudioTrackClientProxy() { }
270
271    // No barriers on the following operations, so the ordering of loads/stores
272    // with respect to other parameters is UNPREDICTABLE. That's considered safe.
273
274    // caller must limit to 0.0 <= sendLevel <= 1.0
275    void        setSendLevel(float sendLevel) {
276        mCblk->mSendLevel = uint16_t(sendLevel * 0x1000);
277    }
278
279    // caller must limit to 0 <= volumeLR <= 0x10001000
280    void        setVolumeLR(uint32_t volumeLR) {
281        mCblk->mVolumeLR = volumeLR;
282    }
283
284    void        setSampleRate(uint32_t sampleRate) {
285        mCblk->mSampleRate = sampleRate;
286    }
287
288    virtual void flush();
289
290    virtual uint32_t    getUnderrunFrames() const {
291        return mCblk->u.mStreaming.mUnderrunFrames;
292    }
293};
294
295class StaticAudioTrackClientProxy : public AudioTrackClientProxy {
296public:
297    StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
298            size_t frameSize);
299    virtual ~StaticAudioTrackClientProxy() { }
300
301    virtual void    flush();
302
303#define MIN_LOOP    16  // minimum length of each loop iteration in frames
304            void    setLoop(size_t loopStart, size_t loopEnd, int loopCount);
305            size_t  getBufferPosition();
306
307    virtual size_t  getMisalignment() {
308        return 0;
309    }
310
311    virtual uint32_t    getUnderrunFrames() const {
312        return 0;
313    }
314
315private:
316    StaticAudioTrackSingleStateQueue::Mutator   mMutator;
317    size_t          mBufferPosition;    // so that getBufferPosition() appears to be synchronous
318};
319
320// ----------------------------------------------------------------------------
321
322// Proxy used by AudioRecord client
323class AudioRecordClientProxy : public ClientProxy {
324public:
325    AudioRecordClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
326            size_t frameSize)
327        : ClientProxy(cblk, buffers, frameCount, frameSize,
328            false /*isOut*/, false /*clientInServer*/) { }
329    ~AudioRecordClientProxy() { }
330};
331
332// ----------------------------------------------------------------------------
333
334// Proxy used by AudioFlinger server
335class ServerProxy : public Proxy {
336protected:
337    ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
338            bool isOut, bool clientInServer);
339public:
340    virtual ~ServerProxy() { }
341
342    // Obtain a buffer with filled frames (writing) or empty frames (reading).
343    // It is permitted to call obtainBuffer() multiple times in succession, without any intervening
344    // calls to releaseBuffer().  In that case, the final obtainBuffer() is the one that effectively
345    // sets or extends the unreleased frame count.
346    // Always non-blocking.
347    // On entry:
348    //  buffer->mFrameCount should be initialized to maximum number of desired frames,
349    //      which must be > 0.
350    //  buffer->mNonContig is unused.
351    //  buffer->mRaw is unused.
352    // On exit:
353    //  buffer->mFrameCount has the actual number of contiguous available frames,
354    //      which is always 0 when the return status != NO_ERROR.
355    //  buffer->mNonContig is the number of additional non-contiguous available frames.
356    //  buffer->mRaw is a pointer to the first available frame,
357    //      or NULL when buffer->mFrameCount == 0.
358    // The return status is one of:
359    //  NO_ERROR    Success, buffer->mFrameCount > 0.
360    //  WOULD_BLOCK No frames are available.
361    //  NO_INIT     Shared memory is corrupt.
362    virtual status_t    obtainBuffer(Buffer* buffer);
363
364    // Release (some of) the frames last obtained.
365    // On entry, buffer->mFrameCount should have the number of frames to release,
366    // which must (cumulatively) be <= the number of frames last obtained but not yet released.
367    // It is permitted to call releaseBuffer() multiple times to release the frames in chunks.
368    // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer().
369    // On exit:
370    //  buffer->mFrameCount is zero.
371    //  buffer->mRaw is NULL.
372    virtual void        releaseBuffer(Buffer* buffer);
373
374protected:
375    size_t      mUnreleased;    // unreleased frames remaining from most recent obtainBuffer()
376    size_t      mAvailToClient; // estimated frames available to client prior to releaseBuffer()
377private:
378    int32_t     mFlush;         // our copy of cblk->u.mStreaming.mFlush, for streaming output only
379    bool        mDeferWake;     // whether another releaseBuffer() is expected soon
380};
381
382// Proxy used by AudioFlinger for servicing AudioTrack
383class AudioTrackServerProxy : public ServerProxy {
384public:
385    AudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
386            size_t frameSize, bool clientInServer = false)
387        : ServerProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/, clientInServer) { }
388protected:
389    virtual ~AudioTrackServerProxy() { }
390
391public:
392    // return value of these methods must be validated by the caller
393    uint32_t    getSampleRate() const { return mCblk->mSampleRate; }
394    uint16_t    getSendLevel_U4_12() const { return mCblk->mSendLevel; }
395    uint32_t    getVolumeLR() const { return mCblk->mVolumeLR; }
396
397    // estimated total number of filled frames available to server to read,
398    // which may include non-contiguous frames
399    virtual size_t      framesReady();
400
401    // Currently AudioFlinger will call framesReady() for a fast track from two threads:
402    // FastMixer thread, and normal mixer thread.  This is dangerous, as the proxy is intended
403    // to be called from at most one thread of server, and one thread of client.
404    // As a temporary workaround, this method informs the proxy implementation that it
405    // should avoid doing a state queue poll from within framesReady().
406    // FIXME Change AudioFlinger to not call framesReady() from normal mixer thread.
407    virtual void        framesReadyIsCalledByMultipleThreads() { }
408};
409
410class StaticAudioTrackServerProxy : public AudioTrackServerProxy {
411public:
412    StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
413            size_t frameSize);
414protected:
415    virtual ~StaticAudioTrackServerProxy() { }
416
417public:
418    virtual size_t      framesReady();
419    virtual void        framesReadyIsCalledByMultipleThreads();
420    virtual status_t    obtainBuffer(Buffer* buffer);
421    virtual void        releaseBuffer(Buffer* buffer);
422
423private:
424    ssize_t             pollPosition(); // poll for state queue update, and return current position
425    StaticAudioTrackSingleStateQueue::Observer  mObserver;
426    size_t              mPosition;  // server's current play position in frames, relative to 0
427    size_t              mEnd;       // cached value computed from mState, safe for asynchronous read
428    bool                mFramesReadyIsCalledByMultipleThreads;
429    StaticAudioTrackState   mState;
430};
431
432// Proxy used by AudioFlinger for servicing AudioRecord
433class AudioRecordServerProxy : public ServerProxy {
434public:
435    AudioRecordServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
436            size_t frameSize)
437        : ServerProxy(cblk, buffers, frameCount, frameSize, false /*isOut*/,
438            false /*clientInServer*/) { }
439protected:
440    virtual ~AudioRecordServerProxy() { }
441};
442
443// ----------------------------------------------------------------------------
444
445}; // namespace android
446
447#endif // ANDROID_AUDIO_TRACK_SHARED_H
448