Home | History | Annotate | Download | only in media
      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 <utils/threads.h>
     32 
     33 namespace android {
     34 
     35 // ----------------------------------------------------------------------------
     36 
     37 class audio_track_cblk_t;
     38 
     39 // ----------------------------------------------------------------------------
     40 
     41 class AudioTrack
     42 {
     43 public:
     44     enum channel_index {
     45         MONO   = 0,
     46         LEFT   = 0,
     47         RIGHT  = 1
     48     };
     49 
     50     /* Events used by AudioTrack callback function (audio_track_cblk_t).
     51      */
     52     enum event_type {
     53         EVENT_MORE_DATA = 0,        // Request to write more data to PCM buffer.
     54         EVENT_UNDERRUN = 1,         // PCM buffer underrun occured.
     55         EVENT_LOOP_END = 2,         // Sample loop end was reached; playback restarted from loop start if loop count was not 0.
     56         EVENT_MARKER = 3,           // Playback head is at the specified marker position (See setMarkerPosition()).
     57         EVENT_NEW_POS = 4,          // Playback head is at a new position (See setPositionUpdatePeriod()).
     58         EVENT_BUFFER_END = 5        // Playback head is at the end of the buffer.
     59     };
     60 
     61     /* Create Buffer on the stack and pass it to obtainBuffer()
     62      * and releaseBuffer().
     63      */
     64 
     65     class Buffer
     66     {
     67     public:
     68         enum {
     69             MUTE    = 0x00000001
     70         };
     71         uint32_t    flags;
     72         int         format;
     73         int         channelCount; // will be removed in the future, do not use
     74         size_t      frameCount;
     75         size_t      size;
     76         union {
     77             void*       raw;
     78             short*      i16;
     79             int8_t*     i8;
     80         };
     81     };
     82 
     83 
     84     /* As a convenience, if a callback is supplied, a handler thread
     85      * is automatically created with the appropriate priority. This thread
     86      * invokes the callback when a new buffer becomes availlable or an underrun condition occurs.
     87      * Parameters:
     88      *
     89      * event:   type of event notified (see enum AudioTrack::event_type).
     90      * user:    Pointer to context for use by the callback receiver.
     91      * info:    Pointer to optional parameter according to event type:
     92      *          - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write
     93      *          more bytes than indicated by 'size' field and update 'size' if less bytes are
     94      *          written.
     95      *          - EVENT_UNDERRUN: unused.
     96      *          - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
     97      *          - EVENT_MARKER: pointer to an uin32_t containing the marker position in frames.
     98      *          - EVENT_NEW_POS: pointer to an uin32_t containing the new position in frames.
     99      *          - EVENT_BUFFER_END: unused.
    100      */
    101 
    102     typedef void (*callback_t)(int event, void* user, void *info);
    103 
    104     /* Returns the minimum frame count required for the successful creation of
    105      * an AudioTrack object.
    106      * Returned status (from utils/Errors.h) can be:
    107      *  - NO_ERROR: successful operation
    108      *  - NO_INIT: audio server or audio hardware not initialized
    109      */
    110 
    111      static status_t getMinFrameCount(int* frameCount,
    112                                       int streamType      =-1,
    113                                       uint32_t sampleRate = 0);
    114 
    115     /* Constructs an uninitialized AudioTrack. No connection with
    116      * AudioFlinger takes place.
    117      */
    118                         AudioTrack();
    119 
    120     /* Creates an audio track and registers it with AudioFlinger.
    121      * Once created, the track needs to be started before it can be used.
    122      * Unspecified values are set to the audio hardware's current
    123      * values.
    124      *
    125      * Parameters:
    126      *
    127      * streamType:         Select the type of audio stream this track is attached to
    128      *                     (e.g. AUDIO_STREAM_MUSIC).
    129      * sampleRate:         Track sampling rate in Hz.
    130      * format:             Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed
    131      *                     16 bits per sample).
    132      * channelMask:        Channel mask: see audio_channels_t.
    133      * frameCount:         Minimum size of track PCM buffer in frames. This defines the
    134      *                     latency of the track. The actual size selected by the AudioTrack could be
    135      *                     larger if the requested size is not compatible with current audio HAL
    136      *                     latency.
    137      * flags:              Reserved for future use.
    138      * cbf:                Callback function. If not null, this function is called periodically
    139      *                     to request new PCM data.
    140      * notificationFrames: The callback function is called each time notificationFrames PCM
    141      *                     frames have been comsumed from track input buffer.
    142      * user                Context for use by the callback receiver.
    143      */
    144 
    145                         AudioTrack( int streamType,
    146                                     uint32_t sampleRate  = 0,
    147                                     int format           = 0,
    148                                     int channelMask      = 0,
    149                                     int frameCount       = 0,
    150                                     uint32_t flags       = 0,
    151                                     callback_t cbf       = 0,
    152                                     void* user           = 0,
    153                                     int notificationFrames = 0,
    154                                     int sessionId = 0);
    155 
    156     /* Creates an audio track and registers it with AudioFlinger. With this constructor,
    157      * The PCM data to be rendered by AudioTrack is passed in a shared memory buffer
    158      * identified by the argument sharedBuffer. This prototype is for static buffer playback.
    159      * PCM data must be present into memory before the AudioTrack is started.
    160      * The Write() and Flush() methods are not supported in this case.
    161      * It is recommented to pass a callback function to be notified of playback end by an
    162      * EVENT_UNDERRUN event.
    163      */
    164 
    165                         AudioTrack( int streamType,
    166                                     uint32_t sampleRate = 0,
    167                                     int format          = 0,
    168                                     int channelMask     = 0,
    169                                     const sp<IMemory>& sharedBuffer = 0,
    170                                     uint32_t flags      = 0,
    171                                     callback_t cbf      = 0,
    172                                     void* user          = 0,
    173                                     int notificationFrames = 0,
    174                                     int sessionId = 0);
    175 
    176     /* Terminates the AudioTrack and unregisters it from AudioFlinger.
    177      * Also destroys all resources assotiated with the AudioTrack.
    178      */
    179                         ~AudioTrack();
    180 
    181 
    182     /* Initialize an uninitialized AudioTrack.
    183      * Returned status (from utils/Errors.h) can be:
    184      *  - NO_ERROR: successful intialization
    185      *  - INVALID_OPERATION: AudioTrack is already intitialized
    186      *  - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
    187      *  - NO_INIT: audio server or audio hardware not initialized
    188      * */
    189             status_t    set(int streamType      =-1,
    190                             uint32_t sampleRate = 0,
    191                             int format          = 0,
    192                             int channelMask     = 0,
    193                             int frameCount      = 0,
    194                             uint32_t flags      = 0,
    195                             callback_t cbf      = 0,
    196                             void* user          = 0,
    197                             int notificationFrames = 0,
    198                             const sp<IMemory>& sharedBuffer = 0,
    199                             bool threadCanCallJava = false,
    200                             int sessionId = 0);
    201 
    202 
    203     /* Result of constructing the AudioTrack. This must be checked
    204      * before using any AudioTrack API (except for set()), using
    205      * an uninitialized AudioTrack produces undefined results.
    206      * See set() method above for possible return codes.
    207      */
    208             status_t    initCheck() const;
    209 
    210     /* Returns this track's latency in milliseconds.
    211      * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
    212      * and audio hardware driver.
    213      */
    214             uint32_t     latency() const;
    215 
    216     /* getters, see constructor */
    217 
    218             int         streamType() const;
    219             int         format() const;
    220             int         channelCount() const;
    221             uint32_t    frameCount() const;
    222             int         frameSize() const;
    223             sp<IMemory>& sharedBuffer();
    224 
    225 
    226     /* After it's created the track is not active. Call start() to
    227      * make it active. If set, the callback will start being called.
    228      */
    229             void        start();
    230 
    231     /* Stop a track. If set, the callback will cease being called and
    232      * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
    233      * and will fill up buffers until the pool is exhausted.
    234      */
    235             void        stop();
    236             bool        stopped() const;
    237 
    238     /* flush a stopped track. All pending buffers are discarded.
    239      * This function has no effect if the track is not stoped.
    240      */
    241             void        flush();
    242 
    243     /* Pause a track. If set, the callback will cease being called and
    244      * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
    245      * and will fill up buffers until the pool is exhausted.
    246      */
    247             void        pause();
    248 
    249     /* mute or unmutes this track.
    250      * While mutted, the callback, if set, is still called.
    251      */
    252             void        mute(bool);
    253             bool        muted() const;
    254 
    255 
    256     /* set volume for this track, mostly used for games' sound effects
    257      * left and right volumes. Levels must be <= 1.0.
    258      */
    259             status_t    setVolume(float left, float right);
    260             void        getVolume(float* left, float* right);
    261 
    262     /* set the send level for this track. An auxiliary effect should be attached
    263      * to the track with attachEffect(). Level must be <= 1.0.
    264      */
    265             status_t    setAuxEffectSendLevel(float level);
    266             void        getAuxEffectSendLevel(float* level);
    267 
    268     /* set sample rate for this track, mostly used for games' sound effects
    269      */
    270             status_t    setSampleRate(int sampleRate);
    271             uint32_t    getSampleRate();
    272 
    273     /* Enables looping and sets the start and end points of looping.
    274      *
    275      * Parameters:
    276      *
    277      * loopStart:   loop start expressed as the number of PCM frames played since AudioTrack start.
    278      * loopEnd:     loop end expressed as the number of PCM frames played since AudioTrack start.
    279      * loopCount:   number of loops to execute. Calling setLoop() with loopCount == 0 cancels any pending or
    280      *          active loop. loopCount = -1 means infinite looping.
    281      *
    282      * For proper operation the following condition must be respected:
    283      *          (loopEnd-loopStart) <= framecount()
    284      */
    285             status_t    setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
    286             status_t    getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount);
    287 
    288 
    289     /* Sets marker position. When playback reaches the number of frames specified, a callback with event
    290      * type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker notification
    291      * callback.
    292      * If the AudioTrack has been opened with no callback function associated, the operation will fail.
    293      *
    294      * Parameters:
    295      *
    296      * marker:   marker position expressed in frames.
    297      *
    298      * Returned status (from utils/Errors.h) can be:
    299      *  - NO_ERROR: successful operation
    300      *  - INVALID_OPERATION: the AudioTrack has no callback installed.
    301      */
    302             status_t    setMarkerPosition(uint32_t marker);
    303             status_t    getMarkerPosition(uint32_t *marker);
    304 
    305 
    306     /* Sets position update period. Every time the number of frames specified has been played,
    307      * a callback with event type EVENT_NEW_POS is called.
    308      * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
    309      * callback.
    310      * If the AudioTrack has been opened with no callback function associated, the operation will fail.
    311      *
    312      * Parameters:
    313      *
    314      * updatePeriod:  position update notification period expressed in frames.
    315      *
    316      * Returned status (from utils/Errors.h) can be:
    317      *  - NO_ERROR: successful operation
    318      *  - INVALID_OPERATION: the AudioTrack has no callback installed.
    319      */
    320             status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
    321             status_t    getPositionUpdatePeriod(uint32_t *updatePeriod);
    322 
    323 
    324     /* Sets playback head position within AudioTrack buffer. The new position is specified
    325      * in number of frames.
    326      * This method must be called with the AudioTrack in paused or stopped state.
    327      * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames.
    328      * Therefore using this method makes sense only when playing a "static" audio buffer
    329      * as opposed to streaming.
    330      * The getPosition() method on the other hand returns the total number of frames played since
    331      * playback start.
    332      *
    333      * Parameters:
    334      *
    335      * position:  New playback head position within AudioTrack buffer.
    336      *
    337      * Returned status (from utils/Errors.h) can be:
    338      *  - NO_ERROR: successful operation
    339      *  - INVALID_OPERATION: the AudioTrack is not stopped.
    340      *  - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer
    341      */
    342             status_t    setPosition(uint32_t position);
    343             status_t    getPosition(uint32_t *position);
    344 
    345     /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
    346      * rewriting the buffer before restarting playback after a stop.
    347      * This method must be called with the AudioTrack in paused or stopped state.
    348      *
    349      * Returned status (from utils/Errors.h) can be:
    350      *  - NO_ERROR: successful operation
    351      *  - INVALID_OPERATION: the AudioTrack is not stopped.
    352      */
    353             status_t    reload();
    354 
    355     /* returns a handle on the audio output used by this AudioTrack.
    356      *
    357      * Parameters:
    358      *  none.
    359      *
    360      * Returned value:
    361      *  handle on audio hardware output
    362      */
    363             audio_io_handle_t    getOutput();
    364 
    365     /* returns the unique ID associated to this track.
    366      *
    367      * Parameters:
    368      *  none.
    369      *
    370      * Returned value:
    371      *  AudioTrack ID.
    372      */
    373             int    getSessionId();
    374 
    375 
    376     /* Attach track auxiliary output to specified effect. Used effectId = 0
    377      * to detach track from effect.
    378      *
    379      * Parameters:
    380      *
    381      * effectId:  effectId obtained from AudioEffect::id().
    382      *
    383      * Returned status (from utils/Errors.h) can be:
    384      *  - NO_ERROR: successful operation
    385      *  - INVALID_OPERATION: the effect is not an auxiliary effect.
    386      *  - BAD_VALUE: The specified effect ID is invalid
    387      */
    388             status_t    attachAuxEffect(int effectId);
    389 
    390     /* obtains a buffer of "frameCount" frames. The buffer must be
    391      * filled entirely. If the track is stopped, obtainBuffer() returns
    392      * STOPPED instead of NO_ERROR as long as there are buffers availlable,
    393      * at which point NO_MORE_BUFFERS is returned.
    394      * Buffers will be returned until the pool (buffercount())
    395      * is exhausted, at which point obtainBuffer() will either block
    396      * or return WOULD_BLOCK depending on the value of the "blocking"
    397      * parameter.
    398      */
    399 
    400         enum {
    401             NO_MORE_BUFFERS = 0x80000001,
    402             STOPPED = 1
    403         };
    404 
    405             status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
    406             void        releaseBuffer(Buffer* audioBuffer);
    407 
    408 
    409     /* As a convenience we provide a write() interface to the audio buffer.
    410      * This is implemented on top of lockBuffer/unlockBuffer. For best
    411      * performance
    412      *
    413      */
    414             ssize_t     write(const void* buffer, size_t size);
    415 
    416     /*
    417      * Dumps the state of an audio track.
    418      */
    419             status_t dump(int fd, const Vector<String16>& args) const;
    420 
    421 private:
    422     /* copying audio tracks is not allowed */
    423                         AudioTrack(const AudioTrack& other);
    424             AudioTrack& operator = (const AudioTrack& other);
    425 
    426     /* a small internal class to handle the callback */
    427     class AudioTrackThread : public Thread
    428     {
    429     public:
    430         AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
    431     private:
    432         friend class AudioTrack;
    433         virtual bool        threadLoop();
    434         virtual status_t    readyToRun();
    435         virtual void        onFirstRef();
    436         AudioTrack& mReceiver;
    437         Mutex       mLock;
    438     };
    439 
    440             bool processAudioBuffer(const sp<AudioTrackThread>& thread);
    441             status_t createTrack_l(int streamType,
    442                                  uint32_t sampleRate,
    443                                  uint32_t format,
    444                                  uint32_t channelMask,
    445                                  int frameCount,
    446                                  uint32_t flags,
    447                                  const sp<IMemory>& sharedBuffer,
    448                                  audio_io_handle_t output,
    449                                  bool enforceFrameCount);
    450             void flush_l();
    451             status_t setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
    452             audio_io_handle_t getOutput_l();
    453             status_t restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart);
    454 
    455     sp<IAudioTrack>         mAudioTrack;
    456     sp<IMemory>             mCblkMemory;
    457     sp<AudioTrackThread>    mAudioTrackThread;
    458 
    459     float                   mVolume[2];
    460     float                   mSendLevel;
    461     uint32_t                mFrameCount;
    462 
    463     audio_track_cblk_t*     mCblk;
    464     uint32_t                mFormat;
    465     uint8_t                 mStreamType;
    466     uint8_t                 mChannelCount;
    467     uint8_t                 mMuted;
    468     uint8_t                 mReserved;
    469     uint32_t                mChannelMask;
    470     status_t                mStatus;
    471     uint32_t                mLatency;
    472 
    473     volatile int32_t        mActive;
    474 
    475     callback_t              mCbf;
    476     void*                   mUserData;
    477     uint32_t                mNotificationFramesReq; // requested number of frames between each notification callback
    478     uint32_t                mNotificationFramesAct; // actual number of frames between each notification callback
    479     sp<IMemory>             mSharedBuffer;
    480     int                     mLoopCount;
    481     uint32_t                mRemainingFrames;
    482     uint32_t                mMarkerPosition;
    483     bool                    mMarkerReached;
    484     uint32_t                mNewPosition;
    485     uint32_t                mUpdatePeriod;
    486     bool                    mFlushed; // FIXME will be made obsolete by making flush() synchronous
    487     uint32_t                mFlags;
    488     int                     mSessionId;
    489     int                     mAuxEffectId;
    490     Mutex                   mLock;
    491     status_t                mRestoreStatus;
    492 };
    493 
    494 
    495 }; // namespace android
    496 
    497 #endif // ANDROID_AUDIOTRACK_H
    498