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