AudioTrack.h revision 2fc14730e4697a6f456b4631549c9981f6b0b115
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 <cutils/sched_policy.h>
21#include <media/AudioSystem.h>
22#include <media/IAudioTrack.h>
23#include <utils/threads.h>
24
25namespace android {
26
27// ----------------------------------------------------------------------------
28
29class audio_track_cblk_t;
30class AudioTrackClientProxy;
31class StaticAudioTrackClientProxy;
32
33// ----------------------------------------------------------------------------
34
35class AudioTrack : public RefBase
36{
37public:
38    enum channel_index {
39        MONO   = 0,
40        LEFT   = 0,
41        RIGHT  = 1
42    };
43
44    /* Events used by AudioTrack callback function (callback_t).
45     * Keep in sync with frameworks/base/media/java/android/media/AudioTrack.java NATIVE_EVENT_*.
46     */
47    enum event_type {
48        EVENT_MORE_DATA = 0,        // Request to write more data to buffer.
49                                    // If this event is delivered but the callback handler
50                                    // does not want to write more data, the handler must explicitly
51                                    // ignore the event by setting frameCount to zero.
52        EVENT_UNDERRUN = 1,         // Buffer underrun occurred.
53        EVENT_LOOP_END = 2,         // Sample loop end was reached; playback restarted from
54                                    // loop start if loop count was not 0.
55        EVENT_MARKER = 3,           // Playback head is at the specified marker position
56                                    // (See setMarkerPosition()).
57        EVENT_NEW_POS = 4,          // Playback head is at a new position
58                                    // (See setPositionUpdatePeriod()).
59        EVENT_BUFFER_END = 5,       // Playback head is at the end of the buffer.
60                                    // Not currently used by android.media.AudioTrack.
61        EVENT_NEW_IAUDIOTRACK = 6,  // IAudioTrack was re-created, either due to re-routing and
62                                    // voluntary invalidation by mediaserver, or mediaserver crash.
63        EVENT_STREAM_END = 7,       // Sent after all the buffers queued in AF and HW are played
64                                    // back (after stop is called)
65    };
66
67    /* Client should declare Buffer on the stack and pass address to obtainBuffer()
68     * and releaseBuffer().  See also callback_t for EVENT_MORE_DATA.
69     */
70
71    class Buffer
72    {
73    public:
74        // FIXME use m prefix
75        size_t      frameCount;   // number of sample frames corresponding to size;
76                                  // on input it is the number of frames desired,
77                                  // on output is the number of frames actually filled
78                                  // (currently ignored, but will make the primary field in future)
79
80        size_t      size;         // input/output in bytes == frameCount * frameSize
81                                  // on output is the number of bytes actually filled
82                                  // FIXME this is redundant with respect to frameCount,
83                                  // and TRANSFER_OBTAIN mode is broken for 8-bit data
84                                  // since we don't define the frame format
85
86        union {
87            void*       raw;
88            short*      i16;      // signed 16-bit
89            int8_t*     i8;       // unsigned 8-bit, offset by 0x80
90        };
91    };
92
93    /* As a convenience, if a callback is supplied, a handler thread
94     * is automatically created with the appropriate priority. This thread
95     * invokes the callback when a new buffer becomes available or various conditions occur.
96     * Parameters:
97     *
98     * event:   type of event notified (see enum AudioTrack::event_type).
99     * user:    Pointer to context for use by the callback receiver.
100     * info:    Pointer to optional parameter according to event type:
101     *          - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write
102     *            more bytes than indicated by 'size' field and update 'size' if fewer bytes are
103     *            written.
104     *          - EVENT_UNDERRUN: unused.
105     *          - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
106     *          - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames.
107     *          - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames.
108     *          - EVENT_BUFFER_END: unused.
109     *          - EVENT_NEW_IAUDIOTRACK: unused.
110     */
111
112    typedef void (*callback_t)(int event, void* user, void *info);
113
114    /* Returns the minimum frame count required for the successful creation of
115     * an AudioTrack object.
116     * Returned status (from utils/Errors.h) can be:
117     *  - NO_ERROR: successful operation
118     *  - NO_INIT: audio server or audio hardware not initialized
119     *  - BAD_VALUE: unsupported configuration
120     */
121
122    static status_t getMinFrameCount(size_t* frameCount,
123                                     audio_stream_type_t streamType,
124                                     uint32_t sampleRate);
125
126    /* How data is transferred to AudioTrack
127     */
128    enum transfer_type {
129        TRANSFER_DEFAULT,   // not specified explicitly; determine from the other parameters
130        TRANSFER_CALLBACK,  // callback EVENT_MORE_DATA
131        TRANSFER_OBTAIN,    // FIXME deprecated: call obtainBuffer() and releaseBuffer()
132        TRANSFER_SYNC,      // synchronous write()
133        TRANSFER_SHARED,    // shared memory
134    };
135
136    /* Constructs an uninitialized AudioTrack. No connection with
137     * AudioFlinger takes place.  Use set() after this.
138     */
139                        AudioTrack();
140
141    /* Creates an AudioTrack object and registers it with AudioFlinger.
142     * Once created, the track needs to be started before it can be used.
143     * Unspecified values are set to appropriate default values.
144     * With this constructor, the track is configured for streaming mode.
145     * Data to be rendered is supplied by write() or by the callback EVENT_MORE_DATA.
146     * Intermixing a combination of write() and non-ignored EVENT_MORE_DATA is not allowed.
147     *
148     * Parameters:
149     *
150     * streamType:         Select the type of audio stream this track is attached to
151     *                     (e.g. AUDIO_STREAM_MUSIC).
152     * sampleRate:         Data source sampling rate in Hz.
153     * format:             Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed
154     *                     16 bits per sample).
155     * channelMask:        Channel mask.
156     * frameCount:         Minimum size of track PCM buffer in frames. This defines the
157     *                     application's contribution to the
158     *                     latency of the track. The actual size selected by the AudioTrack could be
159     *                     larger if the requested size is not compatible with current audio HAL
160     *                     configuration.  Zero means to use a default value.
161     * flags:              See comments on audio_output_flags_t in <system/audio.h>.
162     * cbf:                Callback function. If not null, this function is called periodically
163     *                     to provide new data and inform of marker, position updates, etc.
164     * user:               Context for use by the callback receiver.
165     * notificationFrames: The callback function is called each time notificationFrames PCM
166     *                     frames have been consumed from track input buffer.
167     *                     This is expressed in units of frames at the initial source sample rate.
168     * sessionId:          Specific session ID, or zero to use default.
169     * transferType:       How data is transferred to AudioTrack.
170     * threadCanCallJava:  Not present in parameter list, and so is fixed at false.
171     */
172
173                        AudioTrack( audio_stream_type_t streamType,
174                                    uint32_t sampleRate,
175                                    audio_format_t format,
176                                    audio_channel_mask_t,
177                                    int frameCount       = 0,
178                                    audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
179                                    callback_t cbf       = NULL,
180                                    void* user           = NULL,
181                                    int notificationFrames = 0,
182                                    int sessionId        = 0,
183                                    transfer_type transferType = TRANSFER_DEFAULT,
184                                    const audio_offload_info_t *offloadInfo = NULL);
185
186    /* Creates an audio track and registers it with AudioFlinger.
187     * With this constructor, the track is configured for static buffer mode.
188     * The format must not be 8-bit linear PCM.
189     * Data to be rendered is passed in a shared memory buffer
190     * identified by the argument sharedBuffer, which must be non-0.
191     * The memory should be initialized to the desired data before calling start().
192     * The write() method is not supported in this case.
193     * It is recommended to pass a callback function to be notified of playback end by an
194     * EVENT_UNDERRUN event.
195     */
196
197                        AudioTrack( audio_stream_type_t streamType,
198                                    uint32_t sampleRate,
199                                    audio_format_t format,
200                                    audio_channel_mask_t channelMask,
201                                    const sp<IMemory>& sharedBuffer,
202                                    audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
203                                    callback_t cbf      = NULL,
204                                    void* user          = NULL,
205                                    int notificationFrames = 0,
206                                    int sessionId       = 0,
207                                    transfer_type transferType = TRANSFER_DEFAULT,
208                                    const audio_offload_info_t *offloadInfo = NULL);
209
210    /* Terminates the AudioTrack and unregisters it from AudioFlinger.
211     * Also destroys all resources associated with the AudioTrack.
212     */
213protected:
214                        virtual ~AudioTrack();
215public:
216
217    /* Initialize an AudioTrack that was created using the AudioTrack() constructor.
218     * Don't call set() more than once, or after the AudioTrack() constructors that take parameters.
219     * Returned status (from utils/Errors.h) can be:
220     *  - NO_ERROR: successful initialization
221     *  - INVALID_OPERATION: AudioTrack is already initialized
222     *  - BAD_VALUE: invalid parameter (channelMask, format, sampleRate...)
223     *  - NO_INIT: audio server or audio hardware not initialized
224     * If sharedBuffer is non-0, the frameCount parameter is ignored and
225     * replaced by the shared buffer's total allocated size in frame units.
226     *
227     * Parameters not listed in the AudioTrack constructors above:
228     *
229     * threadCanCallJava:  Whether callbacks are made from an attached thread and thus can call JNI.
230     */
231            status_t    set(audio_stream_type_t streamType,
232                            uint32_t sampleRate,
233                            audio_format_t format,
234                            audio_channel_mask_t channelMask,
235                            int frameCount      = 0,
236                            audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
237                            callback_t cbf      = NULL,
238                            void* user          = NULL,
239                            int notificationFrames = 0,
240                            const sp<IMemory>& sharedBuffer = 0,
241                            bool threadCanCallJava = false,
242                            int sessionId       = 0,
243                            transfer_type transferType = TRANSFER_DEFAULT,
244                            const audio_offload_info_t *offloadInfo = NULL);
245
246    /* Result of constructing the AudioTrack. This must be checked
247     * before using any AudioTrack API (except for set()), because using
248     * an uninitialized AudioTrack produces undefined results.
249     * See set() method above for possible return codes.
250     */
251            status_t    initCheck() const   { return mStatus; }
252
253    /* Returns this track's estimated latency in milliseconds.
254     * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
255     * and audio hardware driver.
256     */
257            uint32_t    latency() const     { return mLatency; }
258
259    /* getters, see constructors and set() */
260
261            audio_stream_type_t streamType() const { return mStreamType; }
262            audio_format_t format() const   { return mFormat; }
263
264    /* Return frame size in bytes, which for linear PCM is
265     * channelCount * (bit depth per channel / 8).
266     * channelCount is determined from channelMask, and bit depth comes from format.
267     * For non-linear formats, the frame size is typically 1 byte.
268     */
269            size_t      frameSize() const   { return mFrameSize; }
270
271            uint32_t    channelCount() const { return mChannelCount; }
272            uint32_t    frameCount() const  { return mFrameCount; }
273
274    /* Return the static buffer specified in constructor or set(), or 0 for streaming mode */
275            sp<IMemory> sharedBuffer() const { return mSharedBuffer; }
276
277    /* After it's created the track is not active. Call start() to
278     * make it active. If set, the callback will start being called.
279     * If the track was previously paused, volume is ramped up over the first mix buffer.
280     */
281            status_t        start();
282
283    /* Stop a track.
284     * In static buffer mode, the track is stopped immediately.
285     * In streaming mode, the callback will cease being called.  Note that obtainBuffer() still
286     * works and will fill up buffers until the pool is exhausted, and then will return WOULD_BLOCK.
287     * In streaming mode the stop does not occur immediately: any data remaining in the buffer
288     * is first drained, mixed, and output, and only then is the track marked as stopped.
289     */
290            void        stop();
291            bool        stopped() const;
292
293    /* Flush a stopped or paused track. All previously buffered data is discarded immediately.
294     * This has the effect of draining the buffers without mixing or output.
295     * Flush is intended for streaming mode, for example before switching to non-contiguous content.
296     * This function is a no-op if the track is not stopped or paused, or uses a static buffer.
297     */
298            void        flush();
299
300    /* Pause a track. After pause, the callback will cease being called and
301     * obtainBuffer returns WOULD_BLOCK. Note that obtainBuffer() still works
302     * and will fill up buffers until the pool is exhausted.
303     * Volume is ramped down over the next mix buffer following the pause request,
304     * and then the track is marked as paused.  It can be resumed with ramp up by start().
305     */
306            void        pause();
307
308    /* Set volume for this track, mostly used for games' sound effects
309     * left and right volumes. Levels must be >= 0.0 and <= 1.0.
310     * This is the older API.  New applications should use setVolume(float) when possible.
311     */
312            status_t    setVolume(float left, float right);
313
314    /* Set volume for all channels.  This is the preferred API for new applications,
315     * especially for multi-channel content.
316     */
317            status_t    setVolume(float volume);
318
319    /* Set the send level for this track. An auxiliary effect should be attached
320     * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0.
321     */
322            status_t    setAuxEffectSendLevel(float level);
323            void        getAuxEffectSendLevel(float* level) const;
324
325    /* Set source sample rate for this track in Hz, mostly used for games' sound effects
326     */
327            status_t    setSampleRate(uint32_t sampleRate);
328
329    /* Return current source sample rate in Hz, or 0 if unknown */
330            uint32_t    getSampleRate() const;
331
332    /* Enables looping and sets the start and end points of looping.
333     * Only supported for static buffer mode.
334     *
335     * Parameters:
336     *
337     * loopStart:   loop start in frames relative to start of buffer.
338     * loopEnd:     loop end in frames relative to start of buffer.
339     * loopCount:   number of loops to execute. Calling setLoop() with loopCount == 0 cancels any
340     *              pending or active loop. loopCount == -1 means infinite looping.
341     *
342     * For proper operation the following condition must be respected:
343     *      loopCount != 0 implies 0 <= loopStart < loopEnd <= frameCount().
344     *
345     * If the loop period (loopEnd - loopStart) is too small for the implementation to support,
346     * setLoop() will return BAD_VALUE.  loopCount must be >= -1.
347     *
348     */
349            status_t    setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
350
351    /* Sets marker position. When playback reaches the number of frames specified, a callback with
352     * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker
353     * notification callback.  To set a marker at a position which would compute as 0,
354     * a workaround is to the set the marker at a nearby position such as ~0 or 1.
355     * If the AudioTrack has been opened with no callback function associated, the operation will
356     * fail.
357     *
358     * Parameters:
359     *
360     * marker:   marker position expressed in wrapping (overflow) frame units,
361     *           like the return value of getPosition().
362     *
363     * Returned status (from utils/Errors.h) can be:
364     *  - NO_ERROR: successful operation
365     *  - INVALID_OPERATION: the AudioTrack has no callback installed.
366     */
367            status_t    setMarkerPosition(uint32_t marker);
368            status_t    getMarkerPosition(uint32_t *marker) const;
369
370    /* Sets position update period. Every time the number of frames specified has been played,
371     * a callback with event type EVENT_NEW_POS is called.
372     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
373     * callback.
374     * If the AudioTrack has been opened with no callback function associated, the operation will
375     * fail.
376     * Extremely small values may be rounded up to a value the implementation can support.
377     *
378     * Parameters:
379     *
380     * updatePeriod:  position update notification period expressed in frames.
381     *
382     * Returned status (from utils/Errors.h) can be:
383     *  - NO_ERROR: successful operation
384     *  - INVALID_OPERATION: the AudioTrack has no callback installed.
385     */
386            status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
387            status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
388
389    /* Sets playback head position.
390     * Only supported for static buffer mode.
391     *
392     * Parameters:
393     *
394     * position:  New playback head position in frames relative to start of buffer.
395     *            0 <= position <= frameCount().  Note that end of buffer is permitted,
396     *            but will result in an immediate underrun if started.
397     *
398     * Returned status (from utils/Errors.h) can be:
399     *  - NO_ERROR: successful operation
400     *  - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode.
401     *  - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack
402     *               buffer
403     */
404            status_t    setPosition(uint32_t position);
405
406    /* Return the total number of frames played since playback start.
407     * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
408     * It is reset to zero by flush(), reload(), and stop().
409     *
410     * Parameters:
411     *
412     *  position:  Address where to return play head position.
413     *
414     * Returned status (from utils/Errors.h) can be:
415     *  - NO_ERROR: successful operation
416     *  - BAD_VALUE:  position is NULL
417     */
418            status_t    getPosition(uint32_t *position) const;
419
420    /* For static buffer mode only, this returns the current playback position in frames
421     * relative to start of buffer.  It is analogous to the position units used by
422     * setLoop() and setPosition().  After underrun, the position will be at end of buffer.
423     */
424            status_t    getBufferPosition(uint32_t *position);
425
426    /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
427     * rewriting the buffer before restarting playback after a stop.
428     * This method must be called with the AudioTrack in paused or stopped state.
429     * Not allowed in streaming mode.
430     *
431     * Returned status (from utils/Errors.h) can be:
432     *  - NO_ERROR: successful operation
433     *  - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode.
434     */
435            status_t    reload();
436
437    /* Returns a handle on the audio output used by this AudioTrack.
438     *
439     * Parameters:
440     *  none.
441     *
442     * Returned value:
443     *  handle on audio hardware output
444     */
445            audio_io_handle_t    getOutput();
446
447    /* Returns the unique session ID associated with this track.
448     *
449     * Parameters:
450     *  none.
451     *
452     * Returned value:
453     *  AudioTrack session ID.
454     */
455            int    getSessionId() const { return mSessionId; }
456
457    /* Attach track auxiliary output to specified effect. Use effectId = 0
458     * to detach track from effect.
459     *
460     * Parameters:
461     *
462     * effectId:  effectId obtained from AudioEffect::id().
463     *
464     * Returned status (from utils/Errors.h) can be:
465     *  - NO_ERROR: successful operation
466     *  - INVALID_OPERATION: the effect is not an auxiliary effect.
467     *  - BAD_VALUE: The specified effect ID is invalid
468     */
469            status_t    attachAuxEffect(int effectId);
470
471    /* Obtains a buffer of up to "audioBuffer->frameCount" empty slots for frames.
472     * After filling these slots with data, the caller should release them with releaseBuffer().
473     * If the track buffer is not full, obtainBuffer() returns as many contiguous
474     * [empty slots for] frames as are available immediately.
475     * If the track buffer is full and track is stopped, obtainBuffer() returns WOULD_BLOCK
476     * regardless of the value of waitCount.
477     * If the track buffer is full and track is not stopped, obtainBuffer() blocks with a
478     * maximum timeout based on waitCount; see chart below.
479     * Buffers will be returned until the pool
480     * is exhausted, at which point obtainBuffer() will either block
481     * or return WOULD_BLOCK depending on the value of the "waitCount"
482     * parameter.
483     * Each sample is 16-bit signed PCM.
484     *
485     * obtainBuffer() and releaseBuffer() are deprecated for direct use by applications,
486     * which should use write() or callback EVENT_MORE_DATA instead.
487     *
488     * Interpretation of waitCount:
489     *  +n  limits wait time to n * WAIT_PERIOD_MS,
490     *  -1  causes an (almost) infinite wait time,
491     *   0  non-blocking.
492     *
493     * Buffer fields
494     * On entry:
495     *  frameCount  number of frames requested
496     * After error return:
497     *  frameCount  0
498     *  size        0
499     *  raw         undefined
500     * After successful return:
501     *  frameCount  actual number of frames available, <= number requested
502     *  size        actual number of bytes available
503     *  raw         pointer to the buffer
504     */
505
506    /* FIXME Deprecated public API for TRANSFER_OBTAIN mode */
507            status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
508                                __attribute__((__deprecated__));
509
510private:
511    /* If nonContig is non-NULL, it is an output parameter that will be set to the number of
512     * additional non-contiguous frames that are available immediately.
513     * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(),
514     * in case the requested amount of frames is in two or more non-contiguous regions.
515     * FIXME requested and elapsed are both relative times.  Consider changing to absolute time.
516     */
517            status_t    obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
518                                     struct timespec *elapsed = NULL, size_t *nonContig = NULL);
519public:
520
521//EL_FIXME to be reconciled with new obtainBuffer() return codes and control block proxy
522//            enum {
523//            NO_MORE_BUFFERS = 0x80000001,   // same name in AudioFlinger.h, ok to be different value
524//            TEAR_DOWN       = 0x80000002,
525//            STOPPED = 1,
526//            STREAM_END_WAIT,
527//            STREAM_END
528//        };
529
530    /* Release a filled buffer of "audioBuffer->frameCount" frames for AudioFlinger to process. */
531    // FIXME make private when obtainBuffer() for TRANSFER_OBTAIN is removed
532            void        releaseBuffer(Buffer* audioBuffer);
533
534    /* As a convenience we provide a write() interface to the audio buffer.
535     * Input parameter 'size' is in byte units.
536     * This is implemented on top of obtainBuffer/releaseBuffer. For best
537     * performance use callbacks. Returns actual number of bytes written >= 0,
538     * or one of the following negative status codes:
539     *      INVALID_OPERATION   AudioTrack is configured for static buffer or streaming mode
540     *      BAD_VALUE           size is invalid
541     *      WOULD_BLOCK         when obtainBuffer() returns same, or
542     *                          AudioTrack was stopped during the write
543     *      or any other error code returned by IAudioTrack::start() or restoreTrack_l().
544     */
545            ssize_t     write(const void* buffer, size_t size);
546
547    /*
548     * Dumps the state of an audio track.
549     */
550            status_t    dump(int fd, const Vector<String16>& args) const;
551
552    /*
553     * Return the total number of frames which AudioFlinger desired but were unavailable,
554     * and thus which resulted in an underrun.  Reset to zero by stop().
555     */
556            uint32_t    getUnderrunFrames() const;
557
558    /* Get the flags */
559            audio_output_flags_t getFlags() const { return mFlags; }
560
561    /* Set parameters - only possible when using direct output */
562            status_t    setParameters(const String8& keyValuePairs);
563
564    /* Get parameters */
565            String8     getParameters(const String8& keys);
566
567protected:
568    /* copying audio tracks is not allowed */
569                        AudioTrack(const AudioTrack& other);
570            AudioTrack& operator = (const AudioTrack& other);
571
572    /* a small internal class to handle the callback */
573    class AudioTrackThread : public Thread
574    {
575    public:
576        AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
577
578        // Do not call Thread::requestExitAndWait() without first calling requestExit().
579        // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
580        virtual void        requestExit();
581
582                void        pause();    // suspend thread from execution at next loop boundary
583                void        resume();   // allow thread to execute, if not requested to exit
584                void        pauseConditional();
585                                        // like pause(), but only if prior resume() wasn't latched
586
587    private:
588        friend class AudioTrack;
589        virtual bool        threadLoop();
590        AudioTrack&         mReceiver;
591        virtual ~AudioTrackThread();
592        Mutex               mMyLock;    // Thread::mLock is private
593        Condition           mMyCond;    // Thread::mThreadExitedCondition is private
594        bool                mPaused;    // whether thread is currently paused
595        bool                mResumeLatch;   // whether next pauseConditional() will be a nop
596    };
597
598            // body of AudioTrackThread::threadLoop()
599            // returns the maximum amount of time before we would like to run again, where:
600            //      0           immediately
601            //      > 0         no later than this many nanoseconds from now
602            //      NS_WHENEVER still active but no particular deadline
603            //      NS_INACTIVE inactive so don't run again until re-started
604            //      NS_NEVER    never again
605            static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
606            nsecs_t processAudioBuffer(const sp<AudioTrackThread>& thread);
607            status_t processStreamEnd(int32_t waitCount);
608
609
610            // caller must hold lock on mLock for all _l methods
611
612            status_t createTrack_l(audio_stream_type_t streamType,
613                                 uint32_t sampleRate,
614                                 audio_format_t format,
615                                 size_t frameCount,
616                                 audio_output_flags_t flags,
617                                 const sp<IMemory>& sharedBuffer,
618                                 audio_io_handle_t output,
619                                 size_t epoch);
620
621            // can only be called when mState != STATE_ACTIVE
622            void flush_l();
623
624            void setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
625            audio_io_handle_t getOutput_l();
626
627            // FIXME enum is faster than strcmp() for parameter 'from'
628            status_t restoreTrack_l(const char *from);
629
630            bool     isOffloaded() const
631                { return (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; }
632
633    // may be changed if IAudioTrack is re-created
634    sp<IAudioTrack>         mAudioTrack;
635    sp<IMemory>             mCblkMemory;
636    audio_track_cblk_t*     mCblk;                  // re-load after mLock.unlock()
637
638    sp<AudioTrackThread>    mAudioTrackThread;
639    float                   mVolume[2];
640    float                   mSendLevel;
641    uint32_t                mSampleRate;
642    size_t                  mFrameCount;            // corresponds to current IAudioTrack
643    size_t                  mReqFrameCount;         // frame count to request the next time a new
644                                                    // IAudioTrack is needed
645
646
647    // constant after constructor or set()
648    audio_format_t          mFormat;                // as requested by client, not forced to 16-bit
649    audio_stream_type_t     mStreamType;
650    uint32_t                mChannelCount;
651    audio_channel_mask_t    mChannelMask;
652    transfer_type           mTransfer;
653
654    // mFrameSize is equal to mFrameSizeAF for non-PCM or 16-bit PCM data.  For 8-bit PCM data, it's
655    // twice as large as mFrameSize because data is expanded to 16-bit before it's stored in buffer.
656    size_t                  mFrameSize;             // app-level frame size
657    size_t                  mFrameSizeAF;           // AudioFlinger frame size
658
659    status_t                mStatus;
660
661    // can change dynamically when IAudioTrack invalidated
662    uint32_t                mLatency;               // in ms
663
664    // Indicates the current track state.  Protected by mLock.
665    enum State {
666        STATE_ACTIVE,
667        STATE_STOPPED,
668        STATE_PAUSED,
669        STATE_PAUSED_STOPPING,
670        STATE_FLUSHED,
671        STATE_STOPPING,
672    }                       mState;
673
674    // for client callback handler
675    callback_t              mCbf;                   // callback handler for events, or NULL
676    void*                   mUserData;
677
678    // for notification APIs
679    uint32_t                mNotificationFramesReq; // requested number of frames between each
680                                                    // notification callback,
681                                                    // at initial source sample rate
682    uint32_t                mNotificationFramesAct; // actual number of frames between each
683                                                    // notification callback,
684                                                    // at initial source sample rate
685    bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
686                                                    // mRemainingFrames and mRetryOnPartialBuffer
687
688    // These are private to processAudioBuffer(), and are not protected by a lock
689    uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
690    bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
691    uint32_t                mObservedSequence;      // last observed value of mSequence
692
693    sp<IMemory>             mSharedBuffer;
694    uint32_t                mLoopPeriod;            // in frames, zero means looping is disabled
695    uint32_t                mMarkerPosition;        // in wrapping (overflow) frame units
696    bool                    mMarkerReached;
697    uint32_t                mNewPosition;           // in frames
698    uint32_t                mUpdatePeriod;          // in frames, zero means no EVENT_NEW_POS
699
700    audio_output_flags_t    mFlags;
701    int                     mSessionId;
702    int                     mAuxEffectId;
703
704    mutable Mutex           mLock;
705
706    bool                    mIsTimed;
707    int                     mPreviousPriority;          // before start()
708    SchedPolicy             mPreviousSchedulingGroup;
709    bool                    mAwaitBoost;    // thread should wait for priority boost before running
710
711    // The proxy should only be referenced while a lock is held because the proxy isn't
712    // multi-thread safe, especially the SingleStateQueue part of the proxy.
713    // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
714    // provided that the caller also holds an extra reference to the proxy and shared memory to keep
715    // them around in case they are replaced during the obtainBuffer().
716    sp<StaticAudioTrackClientProxy> mStaticProxy;   // for type safety only
717    sp<AudioTrackClientProxy>       mProxy;         // primary owner of the memory
718
719    bool                    mInUnderrun;            // whether track is currently in underrun state
720    String8                 mName;                  // server's name for this IAudioTrack
721
722private:
723    class DeathNotifier : public IBinder::DeathRecipient {
724    public:
725        DeathNotifier(AudioTrack* audioTrack) : mAudioTrack(audioTrack) { }
726    protected:
727        virtual void        binderDied(const wp<IBinder>& who);
728    private:
729        const wp<AudioTrack> mAudioTrack;
730    };
731
732    sp<DeathNotifier>       mDeathNotifier;
733    uint32_t                mSequence;              // incremented for each new IAudioTrack attempt
734    audio_io_handle_t       mOutput;                // cached output io handle
735};
736
737class TimedAudioTrack : public AudioTrack
738{
739public:
740    TimedAudioTrack();
741
742    /* allocate a shared memory buffer that can be passed to queueTimedBuffer */
743    status_t allocateTimedBuffer(size_t size, sp<IMemory>* buffer);
744
745    /* queue a buffer obtained via allocateTimedBuffer for playback at the
746       given timestamp.  PTS units are microseconds on the media time timeline.
747       The media time transform (set with setMediaTimeTransform) set by the
748       audio producer will handle converting from media time to local time
749       (perhaps going through the common time timeline in the case of
750       synchronized multiroom audio case) */
751    status_t queueTimedBuffer(const sp<IMemory>& buffer, int64_t pts);
752
753    /* define a transform between media time and either common time or
754       local time */
755    enum TargetTimeline {LOCAL_TIME, COMMON_TIME};
756    status_t setMediaTimeTransform(const LinearTransform& xform,
757                                   TargetTimeline target);
758};
759
760}; // namespace android
761
762#endif // ANDROID_AUDIOTRACK_H
763