AudioTrack.h revision 9c6745f128648f6e0144b74ee593911a9fa10d51
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_AUDIOTRACK_H
18#define ANDROID_AUDIOTRACK_H
19
20#include <stdint.h>
21#include <sys/types.h>
22
23#include <media/IAudioFlinger.h>
24#include <media/IAudioTrack.h>
25#include <media/AudioSystem.h>
26
27#include <utils/RefBase.h>
28#include <utils/Errors.h>
29#include <binder/IInterface.h>
30#include <binder/IMemory.h>
31#include <cutils/sched_policy.h>
32#include <utils/threads.h>
33
34namespace android {
35
36// ----------------------------------------------------------------------------
37
38class audio_track_cblk_t;
39class AudioTrackClientProxy;
40
41// ----------------------------------------------------------------------------
42
43class AudioTrack : virtual public RefBase
44{
45public:
46    enum channel_index {
47        MONO   = 0,
48        LEFT   = 0,
49        RIGHT  = 1
50    };
51
52    /* Events used by AudioTrack callback function (audio_track_cblk_t).
53     * Keep in sync with frameworks/base/media/java/android/media/AudioTrack.java NATIVE_EVENT_*.
54     */
55    enum event_type {
56        EVENT_MORE_DATA = 0,        // Request to write more data to buffer.
57                                    // If this event is delivered but the callback handler
58                                    // does not want to write more data, the handler must explicitly
59                                    // ignore the event by setting frameCount to zero.
60        EVENT_UNDERRUN = 1,         // Buffer underrun occurred.
61        EVENT_LOOP_END = 2,         // Sample loop end was reached; playback restarted from
62                                    // loop start if loop count was not 0.
63        EVENT_MARKER = 3,           // Playback head is at the specified marker position
64                                    // (See setMarkerPosition()).
65        EVENT_NEW_POS = 4,          // Playback head is at a new position
66                                    // (See setPositionUpdatePeriod()).
67        EVENT_BUFFER_END = 5        // Playback head is at the end of the buffer.
68    };
69
70    /* Client should declare Buffer on the stack and pass address to obtainBuffer()
71     * and releaseBuffer().  See also callback_t for EVENT_MORE_DATA.
72     */
73
74    class Buffer
75    {
76    public:
77        size_t      frameCount;   // number of sample frames corresponding to size;
78                                  // on input it is the number of frames desired,
79                                  // on output is the number of frames actually filled
80
81        size_t      size;         // input/output in byte units
82        union {
83            void*       raw;
84            short*      i16;    // signed 16-bit
85            int8_t*     i8;     // unsigned 8-bit, offset by 0x80
86        };
87    };
88
89
90    /* As a convenience, if a callback is supplied, a handler thread
91     * is automatically created with the appropriate priority. This thread
92     * invokes the callback when a new buffer becomes available or various conditions occur.
93     * Parameters:
94     *
95     * event:   type of event notified (see enum AudioTrack::event_type).
96     * user:    Pointer to context for use by the callback receiver.
97     * info:    Pointer to optional parameter according to event type:
98     *          - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write
99     *            more bytes than indicated by 'size' field and update 'size' if fewer bytes are
100     *            written.
101     *          - EVENT_UNDERRUN: unused.
102     *          - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
103     *          - EVENT_MARKER: pointer to an uint32_t containing the marker position in frames.
104     *          - EVENT_NEW_POS: pointer to an uint32_t containing the new position in frames.
105     *          - EVENT_BUFFER_END: unused.
106     */
107
108    typedef void (*callback_t)(int event, void* user, void *info);
109
110    /* Returns the minimum frame count required for the successful creation of
111     * an AudioTrack object.
112     * Returned status (from utils/Errors.h) can be:
113     *  - NO_ERROR: successful operation
114     *  - NO_INIT: audio server or audio hardware not initialized
115     */
116
117     static status_t getMinFrameCount(size_t* frameCount,
118                                      audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT,
119                                      uint32_t sampleRate = 0);
120
121    /* Constructs an uninitialized AudioTrack. No connection with
122     * AudioFlinger takes place.  Use set() after this.
123     */
124                        AudioTrack();
125
126    /* Creates an AudioTrack object and registers it with AudioFlinger.
127     * Once created, the track needs to be started before it can be used.
128     * Unspecified values are set to appropriate default values.
129     * With this constructor, the track is configured for streaming mode.
130     * Data to be rendered is supplied by write() or by the callback EVENT_MORE_DATA.
131     * Intermixing a combination of write() and non-ignored EVENT_MORE_DATA is deprecated.
132     *
133     * Parameters:
134     *
135     * streamType:         Select the type of audio stream this track is attached to
136     *                     (e.g. AUDIO_STREAM_MUSIC).
137     * sampleRate:         Track sampling rate in Hz.
138     * format:             Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed
139     *                     16 bits per sample).
140     * channelMask:        Channel mask.
141     * frameCount:         Minimum size of track PCM buffer in frames. This defines the
142     *                     application's contribution to the
143     *                     latency of the track. The actual size selected by the AudioTrack could be
144     *                     larger if the requested size is not compatible with current audio HAL
145     *                     configuration.  Zero means to use a default value.
146     * flags:              See comments on audio_output_flags_t in <system/audio.h>.
147     * cbf:                Callback function. If not null, this function is called periodically
148     *                     to provide new data and inform of marker, position updates, etc.
149     * user:               Context for use by the callback receiver.
150     * notificationFrames: The callback function is called each time notificationFrames PCM
151     *                     frames have been consumed from track input buffer.
152     * sessionId:          Specific session ID, or zero to use default.
153     * threadCanCallJava:  Whether callbacks are made from an attached thread and thus can call JNI.
154     *                     If not present in parameter list, then fixed at false.
155     */
156
157                        AudioTrack( audio_stream_type_t streamType,
158                                    uint32_t sampleRate  = 0,
159                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
160                                    audio_channel_mask_t channelMask = 0,
161                                    int frameCount       = 0,
162                                    audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
163                                    callback_t cbf       = NULL,
164                                    void* user           = NULL,
165                                    int notificationFrames = 0,
166                                    int sessionId        = 0);
167
168    /* Creates an audio track and registers it with AudioFlinger.
169     * With this constructor, the track is configured for static buffer mode.
170     * The format must not be 8-bit linear PCM.
171     * Data to be rendered is passed in a shared memory buffer
172     * identified by the argument sharedBuffer, which must be non-0.
173     * The memory should be initialized to the desired data before calling start().
174     * The write() method is not supported in this case.
175     * It is recommended to pass a callback function to be notified of playback end by an
176     * EVENT_UNDERRUN event.
177     * FIXME EVENT_MORE_DATA still occurs; it must be ignored.
178     */
179
180                        AudioTrack( audio_stream_type_t streamType,
181                                    uint32_t sampleRate = 0,
182                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
183                                    audio_channel_mask_t channelMask = 0,
184                                    const sp<IMemory>& sharedBuffer = 0,
185                                    audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
186                                    callback_t cbf      = NULL,
187                                    void* user          = NULL,
188                                    int notificationFrames = 0,
189                                    int sessionId       = 0);
190
191    /* Terminates the AudioTrack and unregisters it from AudioFlinger.
192     * Also destroys all resources associated with the AudioTrack.
193     */
194                        ~AudioTrack();
195
196    /* Initialize an uninitialized AudioTrack.
197     * Returned status (from utils/Errors.h) can be:
198     *  - NO_ERROR: successful initialization
199     *  - INVALID_OPERATION: AudioTrack is already initialized
200     *  - BAD_VALUE: invalid parameter (channelMask, format, sampleRate...)
201     *  - NO_INIT: audio server or audio hardware not initialized
202     * If sharedBuffer is non-0, the frameCount parameter is ignored and
203     * replaced by the shared buffer's total allocated size in frame units.
204     */
205            status_t    set(audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT,
206                            uint32_t sampleRate = 0,
207                            audio_format_t format = AUDIO_FORMAT_DEFAULT,
208                            audio_channel_mask_t channelMask = 0,
209                            int frameCount      = 0,
210                            audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
211                            callback_t cbf      = NULL,
212                            void* user          = NULL,
213                            int notificationFrames = 0,
214                            const sp<IMemory>& sharedBuffer = 0,
215                            bool threadCanCallJava = false,
216                            int sessionId       = 0);
217
218    /* Result of constructing the AudioTrack. This must be checked
219     * before using any AudioTrack API (except for set()), because using
220     * an uninitialized AudioTrack produces undefined results.
221     * See set() method above for possible return codes.
222     */
223            status_t    initCheck() const   { return mStatus; }
224
225    /* Returns this track's estimated latency in milliseconds.
226     * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
227     * and audio hardware driver.
228     */
229            uint32_t     latency() const    { return mLatency; }
230
231    /* getters, see constructors and set() */
232
233            audio_stream_type_t streamType() const { return mStreamType; }
234            audio_format_t format() const   { return mFormat; }
235
236    /* Return frame size in bytes, which for linear PCM is channelCount * (bit depth per channel / 8).
237     * channelCount is determined from channelMask, and bit depth comes from format.
238     * For non-linear formats, the frame size is typically 1 byte.
239     */
240            uint32_t    channelCount() const { return mChannelCount; }
241
242            uint32_t    frameCount() const  { return mFrameCount; }
243            size_t      frameSize() const   { return mFrameSize; }
244
245    /* Return the static buffer specified in constructor or set(), or 0 for streaming mode */
246            sp<IMemory> sharedBuffer() const { return mSharedBuffer; }
247
248    /* After it's created the track is not active. Call start() to
249     * make it active. If set, the callback will start being called.
250     * If the track was previously paused, volume is ramped up over the first mix buffer.
251     */
252            void        start();
253
254    /* Stop a track.
255     * In static buffer mode, the track is stopped immediately.
256     * In streaming mode, the callback will cease being called and
257     * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
258     * and will fill up buffers until the pool is exhausted.
259     * The stop does not occur immediately: any data remaining in the buffer
260     * is first drained, mixed, and output, and only then is the track marked as stopped.
261     */
262            void        stop();
263            bool        stopped() const;
264
265    /* Flush a stopped or paused track. All previously buffered data is discarded immediately.
266     * This has the effect of draining the buffers without mixing or output.
267     * Flush is intended for streaming mode, for example before switching to non-contiguous content.
268     * This function is a no-op if the track is not stopped or paused, or uses a static buffer.
269     */
270            void        flush();
271
272    /* Pause a track. After pause, the callback will cease being called and
273     * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
274     * and will fill up buffers until the pool is exhausted.
275     * Volume is ramped down over the next mix buffer following the pause request,
276     * and then the track is marked as paused.  It can be resumed with ramp up by start().
277     */
278            void        pause();
279
280    /* Set volume for this track, mostly used for games' sound effects
281     * left and right volumes. Levels must be >= 0.0 and <= 1.0.
282     * This is the older API.  New applications should use setVolume(float) when possible.
283     */
284            status_t    setVolume(float left, float right);
285
286    /* Set volume for all channels.  This is the preferred API for new applications,
287     * especially for multi-channel content.
288     */
289            status_t    setVolume(float volume);
290
291    /* Set the send level for this track. An auxiliary effect should be attached
292     * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0.
293     */
294            status_t    setAuxEffectSendLevel(float level);
295            void        getAuxEffectSendLevel(float* level) const;
296
297    /* Set sample rate for this track in Hz, mostly used for games' sound effects
298     */
299            status_t    setSampleRate(uint32_t sampleRate);
300
301    /* Return current sample rate in Hz, or 0 if unknown */
302            uint32_t    getSampleRate() const;
303
304    /* Enables looping and sets the start and end points of looping.
305     * Only supported for static buffer mode.
306     *
307     * FIXME The comments below are for the new planned interpretation which is not yet implemented.
308     * Currently the legacy behavior is still implemented, where loopStart and loopEnd
309     * are in wrapping (overflow) frame units like the return value of getPosition().
310     * The plan is to fix all callers to use the new version at same time implementation changes.
311     *
312     * Parameters:
313     *
314     * loopStart:   loop start in frames relative to start of buffer.
315     * loopEnd:     loop end in frames relative to start of buffer.
316     * loopCount:   number of loops to execute. Calling setLoop() with loopCount == 0 cancels any
317     *              pending or active loop. loopCount == -1 means infinite looping.
318     *
319     * For proper operation the following condition must be respected:
320     *      loopCount != 0 implies 0 <= loopStart < loopEnd <= frameCount().
321     *
322     * If the loop period (loopEnd - loopStart) is too small for the implementation to support,
323     * setLoop() will return BAD_VALUE.
324     *
325     */
326            status_t    setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
327
328    /* Sets marker position. When playback reaches the number of frames specified, a callback with
329     * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker
330     * notification callback.  To set a marker at a position which would compute as 0,
331     * a workaround is to the set the marker at a nearby position such as -1 or 1.
332     * If the AudioTrack has been opened with no callback function associated, the operation will
333     * fail.
334     *
335     * Parameters:
336     *
337     * marker:   marker position expressed in wrapping (overflow) frame units,
338     *           like the return value of getPosition().
339     *
340     * Returned status (from utils/Errors.h) can be:
341     *  - NO_ERROR: successful operation
342     *  - INVALID_OPERATION: the AudioTrack has no callback installed.
343     */
344            status_t    setMarkerPosition(uint32_t marker);
345            status_t    getMarkerPosition(uint32_t *marker) const;
346
347    /* Sets position update period. Every time the number of frames specified has been played,
348     * a callback with event type EVENT_NEW_POS is called.
349     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
350     * callback.
351     * If the AudioTrack has been opened with no callback function associated, the operation will
352     * fail.
353     * Extremely small values may be rounded up to a value the implementation can support.
354     *
355     * Parameters:
356     *
357     * updatePeriod:  position update notification period expressed in frames.
358     *
359     * Returned status (from utils/Errors.h) can be:
360     *  - NO_ERROR: successful operation
361     *  - INVALID_OPERATION: the AudioTrack has no callback installed.
362     */
363            status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
364            status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
365
366    /* Sets playback head position.
367     * Only supported for static buffer mode.
368     *
369     * FIXME The comments below are for the new planned interpretation which is not yet implemented.
370     * Currently the legacy behavior is still implemented, where the new position
371     * is in wrapping (overflow) frame units like the return value of getPosition().
372     * The plan is to fix all callers to use the new version at same time implementation changes.
373     *
374     * Parameters:
375     *
376     * position:  New playback head position in frames relative to start of buffer.
377     *            0 <= position <= frameCount().  Note that end of buffer is permitted,
378     *            but will result in an immediate underrun if started.
379     *
380     * Returned status (from utils/Errors.h) can be:
381     *  - NO_ERROR: successful operation
382     *  - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode.
383     *  - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack
384     *               buffer
385     */
386            status_t    setPosition(uint32_t position);
387
388    /* Return the total number of frames played since playback start.
389     * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
390     * It is reset to zero by flush(), reload(), and stop().
391     */
392            status_t    getPosition(uint32_t *position);
393
394#if 0
395    /* For static buffer mode only, this returns the current playback position in frames
396     * relative to start of buffer.  It is analogous to the new API for
397     * setLoop() and setPosition().  After underrun, the position will be at end of buffer.
398     */
399            status_t    getBufferPosition(uint32_t *position);
400#endif
401
402    /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
403     * rewriting the buffer before restarting playback after a stop.
404     * This method must be called with the AudioTrack in paused or stopped state.
405     * Not allowed in streaming mode.
406     *
407     * Returned status (from utils/Errors.h) can be:
408     *  - NO_ERROR: successful operation
409     *  - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode.
410     */
411            status_t    reload();
412
413    /* Returns a handle on the audio output used by this AudioTrack.
414     *
415     * Parameters:
416     *  none.
417     *
418     * Returned value:
419     *  handle on audio hardware output
420     */
421            audio_io_handle_t    getOutput();
422
423    /* Returns the unique session ID associated with this track.
424     *
425     * Parameters:
426     *  none.
427     *
428     * Returned value:
429     *  AudioTrack session ID.
430     */
431            int    getSessionId() const { return mSessionId; }
432
433    /* Attach track auxiliary output to specified effect. Use effectId = 0
434     * to detach track from effect.
435     *
436     * Parameters:
437     *
438     * effectId:  effectId obtained from AudioEffect::id().
439     *
440     * Returned status (from utils/Errors.h) can be:
441     *  - NO_ERROR: successful operation
442     *  - INVALID_OPERATION: the effect is not an auxiliary effect.
443     *  - BAD_VALUE: The specified effect ID is invalid
444     */
445            status_t    attachAuxEffect(int effectId);
446
447    /* Obtains a buffer of "frameCount" frames. The buffer must be
448     * filled entirely, and then released with releaseBuffer().
449     * If the track is stopped, obtainBuffer() returns
450     * STOPPED instead of NO_ERROR as long as there are buffers available,
451     * at which point NO_MORE_BUFFERS is returned.
452     * Buffers will be returned until the pool
453     * is exhausted, at which point obtainBuffer() will either block
454     * or return WOULD_BLOCK depending on the value of the "blocking"
455     * parameter.
456     *
457     * obtainBuffer() and releaseBuffer() are deprecated for direct use by applications,
458     * which should use write() or callback EVENT_MORE_DATA instead.
459     *
460     * Interpretation of waitCount:
461     *  +n  limits wait time to n * WAIT_PERIOD_MS,
462     *  -1  causes an (almost) infinite wait time,
463     *   0  non-blocking.
464     *
465     * Buffer fields
466     * On entry:
467     *  frameCount  number of frames requested
468     * After error return:
469     *  frameCount  0
470     *  size        0
471     *  raw         undefined
472     * After successful return:
473     *  frameCount  actual number of frames available, <= number requested
474     *  size        actual number of bytes available
475     *  raw         pointer to the buffer
476     */
477
478        enum {
479            NO_MORE_BUFFERS = 0x80000001,   // same name in AudioFlinger.h, ok to be different value
480            STOPPED = 1
481        };
482
483            status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
484
485    /* Release a filled buffer of "frameCount" frames for AudioFlinger to process. */
486            void        releaseBuffer(Buffer* audioBuffer);
487
488    /* As a convenience we provide a write() interface to the audio buffer.
489     * This is implemented on top of obtainBuffer/releaseBuffer. For best
490     * performance use callbacks. Returns actual number of bytes written >= 0,
491     * or one of the following negative status codes:
492     *      INVALID_OPERATION   AudioTrack is configured for shared buffer mode
493     *      BAD_VALUE           size is invalid
494     *      STOPPED             AudioTrack was stopped during the write
495     *      NO_MORE_BUFFERS     when obtainBuffer() returns same
496     *      or any other error code returned by IAudioTrack::start() or restoreTrack_l().
497     * Not supported for static buffer mode.
498     */
499            ssize_t     write(const void* buffer, size_t size);
500
501    /*
502     * Dumps the state of an audio track.
503     */
504            status_t dump(int fd, const Vector<String16>& args) const;
505
506protected:
507    /* copying audio tracks is not allowed */
508                        AudioTrack(const AudioTrack& other);
509            AudioTrack& operator = (const AudioTrack& other);
510
511    /* a small internal class to handle the callback */
512    class AudioTrackThread : public Thread
513    {
514    public:
515        AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
516
517        // Do not call Thread::requestExitAndWait() without first calling requestExit().
518        // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
519        virtual void        requestExit();
520
521                void        pause();    // suspend thread from execution at next loop boundary
522                void        resume();   // allow thread to execute, if not requested to exit
523
524    private:
525        friend class AudioTrack;
526        virtual bool        threadLoop();
527        AudioTrack& mReceiver;
528        ~AudioTrackThread();
529        Mutex               mMyLock;    // Thread::mLock is private
530        Condition           mMyCond;    // Thread::mThreadExitedCondition is private
531        bool                mPaused;    // whether thread is currently paused
532    };
533
534            // body of AudioTrackThread::threadLoop()
535            bool processAudioBuffer(const sp<AudioTrackThread>& thread);
536
537            // caller must hold lock on mLock for all _l methods
538            status_t createTrack_l(audio_stream_type_t streamType,
539                                 uint32_t sampleRate,
540                                 audio_format_t format,
541                                 size_t frameCount,
542                                 audio_output_flags_t flags,
543                                 const sp<IMemory>& sharedBuffer,
544                                 audio_io_handle_t output);
545
546            // can only be called when !mActive
547            void flush_l();
548
549            status_t setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
550            audio_io_handle_t getOutput_l();
551            status_t restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart);
552            bool stopped_l() const { return !mActive; }
553
554    sp<IAudioTrack>         mAudioTrack;
555    sp<IMemory>             mCblkMemory;
556    sp<AudioTrackThread>    mAudioTrackThread;
557
558    float                   mVolume[2];
559    float                   mSendLevel;
560    uint32_t                mSampleRate;
561    size_t                  mFrameCount;            // corresponds to current IAudioTrack
562    size_t                  mReqFrameCount;         // frame count to request the next time a new
563                                                    // IAudioTrack is needed
564
565    audio_track_cblk_t*     mCblk;                  // re-load after mLock.unlock()
566
567            // Starting address of buffers in shared memory.  If there is a shared buffer, mBuffers
568            // is the value of pointer() for the shared buffer, otherwise mBuffers points
569            // immediately after the control block.  This address is for the mapping within client
570            // address space.  AudioFlinger::TrackBase::mBuffer is for the server address space.
571    void*                   mBuffers;
572
573    audio_format_t          mFormat;                // as requested by client, not forced to 16-bit
574    audio_stream_type_t     mStreamType;
575    uint32_t                mChannelCount;
576    audio_channel_mask_t    mChannelMask;
577
578                // mFrameSize is equal to mFrameSizeAF for non-PCM or 16-bit PCM data.
579                // For 8-bit PCM data, mFrameSizeAF is
580                // twice as large because data is expanded to 16-bit before being stored in buffer.
581    size_t                  mFrameSize;             // app-level frame size
582    size_t                  mFrameSizeAF;           // AudioFlinger frame size
583
584    status_t                mStatus;
585    uint32_t                mLatency;
586
587    bool                    mActive;                // protected by mLock
588
589    callback_t              mCbf;                   // callback handler for events, or NULL
590    void*                   mUserData;              // for client callback handler
591
592    // for notification APIs
593    uint32_t                mNotificationFramesReq; // requested number of frames between each
594                                                    // notification callback
595    uint32_t                mNotificationFramesAct; // actual number of frames between each
596                                                    // notification callback
597    sp<IMemory>             mSharedBuffer;
598    int                     mLoopCount;
599    uint32_t                mRemainingFrames;
600    uint32_t                mMarkerPosition;        // in wrapping (overflow) frame units
601    bool                    mMarkerReached;
602    uint32_t                mNewPosition;           // in frames
603    uint32_t                mUpdatePeriod;          // in frames
604
605    bool                    mFlushed; // FIXME will be made obsolete by making flush() synchronous
606    audio_output_flags_t    mFlags;
607    int                     mSessionId;
608    int                     mAuxEffectId;
609
610    // When locking both mLock and mCblk->lock, must lock in this order to avoid deadlock:
611    //      1. mLock
612    //      2. mCblk->lock
613    // It is OK to lock only mCblk->lock.
614    mutable Mutex           mLock;
615
616    bool                    mIsTimed;
617    int                     mPreviousPriority;          // before start()
618    SchedPolicy             mPreviousSchedulingGroup;
619    AudioTrackClientProxy*  mProxy;
620};
621
622class TimedAudioTrack : public AudioTrack
623{
624public:
625    TimedAudioTrack();
626
627    /* allocate a shared memory buffer that can be passed to queueTimedBuffer */
628    status_t allocateTimedBuffer(size_t size, sp<IMemory>* buffer);
629
630    /* queue a buffer obtained via allocateTimedBuffer for playback at the
631       given timestamp.  PTS units are microseconds on the media time timeline.
632       The media time transform (set with setMediaTimeTransform) set by the
633       audio producer will handle converting from media time to local time
634       (perhaps going through the common time timeline in the case of
635       synchronized multiroom audio case) */
636    status_t queueTimedBuffer(const sp<IMemory>& buffer, int64_t pts);
637
638    /* define a transform between media time and either common time or
639       local time */
640    enum TargetTimeline {LOCAL_TIME, COMMON_TIME};
641    status_t setMediaTimeTransform(const LinearTransform& xform,
642                                   TargetTimeline target);
643};
644
645}; // namespace android
646
647#endif // ANDROID_AUDIOTRACK_H
648