AudioTrack.java revision 1b8f499a14a4340d3422d95c7f6fdc8c0c72b3a4
1/*
2 * Copyright (C) 2008 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
17package android.media;
18
19import java.lang.ref.WeakReference;
20import java.lang.IllegalArgumentException;
21import java.lang.IllegalStateException;
22
23import android.os.Handler;
24import android.os.Looper;
25import android.os.Message;
26import android.media.AudioManager;
27import android.util.Log;
28
29
30/**
31 * The AudioTrack class manages and plays a single audio resource for Java applications.
32 * It allows streaming PCM audio buffers to the audio hardware for playback. This is
33 * achieved by "pushing" the data to the AudioTrack object using one of the
34 *  {@link #write(byte[], int, int)} and {@link #write(short[], int, int)} methods.
35 *
36 * <p>An AudioTrack instance can operate under two modes: static or streaming.<br>
37 * In Streaming mode, the application writes a continuous stream of data to the AudioTrack, using
38 * one of the {@code write()} methods. These are blocking and return when the data has been
39 * transferred from the Java layer to the native layer and queued for playback. The streaming
40 * mode is most useful when playing blocks of audio data that for instance are:
41 *
42 * <ul>
43 *   <li>too big to fit in memory because of the duration of the sound to play,</li>
44 *   <li>too big to fit in memory because of the characteristics of the audio data
45 *         (high sampling rate, bits per sample ...)</li>
46 *   <li>received or generated while previously queued audio is playing.</li>
47 * </ul>
48 *
49 * The static mode should be chosen when dealing with short sounds that fit in memory and
50 * that need to be played with the smallest latency possible. The static mode will
51 * therefore be preferred for UI and game sounds that are played often, and with the
52 * smallest overhead possible.
53 *
54 * <p>Upon creation, an AudioTrack object initializes its associated audio buffer.
55 * The size of this buffer, specified during the construction, determines how long an AudioTrack
56 * can play before running out of data.<br>
57 * For an AudioTrack using the static mode, this size is the maximum size of the sound that can
58 * be played from it.<br>
59 * For the streaming mode, data will be written to the hardware in chunks of
60 * sizes less than or equal to the total buffer size.
61 */
62public class AudioTrack
63{
64    //---------------------------------------------------------
65    // Constants
66    //--------------------
67    /** Minimum value for a channel volume */
68    private static final float VOLUME_MIN = 0.0f;
69    /** Maximum value for a channel volume */
70    private static final float VOLUME_MAX = 1.0f;
71
72    /** indicates AudioTrack state is stopped */
73    public static final int PLAYSTATE_STOPPED = 1;  // matches SL_PLAYSTATE_STOPPED
74    /** indicates AudioTrack state is paused */
75    public static final int PLAYSTATE_PAUSED  = 2;  // matches SL_PLAYSTATE_PAUSED
76    /** indicates AudioTrack state is playing */
77    public static final int PLAYSTATE_PLAYING = 3;  // matches SL_PLAYSTATE_PLAYING
78
79    // keep these values in sync with android_media_AudioTrack.cpp
80    /**
81     * Creation mode where audio data is transferred from Java to the native layer
82     * only once before the audio starts playing.
83     */
84    public static final int MODE_STATIC = 0;
85    /**
86     * Creation mode where audio data is streamed from Java to the native layer
87     * as the audio is playing.
88     */
89    public static final int MODE_STREAM = 1;
90
91    /**
92     * State of an AudioTrack that was not successfully initialized upon creation.
93     */
94    public static final int STATE_UNINITIALIZED = 0;
95    /**
96     * State of an AudioTrack that is ready to be used.
97     */
98    public static final int STATE_INITIALIZED   = 1;
99    /**
100     * State of a successfully initialized AudioTrack that uses static data,
101     * but that hasn't received that data yet.
102     */
103    public static final int STATE_NO_STATIC_DATA = 2;
104
105    // Error codes:
106    // to keep in sync with frameworks/base/core/jni/android_media_AudioTrack.cpp
107    /**
108     * Denotes a successful operation.
109     */
110    public  static final int SUCCESS                               = 0;
111    /**
112     * Denotes a generic operation failure.
113     */
114    public  static final int ERROR                                 = -1;
115    /**
116     * Denotes a failure due to the use of an invalid value.
117     */
118    public  static final int ERROR_BAD_VALUE                       = -2;
119    /**
120     * Denotes a failure due to the improper use of a method.
121     */
122    public  static final int ERROR_INVALID_OPERATION               = -3;
123
124    private static final int ERROR_NATIVESETUP_AUDIOSYSTEM         = -16;
125    private static final int ERROR_NATIVESETUP_INVALIDCHANNELMASK  = -17;
126    private static final int ERROR_NATIVESETUP_INVALIDFORMAT       = -18;
127    private static final int ERROR_NATIVESETUP_INVALIDSTREAMTYPE   = -19;
128    private static final int ERROR_NATIVESETUP_NATIVEINITFAILED    = -20;
129
130    // Events:
131    // to keep in sync with frameworks/base/include/media/AudioTrack.h
132    /**
133     * Event id denotes when playback head has reached a previously set marker.
134     */
135    private static final int NATIVE_EVENT_MARKER  = 3;
136    /**
137     * Event id denotes when previously set update period has elapsed during playback.
138     */
139    private static final int NATIVE_EVENT_NEW_POS = 4;
140
141    private final static String TAG = "AudioTrack-Java";
142
143
144    //--------------------------------------------------------------------------
145    // Member variables
146    //--------------------
147    /**
148     * Indicates the state of the AudioTrack instance.
149     */
150    private int mState = STATE_UNINITIALIZED;
151    /**
152     * Indicates the play state of the AudioTrack instance.
153     */
154    private int mPlayState = PLAYSTATE_STOPPED;
155    /**
156     * Lock to make sure mPlayState updates are reflecting the actual state of the object.
157     */
158    private final Object mPlayStateLock = new Object();
159    /**
160     * The listener the AudioTrack notifies when the playback position reaches a marker
161     * or for periodic updates during the progression of the playback head.
162     *  @see #setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener)
163     */
164    private OnPlaybackPositionUpdateListener mPositionListener = null;
165    /**
166     * Lock to protect event listener updates against event notifications.
167     */
168    private final Object mPositionListenerLock = new Object();
169    /**
170     * Size of the native audio buffer.
171     */
172    private int mNativeBufferSizeInBytes = 0;
173    /**
174     * Handler for marker events coming from the native code.
175     */
176    private NativeEventHandlerDelegate mEventHandlerDelegate = null;
177    /**
178     * Looper associated with the thread that creates the AudioTrack instance.
179     */
180    private Looper mInitializationLooper = null;
181    /**
182     * The audio data sampling rate in Hz.
183     */
184    private int mSampleRate; // initialized by all constructors
185    /**
186     * The number of audio output channels (1 is mono, 2 is stereo).
187     */
188    private int mChannelCount = 1;
189    /**
190     * The audio channel mask.
191     */
192    private int mChannels = AudioFormat.CHANNEL_OUT_MONO;
193
194    /**
195     * The type of the audio stream to play. See
196     *   {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM},
197     *   {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC},
198     *   {@link AudioManager#STREAM_ALARM}, {@link AudioManager#STREAM_NOTIFICATION}, and
199     *   {@link AudioManager#STREAM_DTMF}.
200     */
201    private int mStreamType = AudioManager.STREAM_MUSIC;
202    /**
203     * The way audio is consumed by the hardware, streaming or static.
204     */
205    private int mDataLoadMode = MODE_STREAM;
206    /**
207     * The current audio channel configuration.
208     */
209    private int mChannelConfiguration = AudioFormat.CHANNEL_OUT_MONO;
210    /**
211     * The encoding of the audio samples.
212     * @see AudioFormat#ENCODING_PCM_8BIT
213     * @see AudioFormat#ENCODING_PCM_16BIT
214     */
215    private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT;
216    /**
217     * Audio session ID
218     */
219    private int mSessionId = 0;
220
221
222    //--------------------------------
223    // Used exclusively by native code
224    //--------------------
225    /**
226     * Accessed by native methods: provides access to C++ AudioTrack object.
227     */
228    @SuppressWarnings("unused")
229    private int mNativeTrackInJavaObj;
230    /**
231     * Accessed by native methods: provides access to the JNI data (i.e. resources used by
232     * the native AudioTrack object, but not stored in it).
233     */
234    @SuppressWarnings("unused")
235    private int mJniData;
236
237
238    //--------------------------------------------------------------------------
239    // Constructor, Finalize
240    //--------------------
241    /**
242     * Class constructor.
243     * @param streamType the type of the audio stream. See
244     *   {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM},
245     *   {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC},
246     *   {@link AudioManager#STREAM_ALARM}, and {@link AudioManager#STREAM_NOTIFICATION}.
247     * @param sampleRateInHz the sample rate expressed in Hertz.
248     * @param channelConfig describes the configuration of the audio channels.
249     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
250     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
251     * @param audioFormat the format in which the audio data is represented.
252     *   See {@link AudioFormat#ENCODING_PCM_16BIT} and
253     *   {@link AudioFormat#ENCODING_PCM_8BIT}
254     * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read
255     *   from for playback. If using the AudioTrack in streaming mode, you can write data into
256     *   this buffer in smaller chunks than this size. If using the AudioTrack in static mode,
257     *   this is the maximum size of the sound that will be played for this instance.
258     *   See {@link #getMinBufferSize(int, int, int)} to determine the minimum required buffer size
259     *   for the successful creation of an AudioTrack instance in streaming mode. Using values
260     *   smaller than getMinBufferSize() will result in an initialization failure.
261     * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM}
262     * @throws java.lang.IllegalArgumentException
263     */
264    public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat,
265            int bufferSizeInBytes, int mode)
266    throws IllegalArgumentException {
267        this(streamType, sampleRateInHz, channelConfig, audioFormat,
268                bufferSizeInBytes, mode, 0);
269    }
270
271    /**
272     * Class constructor with audio session. Use this constructor when the AudioTrack must be
273     * attached to a particular audio session. The primary use of the audio session ID is to
274     * associate audio effects to a particular instance of AudioTrack: if an audio session ID
275     * is provided when creating an AudioEffect, this effect will be applied only to audio tracks
276     * and media players in the same session and not to the output mix.
277     * When an AudioTrack is created without specifying a session, it will create its own session
278     * which can be retreived by calling the {@link #getAudioSessionId()} method.
279     * If a non-zero session ID is provided, this AudioTrack will share effects attached to this
280     * session
281     * with all other media players or audio tracks in the same session, otherwise a new session
282     * will be created for this track if none is supplied.
283     * @param streamType the type of the audio stream. See
284     *   {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM},
285     *   {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC},
286     *   {@link AudioManager#STREAM_ALARM}, and {@link AudioManager#STREAM_NOTIFICATION}.
287     * @param sampleRateInHz the sample rate expressed in Hertz.
288     * @param channelConfig describes the configuration of the audio channels.
289     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
290     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
291     * @param audioFormat the format in which the audio data is represented.
292     *   See {@link AudioFormat#ENCODING_PCM_16BIT} and
293     *   {@link AudioFormat#ENCODING_PCM_8BIT}
294     * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read
295     *   from for playback. If using the AudioTrack in streaming mode, you can write data into
296     *   this buffer in smaller chunks than this size. If using the AudioTrack in static mode,
297     *   this is the maximum size of the sound that will be played for this instance.
298     *   See {@link #getMinBufferSize(int, int, int)} to determine the minimum required buffer size
299     *   for the successful creation of an AudioTrack instance in streaming mode. Using values
300     *   smaller than getMinBufferSize() will result in an initialization failure.
301     * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM}
302     * @param sessionId Id of audio session the AudioTrack must be attached to
303     * @throws java.lang.IllegalArgumentException
304     */
305    public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat,
306            int bufferSizeInBytes, int mode, int sessionId)
307    throws IllegalArgumentException {
308        mState = STATE_UNINITIALIZED;
309
310        // remember which looper is associated with the AudioTrack instantiation
311        if ((mInitializationLooper = Looper.myLooper()) == null) {
312            mInitializationLooper = Looper.getMainLooper();
313        }
314
315        audioParamCheck(streamType, sampleRateInHz, channelConfig, audioFormat, mode);
316
317        audioBuffSizeCheck(bufferSizeInBytes);
318
319        if (sessionId < 0) {
320            throw (new IllegalArgumentException("Invalid audio session ID: "+sessionId));
321        }
322
323        int[] session = new int[1];
324        session[0] = sessionId;
325        // native initialization
326        int initResult = native_setup(new WeakReference<AudioTrack>(this),
327                mStreamType, mSampleRate, mChannels, mAudioFormat,
328                mNativeBufferSizeInBytes, mDataLoadMode, session);
329        if (initResult != SUCCESS) {
330            loge("Error code "+initResult+" when initializing AudioTrack.");
331            return; // with mState == STATE_UNINITIALIZED
332        }
333
334        mSessionId = session[0];
335
336        if (mDataLoadMode == MODE_STATIC) {
337            mState = STATE_NO_STATIC_DATA;
338        } else {
339            mState = STATE_INITIALIZED;
340        }
341    }
342
343    // mask of all the channels supported by this implementation
344    private static final int SUPPORTED_OUT_CHANNELS =
345            AudioFormat.CHANNEL_OUT_FRONT_LEFT |
346            AudioFormat.CHANNEL_OUT_FRONT_RIGHT |
347            AudioFormat.CHANNEL_OUT_FRONT_CENTER |
348            AudioFormat.CHANNEL_OUT_LOW_FREQUENCY |
349            AudioFormat.CHANNEL_OUT_BACK_LEFT |
350            AudioFormat.CHANNEL_OUT_BACK_RIGHT |
351            AudioFormat.CHANNEL_OUT_BACK_CENTER;
352
353    // Convenience method for the constructor's parameter checks.
354    // This is where constructor IllegalArgumentException-s are thrown
355    // postconditions:
356    //    mStreamType is valid
357    //    mChannelCount is valid
358    //    mChannels is valid
359    //    mAudioFormat is valid
360    //    mSampleRate is valid
361    //    mDataLoadMode is valid
362    private void audioParamCheck(int streamType, int sampleRateInHz,
363                                 int channelConfig, int audioFormat, int mode) {
364
365        //--------------
366        // stream type
367        if( (streamType != AudioManager.STREAM_ALARM) && (streamType != AudioManager.STREAM_MUSIC)
368           && (streamType != AudioManager.STREAM_RING) && (streamType != AudioManager.STREAM_SYSTEM)
369           && (streamType != AudioManager.STREAM_VOICE_CALL)
370           && (streamType != AudioManager.STREAM_NOTIFICATION)
371           && (streamType != AudioManager.STREAM_BLUETOOTH_SCO)
372           && (streamType != AudioManager.STREAM_DTMF)) {
373            throw (new IllegalArgumentException("Invalid stream type."));
374        } else {
375            mStreamType = streamType;
376        }
377
378        //--------------
379        // sample rate, note these values are subject to change
380        if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) {
381            throw (new IllegalArgumentException(sampleRateInHz
382                    + "Hz is not a supported sample rate."));
383        } else {
384            mSampleRate = sampleRateInHz;
385        }
386
387        //--------------
388        // channel config
389        mChannelConfiguration = channelConfig;
390
391        switch (channelConfig) {
392        case AudioFormat.CHANNEL_OUT_DEFAULT: //AudioFormat.CHANNEL_CONFIGURATION_DEFAULT
393        case AudioFormat.CHANNEL_OUT_MONO:
394        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
395            mChannelCount = 1;
396            mChannels = AudioFormat.CHANNEL_OUT_MONO;
397            break;
398        case AudioFormat.CHANNEL_OUT_STEREO:
399        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
400            mChannelCount = 2;
401            mChannels = AudioFormat.CHANNEL_OUT_STEREO;
402            break;
403        default:
404            if ((channelConfig & SUPPORTED_OUT_CHANNELS) != channelConfig) {
405                // input channel configuration features unsupported channels
406                mChannelCount = 0;
407                mChannels = AudioFormat.CHANNEL_INVALID;
408                mChannelConfiguration = AudioFormat.CHANNEL_INVALID;
409                throw(new IllegalArgumentException("Unsupported channel configuration."));
410            } else {
411                mChannels = channelConfig;
412                mChannelCount = Integer.bitCount(channelConfig);
413            }
414        }
415
416        //--------------
417        // audio format
418        switch (audioFormat) {
419        case AudioFormat.ENCODING_DEFAULT:
420            mAudioFormat = AudioFormat.ENCODING_PCM_16BIT;
421            break;
422        case AudioFormat.ENCODING_PCM_16BIT:
423        case AudioFormat.ENCODING_PCM_8BIT:
424            mAudioFormat = audioFormat;
425            break;
426        default:
427            mAudioFormat = AudioFormat.ENCODING_INVALID;
428            throw(new IllegalArgumentException("Unsupported sample encoding."
429                + " Should be ENCODING_PCM_8BIT or ENCODING_PCM_16BIT."));
430        }
431
432        //--------------
433        // audio load mode
434        if ( (mode != MODE_STREAM) && (mode != MODE_STATIC) ) {
435            throw(new IllegalArgumentException("Invalid mode."));
436        } else {
437            mDataLoadMode = mode;
438        }
439    }
440
441
442    // Convenience method for the contructor's audio buffer size check.
443    // preconditions:
444    //    mChannelCount is valid
445    //    mAudioFormat is valid
446    // postcondition:
447    //    mNativeBufferSizeInBytes is valid (multiple of frame size, positive)
448    private void audioBuffSizeCheck(int audioBufferSize) {
449        // NB: this section is only valid with PCM data.
450        //     To update when supporting compressed formats
451        int frameSizeInBytes = mChannelCount
452                * (mAudioFormat == AudioFormat.ENCODING_PCM_8BIT ? 1 : 2);
453        if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) {
454            throw (new IllegalArgumentException("Invalid audio buffer size."));
455        }
456
457        mNativeBufferSizeInBytes = audioBufferSize;
458    }
459
460
461    /**
462     * Releases the native AudioTrack resources.
463     */
464    public void release() {
465        // even though native_release() stops the native AudioTrack, we need to stop
466        // AudioTrack subclasses too.
467        try {
468            stop();
469        } catch(IllegalStateException ise) {
470            // don't raise an exception, we're releasing the resources.
471        }
472        native_release();
473        mState = STATE_UNINITIALIZED;
474    }
475
476    @Override
477    protected void finalize() {
478        native_finalize();
479    }
480
481    //--------------------------------------------------------------------------
482    // Getters
483    //--------------------
484    /**
485     * Returns the minimum valid volume value. Volume values set under this one will
486     * be clamped at this value.
487     * @return the minimum volume expressed as a linear attenuation.
488     */
489    static public float getMinVolume() {
490        return AudioTrack.VOLUME_MIN;
491    }
492
493    /**
494     * Returns the maximum valid volume value. Volume values set above this one will
495     * be clamped at this value.
496     * @return the maximum volume expressed as a linear attenuation.
497     */
498    static public float getMaxVolume() {
499        return AudioTrack.VOLUME_MAX;
500    }
501
502    /**
503     * Returns the configured audio data sample rate in Hz
504     */
505    public int getSampleRate() {
506        return mSampleRate;
507    }
508
509    /**
510     * Returns the current playback rate in Hz.
511     */
512    public int getPlaybackRate() {
513        return native_get_playback_rate();
514    }
515
516    /**
517     * Returns the configured audio data format. See {@link AudioFormat#ENCODING_PCM_16BIT}
518     * and {@link AudioFormat#ENCODING_PCM_8BIT}.
519     */
520    public int getAudioFormat() {
521        return mAudioFormat;
522    }
523
524    /**
525     * Returns the type of audio stream this AudioTrack is configured for.
526     * Compare the result against {@link AudioManager#STREAM_VOICE_CALL},
527     * {@link AudioManager#STREAM_SYSTEM}, {@link AudioManager#STREAM_RING},
528     * {@link AudioManager#STREAM_MUSIC}, {@link AudioManager#STREAM_ALARM},
529     * {@link AudioManager#STREAM_NOTIFICATION}, or {@link AudioManager#STREAM_DTMF}.
530     */
531    public int getStreamType() {
532        return mStreamType;
533    }
534
535    /**
536     * Returns the configured channel configuration.
537
538     * See {@link AudioFormat#CHANNEL_OUT_MONO}
539     * and {@link AudioFormat#CHANNEL_OUT_STEREO}.
540     */
541    public int getChannelConfiguration() {
542        return mChannelConfiguration;
543    }
544
545    /**
546     * Returns the configured number of channels.
547     */
548    public int getChannelCount() {
549        return mChannelCount;
550    }
551
552    /**
553     * Returns the state of the AudioTrack instance. This is useful after the
554     * AudioTrack instance has been created to check if it was initialized
555     * properly. This ensures that the appropriate hardware resources have been
556     * acquired.
557     * @see #STATE_INITIALIZED
558     * @see #STATE_NO_STATIC_DATA
559     * @see #STATE_UNINITIALIZED
560     */
561    public int getState() {
562        return mState;
563    }
564
565    /**
566     * Returns the playback state of the AudioTrack instance.
567     * @see #PLAYSTATE_STOPPED
568     * @see #PLAYSTATE_PAUSED
569     * @see #PLAYSTATE_PLAYING
570     */
571    public int getPlayState() {
572        synchronized (mPlayStateLock) {
573            return mPlayState;
574        }
575    }
576
577    /**
578     *  Returns the native frame count used by the hardware.
579     */
580    protected int getNativeFrameCount() {
581        return native_get_native_frame_count();
582    }
583
584    /**
585     * Returns marker position expressed in frames.
586     */
587    public int getNotificationMarkerPosition() {
588        return native_get_marker_pos();
589    }
590
591    /**
592     * Returns the notification update period expressed in frames.
593     */
594    public int getPositionNotificationPeriod() {
595        return native_get_pos_update_period();
596    }
597
598    /**
599     * Returns the playback head position expressed in frames
600     */
601    public int getPlaybackHeadPosition() {
602        return native_get_position();
603    }
604
605    /**
606     *  Returns the hardware output sample rate
607     */
608    static public int getNativeOutputSampleRate(int streamType) {
609        return native_get_output_sample_rate(streamType);
610    }
611
612    /**
613     * Returns the minimum buffer size required for the successful creation of an AudioTrack
614     * object to be created in the {@link #MODE_STREAM} mode. Note that this size doesn't
615     * guarantee a smooth playback under load, and higher values should be chosen according to
616     * the expected frequency at which the buffer will be refilled with additional data to play.
617     * @param sampleRateInHz the sample rate expressed in Hertz.
618     * @param channelConfig describes the configuration of the audio channels.
619     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
620     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
621     * @param audioFormat the format in which the audio data is represented.
622     *   See {@link AudioFormat#ENCODING_PCM_16BIT} and
623     *   {@link AudioFormat#ENCODING_PCM_8BIT}
624     * @return {@link #ERROR_BAD_VALUE} if an invalid parameter was passed,
625     *   or {@link #ERROR} if the implementation was unable to query the hardware for its output
626     *     properties,
627     *   or the minimum buffer size expressed in bytes.
628     */
629    static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) {
630        int channelCount = 0;
631        switch(channelConfig) {
632        case AudioFormat.CHANNEL_OUT_MONO:
633        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
634            channelCount = 1;
635            break;
636        case AudioFormat.CHANNEL_OUT_STEREO:
637        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
638            channelCount = 2;
639            break;
640        default:
641            if ((channelConfig & SUPPORTED_OUT_CHANNELS) != channelConfig) {
642                // input channel configuration features unsupported channels
643                loge("getMinBufferSize(): Invalid channel configuration.");
644                return AudioTrack.ERROR_BAD_VALUE;
645            } else {
646                channelCount = Integer.bitCount(channelConfig);
647            }
648        }
649
650        if ((audioFormat != AudioFormat.ENCODING_PCM_16BIT)
651            && (audioFormat != AudioFormat.ENCODING_PCM_8BIT)) {
652            loge("getMinBufferSize(): Invalid audio format.");
653            return AudioTrack.ERROR_BAD_VALUE;
654        }
655
656        // sample rate, note these values are subject to change
657        if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) {
658            loge("getMinBufferSize(): " + sampleRateInHz +"Hz is not a supported sample rate.");
659            return AudioTrack.ERROR_BAD_VALUE;
660        }
661
662        int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat);
663        if ((size == -1) || (size == 0)) {
664            loge("getMinBufferSize(): error querying hardware");
665            return AudioTrack.ERROR;
666        }
667        else {
668            return size;
669        }
670    }
671
672    /**
673     * Returns the audio session ID.
674     *
675     * @return the ID of the audio session this AudioTrack belongs to.
676     */
677    public int getAudioSessionId() {
678        return mSessionId;
679    }
680
681    //--------------------------------------------------------------------------
682    // Initialization / configuration
683    //--------------------
684    /**
685     * Sets the listener the AudioTrack notifies when a previously set marker is reached or
686     * for each periodic playback head position update.
687     * Notifications will be received in the same thread as the one in which the AudioTrack
688     * instance was created.
689     * @param listener
690     */
691    public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener) {
692        setPlaybackPositionUpdateListener(listener, null);
693    }
694
695    /**
696     * Sets the listener the AudioTrack notifies when a previously set marker is reached or
697     * for each periodic playback head position update.
698     * Use this method to receive AudioTrack events in the Handler associated with another
699     * thread than the one in which you created the AudioTrack instance.
700     * @param listener
701     * @param handler the Handler that will receive the event notification messages.
702     */
703    public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener,
704                                                    Handler handler) {
705        synchronized (mPositionListenerLock) {
706            mPositionListener = listener;
707        }
708        if (listener != null) {
709            mEventHandlerDelegate = new NativeEventHandlerDelegate(this, handler);
710        }
711
712    }
713
714
715
716     /**
717     * Sets the specified left/right output volume values on the AudioTrack. Values are clamped
718     * to the ({@link #getMinVolume()}, {@link #getMaxVolume()}) interval if outside this range.
719     * @param leftVolume output attenuation for the left channel. A value of 0.0f is silence,
720     *      a value of 1.0f is no attenuation.
721     * @param rightVolume output attenuation for the right channel
722     * @return error code or success, see {@link #SUCCESS},
723     *    {@link #ERROR_INVALID_OPERATION}
724     */
725    public int setStereoVolume(float leftVolume, float rightVolume) {
726        if (mState != STATE_INITIALIZED) {
727            return ERROR_INVALID_OPERATION;
728        }
729
730        // clamp the volumes
731        if (leftVolume < getMinVolume()) {
732            leftVolume = getMinVolume();
733        }
734        if (leftVolume > getMaxVolume()) {
735            leftVolume = getMaxVolume();
736        }
737        if (rightVolume < getMinVolume()) {
738            rightVolume = getMinVolume();
739        }
740        if (rightVolume > getMaxVolume()) {
741            rightVolume = getMaxVolume();
742        }
743
744        native_setVolume(leftVolume, rightVolume);
745
746        return SUCCESS;
747    }
748
749
750    /**
751     * Sets the playback sample rate for this track. This sets the sampling rate at which
752     * the audio data will be consumed and played back, not the original sampling rate of the
753     * content. Setting it to half the sample rate of the content will cause the playback to
754     * last twice as long, but will also result in a negative pitch shift.
755     * The valid sample rate range is from 1Hz to twice the value returned by
756     * {@link #getNativeOutputSampleRate(int)}.
757     * @param sampleRateInHz the sample rate expressed in Hz
758     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
759     *    {@link #ERROR_INVALID_OPERATION}
760     */
761    public int setPlaybackRate(int sampleRateInHz) {
762        if (mState != STATE_INITIALIZED) {
763            return ERROR_INVALID_OPERATION;
764        }
765        if (sampleRateInHz <= 0) {
766            return ERROR_BAD_VALUE;
767        }
768        return native_set_playback_rate(sampleRateInHz);
769    }
770
771
772    /**
773     * Sets the position of the notification marker.
774     * @param markerInFrames marker in frames
775     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
776     *  {@link #ERROR_INVALID_OPERATION}
777     */
778    public int setNotificationMarkerPosition(int markerInFrames) {
779        if (mState != STATE_INITIALIZED) {
780            return ERROR_INVALID_OPERATION;
781        }
782        return native_set_marker_pos(markerInFrames);
783    }
784
785
786    /**
787     * Sets the period for the periodic notification event.
788     * @param periodInFrames update period expressed in frames
789     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION}
790     */
791    public int setPositionNotificationPeriod(int periodInFrames) {
792        if (mState != STATE_INITIALIZED) {
793            return ERROR_INVALID_OPERATION;
794        }
795        return native_set_pos_update_period(periodInFrames);
796    }
797
798
799    /**
800     * Sets the playback head position. The track must be stopped for the position to be changed.
801     * @param positionInFrames playback head position expressed in frames
802     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
803     *    {@link #ERROR_INVALID_OPERATION}
804     */
805    public int setPlaybackHeadPosition(int positionInFrames) {
806        synchronized(mPlayStateLock) {
807            if ((mPlayState == PLAYSTATE_STOPPED) || (mPlayState == PLAYSTATE_PAUSED)) {
808                return native_set_position(positionInFrames);
809            } else {
810                return ERROR_INVALID_OPERATION;
811            }
812        }
813    }
814
815    /**
816     * Sets the loop points and the loop count. The loop can be infinite.
817     * @param startInFrames loop start marker expressed in frames
818     * @param endInFrames loop end marker expressed in frames
819     * @param loopCount the number of times the loop is looped.
820     *    A value of -1 means infinite looping.
821     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
822     *    {@link #ERROR_INVALID_OPERATION}
823     */
824    public int setLoopPoints(int startInFrames, int endInFrames, int loopCount) {
825        if (mDataLoadMode == MODE_STREAM) {
826            return ERROR_INVALID_OPERATION;
827        }
828        return native_set_loop(startInFrames, endInFrames, loopCount);
829    }
830
831    /**
832     * Sets the initialization state of the instance. To be used in an AudioTrack subclass
833     * constructor to set a subclass-specific post-initialization state.
834     * @param state the state of the AudioTrack instance
835     */
836    protected void setState(int state) {
837        mState = state;
838    }
839
840
841    //---------------------------------------------------------
842    // Transport control methods
843    //--------------------
844    /**
845     * Starts playing an AudioTrack.
846     *
847     * @throws IllegalStateException
848     */
849    public void play()
850    throws IllegalStateException {
851        if (mState != STATE_INITIALIZED) {
852            throw(new IllegalStateException("play() called on uninitialized AudioTrack."));
853        }
854
855        synchronized(mPlayStateLock) {
856            native_start();
857            mPlayState = PLAYSTATE_PLAYING;
858        }
859    }
860
861    /**
862     * Stops playing the audio data.
863     * When used on an instance created in {@link #MODE_STREAM} mode, audio will stop playing
864     * after the last buffer that was written has been played. For an immediate stop, use
865     * {@link #pause()}, followed by {@link #flush()} to discard audio data that hasn't been played
866     * back yet.
867     * @throws IllegalStateException
868     */
869    public void stop()
870    throws IllegalStateException {
871        if (mState != STATE_INITIALIZED) {
872            throw(new IllegalStateException("stop() called on uninitialized AudioTrack."));
873        }
874
875        // stop playing
876        synchronized(mPlayStateLock) {
877            native_stop();
878            mPlayState = PLAYSTATE_STOPPED;
879        }
880    }
881
882    /**
883     * Pauses the playback of the audio data. Data that has not been played
884     * back will not be discarded. Subsequent calls to {@link #play} will play
885     * this data back. See {@link #flush()} to discard this data.
886     *
887     * @throws IllegalStateException
888     */
889    public void pause()
890    throws IllegalStateException {
891        if (mState != STATE_INITIALIZED) {
892            throw(new IllegalStateException("pause() called on uninitialized AudioTrack."));
893        }
894        //logd("pause()");
895
896        // pause playback
897        synchronized(mPlayStateLock) {
898            native_pause();
899            mPlayState = PLAYSTATE_PAUSED;
900        }
901    }
902
903
904    //---------------------------------------------------------
905    // Audio data supply
906    //--------------------
907
908    /**
909     * Flushes the audio data currently queued for playback. Any data that has
910     * not been played back will be discarded.
911     */
912    public void flush() {
913        if (mState == STATE_INITIALIZED) {
914            // flush the data in native layer
915            native_flush();
916        }
917
918    }
919
920    /**
921     * Writes the audio data to the audio hardware for playback. Will block until
922     * all data has been written to the audio mixer.
923     * Note that the actual playback of this data might occur after this function
924     * returns. This function is thread safe with respect to {@link #stop} calls,
925     * in which case all of the specified data might not be written to the mixer.
926     *
927     * @param audioData the array that holds the data to play.
928     * @param offsetInBytes the offset expressed in bytes in audioData where the data to play
929     *    starts.
930     * @param sizeInBytes the number of bytes to read in audioData after the offset.
931     * @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION}
932     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
933     *    the parameters don't resolve to valid data and indexes.
934     */
935
936    public int write(byte[] audioData, int offsetInBytes, int sizeInBytes) {
937        if ((mDataLoadMode == MODE_STATIC)
938                && (mState == STATE_NO_STATIC_DATA)
939                && (sizeInBytes > 0)) {
940            mState = STATE_INITIALIZED;
941        }
942
943        if (mState != STATE_INITIALIZED) {
944            return ERROR_INVALID_OPERATION;
945        }
946
947        if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0)
948                || (offsetInBytes + sizeInBytes > audioData.length)) {
949            return ERROR_BAD_VALUE;
950        }
951
952        return native_write_byte(audioData, offsetInBytes, sizeInBytes, mAudioFormat);
953    }
954
955
956    /**
957     * Writes the audio data to the audio hardware for playback. Will block until
958     * all data has been written to the audio mixer.
959     * Note that the actual playback of this data might occur after this function
960     * returns. This function is thread safe with respect to {@link #stop} calls,
961     * in which case all of the specified data might not be written to the mixer.
962     *
963     * @param audioData the array that holds the data to play.
964     * @param offsetInShorts the offset expressed in shorts in audioData where the data to play
965     *     starts.
966     * @param sizeInShorts the number of bytes to read in audioData after the offset.
967     * @return the number of shorts that were written or {@link #ERROR_INVALID_OPERATION}
968      *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
969      *    the parameters don't resolve to valid data and indexes.
970     */
971
972    public int write(short[] audioData, int offsetInShorts, int sizeInShorts) {
973        if ((mDataLoadMode == MODE_STATIC)
974                && (mState == STATE_NO_STATIC_DATA)
975                && (sizeInShorts > 0)) {
976            mState = STATE_INITIALIZED;
977        }
978
979        if (mState != STATE_INITIALIZED) {
980            return ERROR_INVALID_OPERATION;
981        }
982
983        if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0)
984                || (offsetInShorts + sizeInShorts > audioData.length)) {
985            return ERROR_BAD_VALUE;
986        }
987
988        return native_write_short(audioData, offsetInShorts, sizeInShorts, mAudioFormat);
989    }
990
991
992    /**
993     * Notifies the native resource to reuse the audio data already loaded in the native
994     * layer. This call is only valid with AudioTrack instances that don't use the streaming
995     * model.
996     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
997     *  {@link #ERROR_INVALID_OPERATION}
998     */
999    public int reloadStaticData() {
1000        if (mDataLoadMode == MODE_STREAM) {
1001            return ERROR_INVALID_OPERATION;
1002        }
1003        return native_reload_static();
1004    }
1005
1006    //--------------------------------------------------------------------------
1007    // Audio effects management
1008    //--------------------
1009
1010    /**
1011     * Attaches an auxiliary effect to the audio track. A typical auxiliary
1012     * effect is a reverberation effect which can be applied on any sound source
1013     * that directs a certain amount of its energy to this effect. This amount
1014     * is defined by setAuxEffectSendLevel().
1015     * {@see #setAuxEffectSendLevel(float)}.
1016     * <p>After creating an auxiliary effect (e.g.
1017     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1018     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling
1019     * this method to attach the audio track to the effect.
1020     * <p>To detach the effect from the audio track, call this method with a
1021     * null effect id.
1022     *
1023     * @param effectId system wide unique id of the effect to attach
1024     * @return error code or success, see {@link #SUCCESS},
1025     *    {@link #ERROR_INVALID_OPERATION}, {@link #ERROR_BAD_VALUE}
1026     */
1027    public int attachAuxEffect(int effectId) {
1028        if (mState != STATE_INITIALIZED) {
1029            return ERROR_INVALID_OPERATION;
1030        }
1031        return native_attachAuxEffect(effectId);
1032    }
1033
1034    /**
1035     * Sets the send level of the audio track to the attached auxiliary effect
1036     * {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1037     * <p>By default the send level is 0, so even if an effect is attached to the player
1038     * this method must be called for the effect to be applied.
1039     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1040     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1041     * so an appropriate conversion from linear UI input x to level is:
1042     * x == 0 -&gt; level = 0
1043     * 0 &lt; x &lt;= R -&gt; level = 10^(72*(x-R)/20/R)
1044     *
1045     * @param level send level scalar
1046     * @return error code or success, see {@link #SUCCESS},
1047     *    {@link #ERROR_INVALID_OPERATION}
1048     */
1049    public int setAuxEffectSendLevel(float level) {
1050        if (mState != STATE_INITIALIZED) {
1051            return ERROR_INVALID_OPERATION;
1052        }
1053        // clamp the level
1054        if (level < getMinVolume()) {
1055            level = getMinVolume();
1056        }
1057        if (level > getMaxVolume()) {
1058            level = getMaxVolume();
1059        }
1060        native_setAuxEffectSendLevel(level);
1061        return SUCCESS;
1062    }
1063
1064    //---------------------------------------------------------
1065    // Interface definitions
1066    //--------------------
1067    /**
1068     * Interface definition for a callback to be invoked when the playback head position of
1069     * an AudioTrack has reached a notification marker or has increased by a certain period.
1070     */
1071    public interface OnPlaybackPositionUpdateListener  {
1072        /**
1073         * Called on the listener to notify it that the previously set marker has been reached
1074         * by the playback head.
1075         */
1076        void onMarkerReached(AudioTrack track);
1077
1078        /**
1079         * Called on the listener to periodically notify it that the playback head has reached
1080         * a multiple of the notification period.
1081         */
1082        void onPeriodicNotification(AudioTrack track);
1083    }
1084
1085
1086    //---------------------------------------------------------
1087    // Inner classes
1088    //--------------------
1089    /**
1090     * Helper class to handle the forwarding of native events to the appropriate listener
1091     * (potentially) handled in a different thread
1092     */
1093    private class NativeEventHandlerDelegate {
1094        private final AudioTrack mAudioTrack;
1095        private final Handler mHandler;
1096
1097        NativeEventHandlerDelegate(AudioTrack track, Handler handler) {
1098            mAudioTrack = track;
1099            // find the looper for our new event handler
1100            Looper looper;
1101            if (handler != null) {
1102                looper = handler.getLooper();
1103            } else {
1104                // no given handler, use the looper the AudioTrack was created in
1105                looper = mInitializationLooper;
1106            }
1107
1108            // construct the event handler with this looper
1109            if (looper != null) {
1110                // implement the event handler delegate
1111                mHandler = new Handler(looper) {
1112                    @Override
1113                    public void handleMessage(Message msg) {
1114                        if (mAudioTrack == null) {
1115                            return;
1116                        }
1117                        OnPlaybackPositionUpdateListener listener = null;
1118                        synchronized (mPositionListenerLock) {
1119                            listener = mAudioTrack.mPositionListener;
1120                        }
1121                        switch(msg.what) {
1122                        case NATIVE_EVENT_MARKER:
1123                            if (listener != null) {
1124                                listener.onMarkerReached(mAudioTrack);
1125                            }
1126                            break;
1127                        case NATIVE_EVENT_NEW_POS:
1128                            if (listener != null) {
1129                                listener.onPeriodicNotification(mAudioTrack);
1130                            }
1131                            break;
1132                        default:
1133                            Log.e(TAG, "[ android.media.AudioTrack.NativeEventHandler ] " +
1134                                    "Unknown event type: " + msg.what);
1135                            break;
1136                        }
1137                    }
1138                };
1139            } else {
1140                mHandler = null;
1141            }
1142        }
1143
1144        Handler getHandler() {
1145            return mHandler;
1146        }
1147    }
1148
1149
1150    //---------------------------------------------------------
1151    // Java methods called from the native side
1152    //--------------------
1153    @SuppressWarnings("unused")
1154    private static void postEventFromNative(Object audiotrack_ref,
1155            int what, int arg1, int arg2, Object obj) {
1156        //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2);
1157        AudioTrack track = (AudioTrack)((WeakReference)audiotrack_ref).get();
1158        if (track == null) {
1159            return;
1160        }
1161
1162        if (track.mEventHandlerDelegate != null) {
1163            Message m =
1164                track.mEventHandlerDelegate.getHandler().obtainMessage(what, arg1, arg2, obj);
1165            track.mEventHandlerDelegate.getHandler().sendMessage(m);
1166        }
1167
1168    }
1169
1170
1171    //---------------------------------------------------------
1172    // Native methods called from the Java side
1173    //--------------------
1174
1175    private native final int native_setup(Object audiotrack_this,
1176            int streamType, int sampleRate, int nbChannels, int audioFormat,
1177            int buffSizeInBytes, int mode, int[] sessionId);
1178
1179    private native final void native_finalize();
1180
1181    private native final void native_release();
1182
1183    private native final void native_start();
1184
1185    private native final void native_stop();
1186
1187    private native final void native_pause();
1188
1189    private native final void native_flush();
1190
1191    private native final int native_write_byte(byte[] audioData,
1192                                               int offsetInBytes, int sizeInBytes, int format);
1193
1194    private native final int native_write_short(short[] audioData,
1195                                                int offsetInShorts, int sizeInShorts, int format);
1196
1197    private native final int native_reload_static();
1198
1199    private native final int native_get_native_frame_count();
1200
1201    private native final void native_setVolume(float leftVolume, float rightVolume);
1202
1203    private native final int native_set_playback_rate(int sampleRateInHz);
1204    private native final int native_get_playback_rate();
1205
1206    private native final int native_set_marker_pos(int marker);
1207    private native final int native_get_marker_pos();
1208
1209    private native final int native_set_pos_update_period(int updatePeriod);
1210    private native final int native_get_pos_update_period();
1211
1212    private native final int native_set_position(int position);
1213    private native final int native_get_position();
1214
1215    private native final int native_set_loop(int start, int end, int loopCount);
1216
1217    static private native final int native_get_output_sample_rate(int streamType);
1218    static private native final int native_get_min_buff_size(
1219            int sampleRateInHz, int channelConfig, int audioFormat);
1220
1221    private native final int native_get_session_id();
1222
1223    private native final int native_attachAuxEffect(int effectId);
1224    private native final void native_setAuxEffectSendLevel(float level);
1225
1226    //---------------------------------------------------------
1227    // Utility methods
1228    //------------------
1229
1230    private static void logd(String msg) {
1231        Log.d(TAG, "[ android.media.AudioTrack ] " + msg);
1232    }
1233
1234    private static void loge(String msg) {
1235        Log.e(TAG, "[ android.media.AudioTrack ] " + msg);
1236    }
1237
1238}
1239