AudioTrack.java revision b282e08ab641d4fc74d0324b7a0ce30926638dd5
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
344    // Convenience method for the constructor's parameter checks.
345    // This is where constructor IllegalArgumentException-s are thrown
346    // postconditions:
347    //    mStreamType is valid
348    //    mChannelCount is valid
349    //    mChannels is valid
350    //    mAudioFormat is valid
351    //    mSampleRate is valid
352    //    mDataLoadMode is valid
353    private void audioParamCheck(int streamType, int sampleRateInHz,
354                                 int channelConfig, int audioFormat, int mode) {
355
356        //--------------
357        // stream type
358        if( (streamType != AudioManager.STREAM_ALARM) && (streamType != AudioManager.STREAM_MUSIC)
359           && (streamType != AudioManager.STREAM_RING) && (streamType != AudioManager.STREAM_SYSTEM)
360           && (streamType != AudioManager.STREAM_VOICE_CALL)
361           && (streamType != AudioManager.STREAM_NOTIFICATION)
362           && (streamType != AudioManager.STREAM_BLUETOOTH_SCO)
363           && (streamType != AudioManager.STREAM_DTMF)) {
364            throw (new IllegalArgumentException("Invalid stream type."));
365        } else {
366            mStreamType = streamType;
367        }
368
369        //--------------
370        // sample rate, note these values are subject to change
371        if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) {
372            throw (new IllegalArgumentException(sampleRateInHz
373                    + "Hz is not a supported sample rate."));
374        } else {
375            mSampleRate = sampleRateInHz;
376        }
377
378        //--------------
379        // channel config
380        mChannelConfiguration = channelConfig;
381
382        switch (channelConfig) {
383        case AudioFormat.CHANNEL_OUT_DEFAULT: //AudioFormat.CHANNEL_CONFIGURATION_DEFAULT
384        case AudioFormat.CHANNEL_OUT_MONO:
385        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
386            mChannelCount = 1;
387            mChannels = AudioFormat.CHANNEL_OUT_MONO;
388            break;
389        case AudioFormat.CHANNEL_OUT_STEREO:
390        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
391            mChannelCount = 2;
392            mChannels = AudioFormat.CHANNEL_OUT_STEREO;
393            break;
394        default:
395            mChannelCount = 0;
396            mChannels = AudioFormat.CHANNEL_INVALID;
397            mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_INVALID;
398            throw(new IllegalArgumentException("Unsupported channel configuration."));
399        }
400
401        //--------------
402        // audio format
403        switch (audioFormat) {
404        case AudioFormat.ENCODING_DEFAULT:
405            mAudioFormat = AudioFormat.ENCODING_PCM_16BIT;
406            break;
407        case AudioFormat.ENCODING_PCM_16BIT:
408        case AudioFormat.ENCODING_PCM_8BIT:
409            mAudioFormat = audioFormat;
410            break;
411        default:
412            mAudioFormat = AudioFormat.ENCODING_INVALID;
413            throw(new IllegalArgumentException("Unsupported sample encoding."
414                + " Should be ENCODING_PCM_8BIT or ENCODING_PCM_16BIT."));
415        }
416
417        //--------------
418        // audio load mode
419        if ( (mode != MODE_STREAM) && (mode != MODE_STATIC) ) {
420            throw(new IllegalArgumentException("Invalid mode."));
421        } else {
422            mDataLoadMode = mode;
423        }
424    }
425
426
427    // Convenience method for the contructor's audio buffer size check.
428    // preconditions:
429    //    mChannelCount is valid
430    //    mAudioFormat is valid
431    // postcondition:
432    //    mNativeBufferSizeInBytes is valid (multiple of frame size, positive)
433    private void audioBuffSizeCheck(int audioBufferSize) {
434        // NB: this section is only valid with PCM data.
435        //     To update when supporting compressed formats
436        int frameSizeInBytes = mChannelCount
437                * (mAudioFormat == AudioFormat.ENCODING_PCM_8BIT ? 1 : 2);
438        if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) {
439            throw (new IllegalArgumentException("Invalid audio buffer size."));
440        }
441
442        mNativeBufferSizeInBytes = audioBufferSize;
443    }
444
445
446    /**
447     * Releases the native AudioTrack resources.
448     */
449    public void release() {
450        // even though native_release() stops the native AudioTrack, we need to stop
451        // AudioTrack subclasses too.
452        try {
453            stop();
454        } catch(IllegalStateException ise) {
455            // don't raise an exception, we're releasing the resources.
456        }
457        native_release();
458        mState = STATE_UNINITIALIZED;
459    }
460
461    @Override
462    protected void finalize() {
463        native_finalize();
464    }
465
466    //--------------------------------------------------------------------------
467    // Getters
468    //--------------------
469    /**
470     * Returns the minimum valid volume value. Volume values set under this one will
471     * be clamped at this value.
472     * @return the minimum volume expressed as a linear attenuation.
473     */
474    static public float getMinVolume() {
475        return AudioTrack.VOLUME_MIN;
476    }
477
478    /**
479     * Returns the maximum valid volume value. Volume values set above this one will
480     * be clamped at this value.
481     * @return the maximum volume expressed as a linear attenuation.
482     */
483    static public float getMaxVolume() {
484        return AudioTrack.VOLUME_MAX;
485    }
486
487    /**
488     * Returns the configured audio data sample rate in Hz
489     */
490    public int getSampleRate() {
491        return mSampleRate;
492    }
493
494    /**
495     * Returns the current playback rate in Hz.
496     */
497    public int getPlaybackRate() {
498        return native_get_playback_rate();
499    }
500
501    /**
502     * Returns the configured audio data format. See {@link AudioFormat#ENCODING_PCM_16BIT}
503     * and {@link AudioFormat#ENCODING_PCM_8BIT}.
504     */
505    public int getAudioFormat() {
506        return mAudioFormat;
507    }
508
509    /**
510     * Returns the type of audio stream this AudioTrack is configured for.
511     * Compare the result against {@link AudioManager#STREAM_VOICE_CALL},
512     * {@link AudioManager#STREAM_SYSTEM}, {@link AudioManager#STREAM_RING},
513     * {@link AudioManager#STREAM_MUSIC}, {@link AudioManager#STREAM_ALARM},
514     * {@link AudioManager#STREAM_NOTIFICATION}, or {@link AudioManager#STREAM_DTMF}.
515     */
516    public int getStreamType() {
517        return mStreamType;
518    }
519
520    /**
521     * Returns the configured channel configuration.
522
523     * See {@link AudioFormat#CHANNEL_OUT_MONO}
524     * and {@link AudioFormat#CHANNEL_OUT_STEREO}.
525     */
526    public int getChannelConfiguration() {
527        return mChannelConfiguration;
528    }
529
530    /**
531     * Returns the configured number of channels.
532     */
533    public int getChannelCount() {
534        return mChannelCount;
535    }
536
537    /**
538     * Returns the state of the AudioTrack instance. This is useful after the
539     * AudioTrack instance has been created to check if it was initialized
540     * properly. This ensures that the appropriate hardware resources have been
541     * acquired.
542     * @see #STATE_INITIALIZED
543     * @see #STATE_NO_STATIC_DATA
544     * @see #STATE_UNINITIALIZED
545     */
546    public int getState() {
547        return mState;
548    }
549
550    /**
551     * Returns the playback state of the AudioTrack instance.
552     * @see #PLAYSTATE_STOPPED
553     * @see #PLAYSTATE_PAUSED
554     * @see #PLAYSTATE_PLAYING
555     */
556    public int getPlayState() {
557        synchronized (mPlayStateLock) {
558            return mPlayState;
559        }
560    }
561
562    /**
563     *  Returns the native frame count used by the hardware.
564     */
565    protected int getNativeFrameCount() {
566        return native_get_native_frame_count();
567    }
568
569    /**
570     * Returns marker position expressed in frames.
571     */
572    public int getNotificationMarkerPosition() {
573        return native_get_marker_pos();
574    }
575
576    /**
577     * Returns the notification update period expressed in frames.
578     */
579    public int getPositionNotificationPeriod() {
580        return native_get_pos_update_period();
581    }
582
583    /**
584     * Returns the playback head position expressed in frames
585     */
586    public int getPlaybackHeadPosition() {
587        return native_get_position();
588    }
589
590    /**
591     *  Returns the hardware output sample rate
592     */
593    static public int getNativeOutputSampleRate(int streamType) {
594        return native_get_output_sample_rate(streamType);
595    }
596
597    /**
598     * Returns the minimum buffer size required for the successful creation of an AudioTrack
599     * object to be created in the {@link #MODE_STREAM} mode. Note that this size doesn't
600     * guarantee a smooth playback under load, and higher values should be chosen according to
601     * the expected frequency at which the buffer will be refilled with additional data to play.
602     * @param sampleRateInHz the sample rate expressed in Hertz.
603     * @param channelConfig describes the configuration of the audio channels.
604     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
605     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
606     * @param audioFormat the format in which the audio data is represented.
607     *   See {@link AudioFormat#ENCODING_PCM_16BIT} and
608     *   {@link AudioFormat#ENCODING_PCM_8BIT}
609     * @return {@link #ERROR_BAD_VALUE} if an invalid parameter was passed,
610     *   or {@link #ERROR} if the implementation was unable to query the hardware for its output
611     *     properties,
612     *   or the minimum buffer size expressed in bytes.
613     */
614    static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) {
615        int channelCount = 0;
616        switch(channelConfig) {
617        case AudioFormat.CHANNEL_OUT_MONO:
618        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
619            channelCount = 1;
620            break;
621        case AudioFormat.CHANNEL_OUT_STEREO:
622        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
623            channelCount = 2;
624            break;
625        default:
626            loge("getMinBufferSize(): Invalid channel configuration.");
627            return AudioTrack.ERROR_BAD_VALUE;
628        }
629
630        if ((audioFormat != AudioFormat.ENCODING_PCM_16BIT)
631            && (audioFormat != AudioFormat.ENCODING_PCM_8BIT)) {
632            loge("getMinBufferSize(): Invalid audio format.");
633            return AudioTrack.ERROR_BAD_VALUE;
634        }
635
636        // sample rate, note these values are subject to change
637        if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) {
638            loge("getMinBufferSize(): " + sampleRateInHz +"Hz is not a supported sample rate.");
639            return AudioTrack.ERROR_BAD_VALUE;
640        }
641
642        int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat);
643        if ((size == -1) || (size == 0)) {
644            loge("getMinBufferSize(): error querying hardware");
645            return AudioTrack.ERROR;
646        }
647        else {
648            return size;
649        }
650    }
651
652    /**
653     * Returns the audio session ID.
654     *
655     * @return the ID of the audio session this AudioTrack belongs to.
656     */
657    public int getAudioSessionId() {
658        return mSessionId;
659    }
660
661    //--------------------------------------------------------------------------
662    // Initialization / configuration
663    //--------------------
664    /**
665     * Sets the listener the AudioTrack notifies when a previously set marker is reached or
666     * for each periodic playback head position update.
667     * Notifications will be received in the same thread as the one in which the AudioTrack
668     * instance was created.
669     * @param listener
670     */
671    public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener) {
672        setPlaybackPositionUpdateListener(listener, null);
673    }
674
675    /**
676     * Sets the listener the AudioTrack notifies when a previously set marker is reached or
677     * for each periodic playback head position update.
678     * Use this method to receive AudioTrack events in the Handler associated with another
679     * thread than the one in which you created the AudioTrack instance.
680     * @param listener
681     * @param handler the Handler that will receive the event notification messages.
682     */
683    public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener,
684                                                    Handler handler) {
685        synchronized (mPositionListenerLock) {
686            mPositionListener = listener;
687        }
688        if (listener != null) {
689            mEventHandlerDelegate = new NativeEventHandlerDelegate(this, handler);
690        }
691
692    }
693
694
695
696     /**
697     * Sets the specified left/right output volume values on the AudioTrack. Values are clamped
698     * to the ({@link #getMinVolume()}, {@link #getMaxVolume()}) interval if outside this range.
699     * @param leftVolume output attenuation for the left channel. A value of 0.0f is silence,
700     *      a value of 1.0f is no attenuation.
701     * @param rightVolume output attenuation for the right channel
702     * @return error code or success, see {@link #SUCCESS},
703     *    {@link #ERROR_INVALID_OPERATION}
704     */
705    public int setStereoVolume(float leftVolume, float rightVolume) {
706        if (mState != STATE_INITIALIZED) {
707            return ERROR_INVALID_OPERATION;
708        }
709
710        // clamp the volumes
711        if (leftVolume < getMinVolume()) {
712            leftVolume = getMinVolume();
713        }
714        if (leftVolume > getMaxVolume()) {
715            leftVolume = getMaxVolume();
716        }
717        if (rightVolume < getMinVolume()) {
718            rightVolume = getMinVolume();
719        }
720        if (rightVolume > getMaxVolume()) {
721            rightVolume = getMaxVolume();
722        }
723
724        native_setVolume(leftVolume, rightVolume);
725
726        return SUCCESS;
727    }
728
729
730    /**
731     * Sets the playback sample rate for this track. This sets the sampling rate at which
732     * the audio data will be consumed and played back, not the original sampling rate of the
733     * content. Setting it to half the sample rate of the content will cause the playback to
734     * last twice as long, but will also result in a negative pitch shift.
735     * The valid sample rate range is from 1Hz to twice the value returned by
736     * {@link #getNativeOutputSampleRate(int)}.
737     * @param sampleRateInHz the sample rate expressed in Hz
738     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
739     *    {@link #ERROR_INVALID_OPERATION}
740     */
741    public int setPlaybackRate(int sampleRateInHz) {
742        if (mState != STATE_INITIALIZED) {
743            return ERROR_INVALID_OPERATION;
744        }
745        if (sampleRateInHz <= 0) {
746            return ERROR_BAD_VALUE;
747        }
748        return native_set_playback_rate(sampleRateInHz);
749    }
750
751
752    /**
753     * Sets the position of the notification marker.
754     * @param markerInFrames marker in frames
755     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
756     *  {@link #ERROR_INVALID_OPERATION}
757     */
758    public int setNotificationMarkerPosition(int markerInFrames) {
759        if (mState != STATE_INITIALIZED) {
760            return ERROR_INVALID_OPERATION;
761        }
762        return native_set_marker_pos(markerInFrames);
763    }
764
765
766    /**
767     * Sets the period for the periodic notification event.
768     * @param periodInFrames update period expressed in frames
769     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION}
770     */
771    public int setPositionNotificationPeriod(int periodInFrames) {
772        if (mState != STATE_INITIALIZED) {
773            return ERROR_INVALID_OPERATION;
774        }
775        return native_set_pos_update_period(periodInFrames);
776    }
777
778
779    /**
780     * Sets the playback head position. The track must be stopped for the position to be changed.
781     * @param positionInFrames playback head position expressed in frames
782     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
783     *    {@link #ERROR_INVALID_OPERATION}
784     */
785    public int setPlaybackHeadPosition(int positionInFrames) {
786        synchronized(mPlayStateLock) {
787            if ((mPlayState == PLAYSTATE_STOPPED) || (mPlayState == PLAYSTATE_PAUSED)) {
788                return native_set_position(positionInFrames);
789            } else {
790                return ERROR_INVALID_OPERATION;
791            }
792        }
793    }
794
795    /**
796     * Sets the loop points and the loop count. The loop can be infinite.
797     * @param startInFrames loop start marker expressed in frames
798     * @param endInFrames loop end marker expressed in frames
799     * @param loopCount the number of times the loop is looped.
800     *    A value of -1 means infinite looping.
801     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
802     *    {@link #ERROR_INVALID_OPERATION}
803     */
804    public int setLoopPoints(int startInFrames, int endInFrames, int loopCount) {
805        if (mDataLoadMode == MODE_STREAM) {
806            return ERROR_INVALID_OPERATION;
807        }
808        return native_set_loop(startInFrames, endInFrames, loopCount);
809    }
810
811    /**
812     * Sets the initialization state of the instance. To be used in an AudioTrack subclass
813     * constructor to set a subclass-specific post-initialization state.
814     * @param state the state of the AudioTrack instance
815     */
816    protected void setState(int state) {
817        mState = state;
818    }
819
820
821    //---------------------------------------------------------
822    // Transport control methods
823    //--------------------
824    /**
825     * Starts playing an AudioTrack.
826     *
827     * @throws IllegalStateException
828     */
829    public void play()
830    throws IllegalStateException {
831        if (mState != STATE_INITIALIZED) {
832            throw(new IllegalStateException("play() called on uninitialized AudioTrack."));
833        }
834
835        synchronized(mPlayStateLock) {
836            native_start();
837            mPlayState = PLAYSTATE_PLAYING;
838        }
839    }
840
841    /**
842     * Stops playing the audio data.
843     *
844     * @throws IllegalStateException
845     */
846    public void stop()
847    throws IllegalStateException {
848        if (mState != STATE_INITIALIZED) {
849            throw(new IllegalStateException("stop() called on uninitialized AudioTrack."));
850        }
851
852        // stop playing
853        synchronized(mPlayStateLock) {
854            native_stop();
855            mPlayState = PLAYSTATE_STOPPED;
856        }
857    }
858
859    /**
860     * Pauses the playback of the audio data. Data that has not been played
861     * back will not be discarded. Subsequent calls to {@link #play} will play
862     * this data back.
863     *
864     * @throws IllegalStateException
865     */
866    public void pause()
867    throws IllegalStateException {
868        if (mState != STATE_INITIALIZED) {
869            throw(new IllegalStateException("pause() called on uninitialized AudioTrack."));
870        }
871        //logd("pause()");
872
873        // pause playback
874        synchronized(mPlayStateLock) {
875            native_pause();
876            mPlayState = PLAYSTATE_PAUSED;
877        }
878    }
879
880
881    //---------------------------------------------------------
882    // Audio data supply
883    //--------------------
884
885    /**
886     * Flushes the audio data currently queued for playback. Any data that has
887     * not been played back will be discarded.
888     */
889    public void flush() {
890        if (mState == STATE_INITIALIZED) {
891            // flush the data in native layer
892            native_flush();
893        }
894
895    }
896
897    /**
898     * Writes the audio data to the audio hardware for playback. Will block until
899     * all data has been written to the audio mixer.
900     * Note that the actual playback of this data might occur after this function
901     * returns. This function is thread safe with respect to {@link #stop} calls,
902     * in which case all of the specified data might not be written to the mixer.
903     *
904     * @param audioData the array that holds the data to play.
905     * @param offsetInBytes the offset expressed in bytes in audioData where the data to play
906     *    starts.
907     * @param sizeInBytes the number of bytes to read in audioData after the offset.
908     * @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION}
909     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
910     *    the parameters don't resolve to valid data and indexes.
911     */
912
913    public int write(byte[] audioData, int offsetInBytes, int sizeInBytes) {
914        if ((mDataLoadMode == MODE_STATIC)
915                && (mState == STATE_NO_STATIC_DATA)
916                && (sizeInBytes > 0)) {
917            mState = STATE_INITIALIZED;
918        }
919
920        if (mState != STATE_INITIALIZED) {
921            return ERROR_INVALID_OPERATION;
922        }
923
924        if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0)
925                || (offsetInBytes + sizeInBytes > audioData.length)) {
926            return ERROR_BAD_VALUE;
927        }
928
929        return native_write_byte(audioData, offsetInBytes, sizeInBytes, mAudioFormat);
930    }
931
932
933    /**
934     * Writes the audio data to the audio hardware for playback. Will block until
935     * all data has been written to the audio mixer.
936     * Note that the actual playback of this data might occur after this function
937     * returns. This function is thread safe with respect to {@link #stop} calls,
938     * in which case all of the specified data might not be written to the mixer.
939     *
940     * @param audioData the array that holds the data to play.
941     * @param offsetInShorts the offset expressed in shorts in audioData where the data to play
942     *     starts.
943     * @param sizeInShorts the number of bytes to read in audioData after the offset.
944     * @return the number of shorts that were written or {@link #ERROR_INVALID_OPERATION}
945      *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
946      *    the parameters don't resolve to valid data and indexes.
947     */
948
949    public int write(short[] audioData, int offsetInShorts, int sizeInShorts) {
950        if ((mDataLoadMode == MODE_STATIC)
951                && (mState == STATE_NO_STATIC_DATA)
952                && (sizeInShorts > 0)) {
953            mState = STATE_INITIALIZED;
954        }
955
956        if (mState != STATE_INITIALIZED) {
957            return ERROR_INVALID_OPERATION;
958        }
959
960        if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0)
961                || (offsetInShorts + sizeInShorts > audioData.length)) {
962            return ERROR_BAD_VALUE;
963        }
964
965        return native_write_short(audioData, offsetInShorts, sizeInShorts, mAudioFormat);
966    }
967
968
969    /**
970     * Notifies the native resource to reuse the audio data already loaded in the native
971     * layer. This call is only valid with AudioTrack instances that don't use the streaming
972     * model.
973     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
974     *  {@link #ERROR_INVALID_OPERATION}
975     */
976    public int reloadStaticData() {
977        if (mDataLoadMode == MODE_STREAM) {
978            return ERROR_INVALID_OPERATION;
979        }
980        return native_reload_static();
981    }
982
983    //--------------------------------------------------------------------------
984    // Audio effects management
985    //--------------------
986
987    /**
988     * Attaches an auxiliary effect to the audio track. A typical auxiliary
989     * effect is a reverberation effect which can be applied on any sound source
990     * that directs a certain amount of its energy to this effect. This amount
991     * is defined by setAuxEffectSendLevel().
992     * {@see #setAuxEffectSendLevel(float)}.
993     * <p>After creating an auxiliary effect (e.g.
994     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
995     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling
996     * this method to attach the audio track to the effect.
997     * <p>To detach the effect from the audio track, call this method with a
998     * null effect id.
999     *
1000     * @param effectId system wide unique id of the effect to attach
1001     * @return error code or success, see {@link #SUCCESS},
1002     *    {@link #ERROR_INVALID_OPERATION}, {@link #ERROR_BAD_VALUE}
1003     */
1004    public int attachAuxEffect(int effectId) {
1005        if (mState != STATE_INITIALIZED) {
1006            return ERROR_INVALID_OPERATION;
1007        }
1008        return native_attachAuxEffect(effectId);
1009    }
1010
1011    /**
1012     * Sets the send level of the audio track to the attached auxiliary effect
1013     * {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1014     * <p>By default the send level is 0, so even if an effect is attached to the player
1015     * this method must be called for the effect to be applied.
1016     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1017     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1018     * so an appropriate conversion from linear UI input x to level is:
1019     * x == 0 -&gt; level = 0
1020     * 0 &lt; x &lt;= R -&gt; level = 10^(72*(x-R)/20/R)
1021     *
1022     * @param level send level scalar
1023     * @return error code or success, see {@link #SUCCESS},
1024     *    {@link #ERROR_INVALID_OPERATION}
1025     */
1026    public int setAuxEffectSendLevel(float level) {
1027        if (mState != STATE_INITIALIZED) {
1028            return ERROR_INVALID_OPERATION;
1029        }
1030        // clamp the level
1031        if (level < getMinVolume()) {
1032            level = getMinVolume();
1033        }
1034        if (level > getMaxVolume()) {
1035            level = getMaxVolume();
1036        }
1037        native_setAuxEffectSendLevel(level);
1038        return SUCCESS;
1039    }
1040
1041    //---------------------------------------------------------
1042    // Interface definitions
1043    //--------------------
1044    /**
1045     * Interface definition for a callback to be invoked when the playback head position of
1046     * an AudioTrack has reached a notification marker or has increased by a certain period.
1047     */
1048    public interface OnPlaybackPositionUpdateListener  {
1049        /**
1050         * Called on the listener to notify it that the previously set marker has been reached
1051         * by the playback head.
1052         */
1053        void onMarkerReached(AudioTrack track);
1054
1055        /**
1056         * Called on the listener to periodically notify it that the playback head has reached
1057         * a multiple of the notification period.
1058         */
1059        void onPeriodicNotification(AudioTrack track);
1060    }
1061
1062
1063    //---------------------------------------------------------
1064    // Inner classes
1065    //--------------------
1066    /**
1067     * Helper class to handle the forwarding of native events to the appropriate listener
1068     * (potentially) handled in a different thread
1069     */
1070    private class NativeEventHandlerDelegate {
1071        private final AudioTrack mAudioTrack;
1072        private final Handler mHandler;
1073
1074        NativeEventHandlerDelegate(AudioTrack track, Handler handler) {
1075            mAudioTrack = track;
1076            // find the looper for our new event handler
1077            Looper looper;
1078            if (handler != null) {
1079                looper = handler.getLooper();
1080            } else {
1081                // no given handler, use the looper the AudioTrack was created in
1082                looper = mInitializationLooper;
1083            }
1084
1085            // construct the event handler with this looper
1086            if (looper != null) {
1087                // implement the event handler delegate
1088                mHandler = new Handler(looper) {
1089                    @Override
1090                    public void handleMessage(Message msg) {
1091                        if (mAudioTrack == null) {
1092                            return;
1093                        }
1094                        OnPlaybackPositionUpdateListener listener = null;
1095                        synchronized (mPositionListenerLock) {
1096                            listener = mAudioTrack.mPositionListener;
1097                        }
1098                        switch(msg.what) {
1099                        case NATIVE_EVENT_MARKER:
1100                            if (listener != null) {
1101                                listener.onMarkerReached(mAudioTrack);
1102                            }
1103                            break;
1104                        case NATIVE_EVENT_NEW_POS:
1105                            if (listener != null) {
1106                                listener.onPeriodicNotification(mAudioTrack);
1107                            }
1108                            break;
1109                        default:
1110                            Log.e(TAG, "[ android.media.AudioTrack.NativeEventHandler ] " +
1111                                    "Unknown event type: " + msg.what);
1112                            break;
1113                        }
1114                    }
1115                };
1116            } else {
1117                mHandler = null;
1118            }
1119        }
1120
1121        Handler getHandler() {
1122            return mHandler;
1123        }
1124    }
1125
1126
1127    //---------------------------------------------------------
1128    // Java methods called from the native side
1129    //--------------------
1130    @SuppressWarnings("unused")
1131    private static void postEventFromNative(Object audiotrack_ref,
1132            int what, int arg1, int arg2, Object obj) {
1133        //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2);
1134        AudioTrack track = (AudioTrack)((WeakReference)audiotrack_ref).get();
1135        if (track == null) {
1136            return;
1137        }
1138
1139        if (track.mEventHandlerDelegate != null) {
1140            Message m =
1141                track.mEventHandlerDelegate.getHandler().obtainMessage(what, arg1, arg2, obj);
1142            track.mEventHandlerDelegate.getHandler().sendMessage(m);
1143        }
1144
1145    }
1146
1147
1148    //---------------------------------------------------------
1149    // Native methods called from the Java side
1150    //--------------------
1151
1152    private native final int native_setup(Object audiotrack_this,
1153            int streamType, int sampleRate, int nbChannels, int audioFormat,
1154            int buffSizeInBytes, int mode, int[] sessionId);
1155
1156    private native final void native_finalize();
1157
1158    private native final void native_release();
1159
1160    private native final void native_start();
1161
1162    private native final void native_stop();
1163
1164    private native final void native_pause();
1165
1166    private native final void native_flush();
1167
1168    private native final int native_write_byte(byte[] audioData,
1169                                               int offsetInBytes, int sizeInBytes, int format);
1170
1171    private native final int native_write_short(short[] audioData,
1172                                                int offsetInShorts, int sizeInShorts, int format);
1173
1174    private native final int native_reload_static();
1175
1176    private native final int native_get_native_frame_count();
1177
1178    private native final void native_setVolume(float leftVolume, float rightVolume);
1179
1180    private native final int native_set_playback_rate(int sampleRateInHz);
1181    private native final int native_get_playback_rate();
1182
1183    private native final int native_set_marker_pos(int marker);
1184    private native final int native_get_marker_pos();
1185
1186    private native final int native_set_pos_update_period(int updatePeriod);
1187    private native final int native_get_pos_update_period();
1188
1189    private native final int native_set_position(int position);
1190    private native final int native_get_position();
1191
1192    private native final int native_set_loop(int start, int end, int loopCount);
1193
1194    static private native final int native_get_output_sample_rate(int streamType);
1195    static private native final int native_get_min_buff_size(
1196            int sampleRateInHz, int channelConfig, int audioFormat);
1197
1198    private native final int native_get_session_id();
1199
1200    private native final int native_attachAuxEffect(int effectId);
1201    private native final void native_setAuxEffectSendLevel(float level);
1202
1203    //---------------------------------------------------------
1204    // Utility methods
1205    //------------------
1206
1207    private static void logd(String msg) {
1208        Log.d(TAG, "[ android.media.AudioTrack ] " + msg);
1209    }
1210
1211    private static void loge(String msg) {
1212        Log.e(TAG, "[ android.media.AudioTrack ] " + msg);
1213    }
1214
1215}
1216