AudioTrack.java revision 9e29086d5df800532e736d8f31e2b9159b102524
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.annotation.Retention;
20import java.lang.annotation.RetentionPolicy;
21import java.lang.ref.WeakReference;
22import java.lang.Math;
23import java.nio.ByteBuffer;
24import java.nio.ByteOrder;
25import java.nio.NioUtils;
26import java.util.Collection;
27
28import android.annotation.IntDef;
29import android.annotation.NonNull;
30import android.annotation.SystemApi;
31import android.app.ActivityThread;
32import android.app.AppOpsManager;
33import android.content.Context;
34import android.os.Handler;
35import android.os.IBinder;
36import android.os.Looper;
37import android.os.Message;
38import android.os.Process;
39import android.os.RemoteException;
40import android.os.ServiceManager;
41import android.util.ArrayMap;
42import android.util.Log;
43
44import com.android.internal.app.IAppOpsService;
45
46
47/**
48 * The AudioTrack class manages and plays a single audio resource for Java applications.
49 * It allows streaming of PCM audio buffers to the audio sink for playback. This is
50 * achieved by "pushing" the data to the AudioTrack object using one of the
51 *  {@link #write(byte[], int, int)}, {@link #write(short[], int, int)},
52 *  and {@link #write(float[], int, int, int)} methods.
53 *
54 * <p>An AudioTrack instance can operate under two modes: static or streaming.<br>
55 * In Streaming mode, the application writes a continuous stream of data to the AudioTrack, using
56 * one of the {@code write()} methods. These are blocking and return when the data has been
57 * transferred from the Java layer to the native layer and queued for playback. The streaming
58 * mode is most useful when playing blocks of audio data that for instance are:
59 *
60 * <ul>
61 *   <li>too big to fit in memory because of the duration of the sound to play,</li>
62 *   <li>too big to fit in memory because of the characteristics of the audio data
63 *         (high sampling rate, bits per sample ...)</li>
64 *   <li>received or generated while previously queued audio is playing.</li>
65 * </ul>
66 *
67 * The static mode should be chosen when dealing with short sounds that fit in memory and
68 * that need to be played with the smallest latency possible. The static mode will
69 * therefore be preferred for UI and game sounds that are played often, and with the
70 * smallest overhead possible.
71 *
72 * <p>Upon creation, an AudioTrack object initializes its associated audio buffer.
73 * The size of this buffer, specified during the construction, determines how long an AudioTrack
74 * can play before running out of data.<br>
75 * For an AudioTrack using the static mode, this size is the maximum size of the sound that can
76 * be played from it.<br>
77 * For the streaming mode, data will be written to the audio sink in chunks of
78 * sizes less than or equal to the total buffer size.
79 *
80 * AudioTrack is not final and thus permits subclasses, but such use is not recommended.
81 */
82public class AudioTrack
83{
84    //---------------------------------------------------------
85    // Constants
86    //--------------------
87    /** Minimum value for a linear gain or auxiliary effect level.
88     *  This value must be exactly equal to 0.0f; do not change it.
89     */
90    private static final float GAIN_MIN = 0.0f;
91    /** Maximum value for a linear gain or auxiliary effect level.
92     *  This value must be greater than or equal to 1.0f.
93     */
94    private static final float GAIN_MAX = 1.0f;
95
96    /** Minimum value for sample rate */
97    private static final int SAMPLE_RATE_HZ_MIN = 4000;
98    /** Maximum value for sample rate */
99    private static final int SAMPLE_RATE_HZ_MAX = 96000;
100
101    /** Maximum value for AudioTrack channel count */
102    private static final int CHANNEL_COUNT_MAX = 8;
103
104    /** indicates AudioTrack state is stopped */
105    public static final int PLAYSTATE_STOPPED = 1;  // matches SL_PLAYSTATE_STOPPED
106    /** indicates AudioTrack state is paused */
107    public static final int PLAYSTATE_PAUSED  = 2;  // matches SL_PLAYSTATE_PAUSED
108    /** indicates AudioTrack state is playing */
109    public static final int PLAYSTATE_PLAYING = 3;  // matches SL_PLAYSTATE_PLAYING
110
111    // keep these values in sync with android_media_AudioTrack.cpp
112    /**
113     * Creation mode where audio data is transferred from Java to the native layer
114     * only once before the audio starts playing.
115     */
116    public static final int MODE_STATIC = 0;
117    /**
118     * Creation mode where audio data is streamed from Java to the native layer
119     * as the audio is playing.
120     */
121    public static final int MODE_STREAM = 1;
122
123    /** @hide */
124    @IntDef({
125        MODE_STATIC,
126        MODE_STREAM
127    })
128    @Retention(RetentionPolicy.SOURCE)
129    public @interface TransferMode {}
130
131    /**
132     * State of an AudioTrack that was not successfully initialized upon creation.
133     */
134    public static final int STATE_UNINITIALIZED = 0;
135    /**
136     * State of an AudioTrack that is ready to be used.
137     */
138    public static final int STATE_INITIALIZED   = 1;
139    /**
140     * State of a successfully initialized AudioTrack that uses static data,
141     * but that hasn't received that data yet.
142     */
143    public static final int STATE_NO_STATIC_DATA = 2;
144
145    /**
146     * Denotes a successful operation.
147     */
148    public  static final int SUCCESS                               = AudioSystem.SUCCESS;
149    /**
150     * Denotes a generic operation failure.
151     */
152    public  static final int ERROR                                 = AudioSystem.ERROR;
153    /**
154     * Denotes a failure due to the use of an invalid value.
155     */
156    public  static final int ERROR_BAD_VALUE                       = AudioSystem.BAD_VALUE;
157    /**
158     * Denotes a failure due to the improper use of a method.
159     */
160    public  static final int ERROR_INVALID_OPERATION               = AudioSystem.INVALID_OPERATION;
161
162    // Error codes:
163    // to keep in sync with frameworks/base/core/jni/android_media_AudioTrack.cpp
164    private static final int ERROR_NATIVESETUP_AUDIOSYSTEM         = -16;
165    private static final int ERROR_NATIVESETUP_INVALIDCHANNELMASK  = -17;
166    private static final int ERROR_NATIVESETUP_INVALIDFORMAT       = -18;
167    private static final int ERROR_NATIVESETUP_INVALIDSTREAMTYPE   = -19;
168    private static final int ERROR_NATIVESETUP_NATIVEINITFAILED    = -20;
169
170    // Events:
171    // to keep in sync with frameworks/av/include/media/AudioTrack.h
172    /**
173     * Event id denotes when playback head has reached a previously set marker.
174     */
175    private static final int NATIVE_EVENT_MARKER  = 3;
176    /**
177     * Event id denotes when previously set update period has elapsed during playback.
178     */
179    private static final int NATIVE_EVENT_NEW_POS = 4;
180
181    /**
182     * Event id denotes when the routing changes.
183     */
184    private final static int NATIVE_EVENT_ROUTING_CHANGE = 1000;
185
186
187    private final static String TAG = "android.media.AudioTrack";
188
189
190    /** @hide */
191    @IntDef({
192        WRITE_BLOCKING,
193        WRITE_NON_BLOCKING
194    })
195    @Retention(RetentionPolicy.SOURCE)
196    public @interface WriteMode {}
197
198    /**
199     * The write mode indicating the write operation will block until all data has been written,
200     * to be used in {@link #write(ByteBuffer, int, int)}
201     */
202    public final static int WRITE_BLOCKING = 0;
203    /**
204     * The write mode indicating the write operation will return immediately after
205     * queuing as much audio data for playback as possible without blocking, to be used in
206     * {@link #write(ByteBuffer, int, int)}.
207     */
208    public final static int WRITE_NON_BLOCKING = 1;
209
210    //--------------------------------------------------------------------------
211    // Member variables
212    //--------------------
213    /**
214     * Indicates the state of the AudioTrack instance.
215     */
216    private int mState = STATE_UNINITIALIZED;
217    /**
218     * Indicates the play state of the AudioTrack instance.
219     */
220    private int mPlayState = PLAYSTATE_STOPPED;
221    /**
222     * Lock to make sure mPlayState updates are reflecting the actual state of the object.
223     */
224    private final Object mPlayStateLock = new Object();
225    /**
226     * Sizes of the native audio buffer.
227     * These values are set during construction and can be stale.
228     * To obtain the current native audio buffer frame count use {@link #getNativeFrameCount()}.
229     */
230    private int mNativeBufferSizeInBytes = 0;
231    private int mNativeBufferSizeInFrames = 0;
232    /**
233     * Handler for events coming from the native code.
234     */
235    private NativePositionEventHandlerDelegate mEventHandlerDelegate;
236    /**
237     * Looper associated with the thread that creates the AudioTrack instance.
238     */
239    private final Looper mInitializationLooper;
240    /**
241     * The audio data source sampling rate in Hz.
242     */
243    private int mSampleRate; // initialized by all constructors
244    /**
245     * The number of audio output channels (1 is mono, 2 is stereo).
246     */
247    private int mChannelCount = 1;
248    /**
249     * The audio channel mask used for calling native AudioTrack
250     */
251    private int mChannels = AudioFormat.CHANNEL_OUT_MONO;
252
253    /**
254     * The type of the audio stream to play. See
255     *   {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM},
256     *   {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC},
257     *   {@link AudioManager#STREAM_ALARM}, {@link AudioManager#STREAM_NOTIFICATION}, and
258     *   {@link AudioManager#STREAM_DTMF}.
259     */
260    private int mStreamType = AudioManager.STREAM_MUSIC;
261
262    private final AudioAttributes mAttributes;
263    /**
264     * The way audio is consumed by the audio sink, streaming or static.
265     */
266    private int mDataLoadMode = MODE_STREAM;
267    /**
268     * The current channel position mask, as specified on AudioTrack creation.
269     * Can be set simultaneously with channel index mask {@link #mChannelIndexMask}.
270     * May be set to {@link AudioFormat#CHANNEL_INVALID} if a channel index mask is specified.
271     */
272    private int mChannelConfiguration = AudioFormat.CHANNEL_OUT_MONO;
273    /**
274     * The current audio channel index configuration (if specified).
275     */
276    private int mChannelIndexMask = 0;
277    /**
278     * The encoding of the audio samples.
279     * @see AudioFormat#ENCODING_PCM_8BIT
280     * @see AudioFormat#ENCODING_PCM_16BIT
281     * @see AudioFormat#ENCODING_PCM_FLOAT
282     */
283    private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT;
284    /**
285     * Audio session ID
286     */
287    private int mSessionId = AudioSystem.AUDIO_SESSION_ALLOCATE;
288    /**
289     * Reference to the app-ops service.
290     */
291    private final IAppOpsService mAppOps;
292    /**
293     * HW_AV_SYNC track AV Sync Header
294     */
295    private ByteBuffer mAvSyncHeader = null;
296    /**
297     * HW_AV_SYNC track audio data bytes remaining to write after current AV sync header
298     */
299    private int mAvSyncBytesRemaining = 0;
300
301    //--------------------------------
302    // Used exclusively by native code
303    //--------------------
304    /**
305     * Accessed by native methods: provides access to C++ AudioTrack object.
306     */
307    @SuppressWarnings("unused")
308    private long mNativeTrackInJavaObj;
309    /**
310     * Accessed by native methods: provides access to the JNI data (i.e. resources used by
311     * the native AudioTrack object, but not stored in it).
312     */
313    @SuppressWarnings("unused")
314    private long mJniData;
315
316
317    //--------------------------------------------------------------------------
318    // Constructor, Finalize
319    //--------------------
320    /**
321     * Class constructor.
322     * @param streamType the type of the audio stream. See
323     *   {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM},
324     *   {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC},
325     *   {@link AudioManager#STREAM_ALARM}, and {@link AudioManager#STREAM_NOTIFICATION}.
326     * @param sampleRateInHz the initial source sample rate expressed in Hz.
327     * @param channelConfig describes the configuration of the audio channels.
328     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
329     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
330     * @param audioFormat the format in which the audio data is represented.
331     *   See {@link AudioFormat#ENCODING_PCM_16BIT},
332     *   {@link AudioFormat#ENCODING_PCM_8BIT},
333     *   and {@link AudioFormat#ENCODING_PCM_FLOAT}.
334     * @param bufferSizeInBytes the total size (in bytes) of the internal buffer where audio data is
335     *   read from for playback. This should be a multiple of the frame size in bytes.
336     *   <p> If the track's creation mode is {@link #MODE_STATIC},
337     *   this is the maximum length sample, or audio clip, that can be played by this instance.
338     *   <p> If the track's creation mode is {@link #MODE_STREAM},
339     *   this should be the desired buffer size
340     *   for the <code>AudioTrack</code> to satisfy the application's
341     *   natural latency requirements.
342     *   If <code>bufferSizeInBytes</code> is less than the
343     *   minimum buffer size for the output sink, it is automatically increased to the minimum
344     *   buffer size.
345     *   The method {@link #getNativeFrameCount()} returns the
346     *   actual size in frames of the native buffer created, which
347     *   determines the frequency to write
348     *   to the streaming <code>AudioTrack</code> to avoid underrun.
349     * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM}
350     * @throws java.lang.IllegalArgumentException
351     */
352    public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat,
353            int bufferSizeInBytes, int mode)
354    throws IllegalArgumentException {
355        this(streamType, sampleRateInHz, channelConfig, audioFormat,
356                bufferSizeInBytes, mode, AudioSystem.AUDIO_SESSION_ALLOCATE);
357    }
358
359    /**
360     * Class constructor with audio session. Use this constructor when the AudioTrack must be
361     * attached to a particular audio session. The primary use of the audio session ID is to
362     * associate audio effects to a particular instance of AudioTrack: if an audio session ID
363     * is provided when creating an AudioEffect, this effect will be applied only to audio tracks
364     * and media players in the same session and not to the output mix.
365     * When an AudioTrack is created without specifying a session, it will create its own session
366     * which can be retrieved by calling the {@link #getAudioSessionId()} method.
367     * If a non-zero session ID is provided, this AudioTrack will share effects attached to this
368     * session
369     * with all other media players or audio tracks in the same session, otherwise a new session
370     * will be created for this track if none is supplied.
371     * @param streamType the type of the audio stream. See
372     *   {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM},
373     *   {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC},
374     *   {@link AudioManager#STREAM_ALARM}, and {@link AudioManager#STREAM_NOTIFICATION}.
375     * @param sampleRateInHz the initial source sample rate expressed in Hz.
376     * @param channelConfig describes the configuration of the audio channels.
377     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
378     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
379     * @param audioFormat the format in which the audio data is represented.
380     *   See {@link AudioFormat#ENCODING_PCM_16BIT} and
381     *   {@link AudioFormat#ENCODING_PCM_8BIT},
382     *   and {@link AudioFormat#ENCODING_PCM_FLOAT}.
383     * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read
384     *   from for playback. If using the AudioTrack in streaming mode, you can write data into
385     *   this buffer in smaller chunks than this size. If using the AudioTrack in static mode,
386     *   this is the maximum size of the sound that will be played for this instance.
387     *   See {@link #getMinBufferSize(int, int, int)} to determine the minimum required buffer size
388     *   for the successful creation of an AudioTrack instance in streaming mode. Using values
389     *   smaller than getMinBufferSize() will result in an initialization failure.
390     * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM}
391     * @param sessionId Id of audio session the AudioTrack must be attached to
392     * @throws java.lang.IllegalArgumentException
393     */
394    public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat,
395            int bufferSizeInBytes, int mode, int sessionId)
396    throws IllegalArgumentException {
397        // mState already == STATE_UNINITIALIZED
398        this((new AudioAttributes.Builder())
399                    .setLegacyStreamType(streamType)
400                    .build(),
401                (new AudioFormat.Builder())
402                    .setChannelMask(channelConfig)
403                    .setEncoding(audioFormat)
404                    .setSampleRate(sampleRateInHz)
405                    .build(),
406                bufferSizeInBytes,
407                mode, sessionId);
408    }
409
410    /**
411     * Class constructor with {@link AudioAttributes} and {@link AudioFormat}.
412     * @param attributes a non-null {@link AudioAttributes} instance.
413     * @param format a non-null {@link AudioFormat} instance describing the format of the data
414     *     that will be played through this AudioTrack. See {@link AudioFormat.Builder} for
415     *     configuring the audio format parameters such as encoding, channel mask and sample rate.
416     * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read
417     *   from for playback. If using the AudioTrack in streaming mode, you can write data into
418     *   this buffer in smaller chunks than this size. If using the AudioTrack in static mode,
419     *   this is the maximum size of the sound that will be played for this instance.
420     *   See {@link #getMinBufferSize(int, int, int)} to determine the minimum required buffer size
421     *   for the successful creation of an AudioTrack instance in streaming mode. Using values
422     *   smaller than getMinBufferSize() will result in an initialization failure.
423     * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM}.
424     * @param sessionId ID of audio session the AudioTrack must be attached to, or
425     *   {@link AudioManager#AUDIO_SESSION_ID_GENERATE} if the session isn't known at construction
426     *   time. See also {@link AudioManager#generateAudioSessionId()} to obtain a session ID before
427     *   construction.
428     * @throws IllegalArgumentException
429     */
430    public AudioTrack(AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes,
431            int mode, int sessionId)
432                    throws IllegalArgumentException {
433        // mState already == STATE_UNINITIALIZED
434
435        if (attributes == null) {
436            throw new IllegalArgumentException("Illegal null AudioAttributes");
437        }
438        if (format == null) {
439            throw new IllegalArgumentException("Illegal null AudioFormat");
440        }
441
442        // remember which looper is associated with the AudioTrack instantiation
443        Looper looper;
444        if ((looper = Looper.myLooper()) == null) {
445            looper = Looper.getMainLooper();
446        }
447
448        int rate = 0;
449        if ((format.getPropertySetMask() & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE) != 0)
450        {
451            rate = format.getSampleRate();
452        } else {
453            rate = AudioSystem.getPrimaryOutputSamplingRate();
454            if (rate <= 0) {
455                rate = 44100;
456            }
457        }
458        int channelIndexMask = 0;
459        if ((format.getPropertySetMask()
460                & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_INDEX_MASK) != 0) {
461            channelIndexMask = format.getChannelIndexMask();
462        }
463        int channelMask = 0;
464        if ((format.getPropertySetMask()
465                & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK) != 0) {
466            channelMask = format.getChannelMask();
467        } else if (channelIndexMask == 0) { // if no masks at all, use stereo
468            channelMask = AudioFormat.CHANNEL_OUT_FRONT_LEFT
469                    | AudioFormat.CHANNEL_OUT_FRONT_RIGHT;
470        }
471        int encoding = AudioFormat.ENCODING_DEFAULT;
472        if ((format.getPropertySetMask() & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_ENCODING) != 0) {
473            encoding = format.getEncoding();
474        }
475        audioParamCheck(rate, channelMask, channelIndexMask, encoding, mode);
476        mStreamType = AudioSystem.STREAM_DEFAULT;
477
478        audioBuffSizeCheck(bufferSizeInBytes);
479
480        mInitializationLooper = looper;
481        IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
482        mAppOps = IAppOpsService.Stub.asInterface(b);
483
484        mAttributes = (new AudioAttributes.Builder(attributes).build());
485
486        if (sessionId < 0) {
487            throw new IllegalArgumentException("Invalid audio session ID: "+sessionId);
488        }
489
490        int[] session = new int[1];
491        session[0] = sessionId;
492        // native initialization
493        int initResult = native_setup(new WeakReference<AudioTrack>(this), mAttributes,
494                mSampleRate, mChannels, mAudioFormat,
495                mNativeBufferSizeInBytes, mDataLoadMode, session);
496        if (initResult != SUCCESS) {
497            loge("Error code "+initResult+" when initializing AudioTrack.");
498            return; // with mState == STATE_UNINITIALIZED
499        }
500
501        mSessionId = session[0];
502
503        if (mDataLoadMode == MODE_STATIC) {
504            mState = STATE_NO_STATIC_DATA;
505        } else {
506            mState = STATE_INITIALIZED;
507        }
508    }
509
510    /**
511     * Builder class for {@link AudioTrack} objects.
512     * Use this class to configure and create an <code>AudioTrack</code> instance. By setting audio
513     * attributes and audio format parameters, you indicate which of those vary from the default
514     * behavior on the device.
515     * <p> Here is an example where <code>Builder</code> is used to specify all {@link AudioFormat}
516     * parameters, to be used by a new <code>AudioTrack</code> instance:
517     *
518     * <pre class="prettyprint">
519     * AudioTrack player = new AudioTrack.Builder()
520     *         .setAudioAttributes(new AudioAttributes.Builder()
521     *                  .setUsage(AudioAttributes.USAGE_ALARM)
522     *                  .setContentType(CONTENT_TYPE_MUSIC)
523     *                  .build())
524     *         .setAudioFormat(new AudioFormat.Builder()
525     *                 .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
526     *                 .setSampleRate(441000)
527     *                 .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
528     *                 .build())
529     *         .setBufferSize(minBuffSize)
530     *         .build();
531     * </pre>
532     * <p>
533     * If the audio attributes are not set with {@link #setAudioAttributes(AudioAttributes)},
534     * attributes comprising {@link AudioAttributes#USAGE_MEDIA} will be used.
535     * <br>If the audio format is not specified or is incomplete, its sample rate will be the
536     * default output sample rate of the device (see
537     * {@link AudioManager#PROPERTY_OUTPUT_SAMPLE_RATE}), its channel configuration will be
538     * {@link AudioFormat#CHANNEL_OUT_STEREO} and the encoding will be
539     * {@link AudioFormat#ENCODING_PCM_16BIT}.
540     * <br>If the buffer size is not specified with {@link #setBufferSizeInBytes(int)},
541     * and the mode is {@link AudioTrack#MODE_STREAM}, the minimum buffer size is used.
542     * <br>If the transfer mode is not specified with {@link #setTransferMode(int)},
543     * <code>MODE_STREAM</code> will be used.
544     * <br>If the session ID is not specified with {@link #setSessionId(int)}, a new one will
545     * be generated.
546     */
547    public static class Builder {
548        private AudioAttributes mAttributes;
549        private AudioFormat mFormat;
550        private int mBufferSizeInBytes;
551        private int mSessionId = AudioManager.AUDIO_SESSION_ID_GENERATE;
552        private int mMode = MODE_STREAM;
553
554        /**
555         * Constructs a new Builder with the default values as described above.
556         */
557        public Builder() {
558        }
559
560        /**
561         * Sets the {@link AudioAttributes}.
562         * @param attributes a non-null {@link AudioAttributes} instance that describes the audio
563         *     data to be played.
564         * @return the same Builder instance.
565         * @throws IllegalArgumentException
566         */
567        public @NonNull Builder setAudioAttributes(@NonNull AudioAttributes attributes)
568                throws IllegalArgumentException {
569            if (attributes == null) {
570                throw new IllegalArgumentException("Illegal null AudioAttributes argument");
571            }
572            // keep reference, we only copy the data when building
573            mAttributes = attributes;
574            return this;
575        }
576
577        /**
578         * Sets the format of the audio data to be played by the {@link AudioTrack}.
579         * See {@link AudioFormat.Builder} for configuring the audio format parameters such
580         * as encoding, channel mask and sample rate.
581         * @param format a non-null {@link AudioFormat} instance.
582         * @return the same Builder instance.
583         * @throws IllegalArgumentException
584         */
585        public @NonNull Builder setAudioFormat(@NonNull AudioFormat format)
586                throws IllegalArgumentException {
587            if (format == null) {
588                throw new IllegalArgumentException("Illegal null AudioFormat argument");
589            }
590            // keep reference, we only copy the data when building
591            mFormat = format;
592            return this;
593        }
594
595        /**
596         * Sets the total size (in bytes) of the buffer where audio data is read from for playback.
597         * If using the {@link AudioTrack} in streaming mode
598         * (see {@link AudioTrack#MODE_STREAM}, you can write data into this buffer in smaller
599         * chunks than this size. See {@link #getMinBufferSize(int, int, int)} to determine
600         * the minimum required buffer size for the successful creation of an AudioTrack instance
601         * in streaming mode. Using values smaller than <code>getMinBufferSize()</code> will result
602         * in an exception when trying to build the <code>AudioTrack</code>.
603         * <br>If using the <code>AudioTrack</code> in static mode (see
604         * {@link AudioTrack#MODE_STATIC}), this is the maximum size of the sound that will be
605         * played by this instance.
606         * @param bufferSizeInBytes
607         * @return the same Builder instance.
608         * @throws IllegalArgumentException
609         */
610        public @NonNull Builder setBufferSizeInBytes(int bufferSizeInBytes)
611                throws IllegalArgumentException {
612            if (bufferSizeInBytes <= 0) {
613                throw new IllegalArgumentException("Invalid buffer size " + bufferSizeInBytes);
614            }
615            mBufferSizeInBytes = bufferSizeInBytes;
616            return this;
617        }
618
619        /**
620         * Sets the mode under which buffers of audio data are transferred from the
621         * {@link AudioTrack} to the framework.
622         * @param mode one of {@link AudioTrack#MODE_STREAM}, {@link AudioTrack#MODE_STATIC}.
623         * @return the same Builder instance.
624         * @throws IllegalArgumentException
625         */
626        public @NonNull Builder setTransferMode(@TransferMode int mode)
627                throws IllegalArgumentException {
628            switch(mode) {
629                case MODE_STREAM:
630                case MODE_STATIC:
631                    mMode = mode;
632                    break;
633                default:
634                    throw new IllegalArgumentException("Invalid transfer mode " + mode);
635            }
636            return this;
637        }
638
639        /**
640         * Sets the session ID the {@link AudioTrack} will be attached to.
641         * @param sessionId a strictly positive ID number retrieved from another
642         *     <code>AudioTrack</code> via {@link AudioTrack#getAudioSessionId()} or allocated by
643         *     {@link AudioManager} via {@link AudioManager#generateAudioSessionId()}, or
644         *     {@link AudioManager#AUDIO_SESSION_ID_GENERATE}.
645         * @return the same Builder instance.
646         * @throws IllegalArgumentException
647         */
648        public @NonNull Builder setSessionId(int sessionId)
649                throws IllegalArgumentException {
650            if ((sessionId != AudioManager.AUDIO_SESSION_ID_GENERATE) && (sessionId < 1)) {
651                throw new IllegalArgumentException("Invalid audio session ID " + sessionId);
652            }
653            mSessionId = sessionId;
654            return this;
655        }
656
657        /**
658         * Builds an {@link AudioTrack} instance initialized with all the parameters set
659         * on this <code>Builder</code>.
660         * @return a new {@link AudioTrack} instance.
661         * @throws UnsupportedOperationException if the parameters set on the <code>Builder</code>
662         *     were incompatible, or if they are not supported by the device.
663         */
664        public @NonNull AudioTrack build() throws UnsupportedOperationException {
665            if (mAttributes == null) {
666                mAttributes = new AudioAttributes.Builder()
667                        .setUsage(AudioAttributes.USAGE_MEDIA)
668                        .build();
669            }
670            if (mFormat == null) {
671                mFormat = new AudioFormat.Builder()
672                        .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
673                        .setSampleRate(AudioSystem.getPrimaryOutputSamplingRate())
674                        .setEncoding(AudioFormat.ENCODING_DEFAULT)
675                        .build();
676            }
677            try {
678                // If the buffer size is not specified in streaming mode,
679                // use a single frame for the buffer size and let the
680                // native code figure out the minimum buffer size.
681                if (mMode == MODE_STREAM && mBufferSizeInBytes == 0) {
682                    mBufferSizeInBytes = mFormat.getChannelCount()
683                            * mFormat.getBytesPerSample(mFormat.getEncoding());
684                }
685                return new AudioTrack(mAttributes, mFormat, mBufferSizeInBytes, mMode, mSessionId);
686            } catch (IllegalArgumentException e) {
687                throw new UnsupportedOperationException(e.getMessage());
688            }
689        }
690    }
691
692    // mask of all the channels supported by this implementation
693    private static final int SUPPORTED_OUT_CHANNELS =
694            AudioFormat.CHANNEL_OUT_FRONT_LEFT |
695            AudioFormat.CHANNEL_OUT_FRONT_RIGHT |
696            AudioFormat.CHANNEL_OUT_FRONT_CENTER |
697            AudioFormat.CHANNEL_OUT_LOW_FREQUENCY |
698            AudioFormat.CHANNEL_OUT_BACK_LEFT |
699            AudioFormat.CHANNEL_OUT_BACK_RIGHT |
700            AudioFormat.CHANNEL_OUT_BACK_CENTER |
701            AudioFormat.CHANNEL_OUT_SIDE_LEFT |
702            AudioFormat.CHANNEL_OUT_SIDE_RIGHT;
703
704    // Java channel mask definitions below match those
705    // in /system/core/include/system/audio.h in the JNI code of AudioTrack.
706
707    // internal maximum size for bits parameter, not part of public API
708    private static final int AUDIO_CHANNEL_BITS_LOG2 = 30;
709
710    // log(2) of maximum number of representations, not part of public API
711    private static final int AUDIO_CHANNEL_REPRESENTATION_LOG2 = 2;
712
713    // used to create a channel index mask or channel position mask
714    // with getChannelMaskFromRepresentationAndBits();
715    private static final int CHANNEL_OUT_REPRESENTATION_POSITION = 0;
716    private static final int CHANNEL_OUT_REPRESENTATION_INDEX = 2;
717
718    /**
719     * Return the channel mask from its representation and bits.
720     *
721     * This creates a channel mask for mChannels which combines a
722     * representation field and a bits field.  This is for internal
723     * communication to native code, not part of the public API.
724     *
725     * @param representation the type of channel mask,
726     *   either CHANNEL_OUT_REPRESENTATION_POSITION
727     *   or CHANNEL_OUT_REPRESENTATION_INDEX
728     * @param bits is the channel bits specifying occupancy
729     * @return the channel mask
730     * @throws java.lang.IllegalArgumentException if representation is not recognized or
731     *   the bits field is not acceptable for that representation
732     */
733    private static int getChannelMaskFromRepresentationAndBits(int representation, int bits) {
734        switch (representation) {
735        case CHANNEL_OUT_REPRESENTATION_POSITION:
736        case CHANNEL_OUT_REPRESENTATION_INDEX:
737            if ((bits & ~((1 << AUDIO_CHANNEL_BITS_LOG2) - 1)) != 0) {
738                throw new IllegalArgumentException("invalid bits " + bits);
739            }
740            return representation << AUDIO_CHANNEL_BITS_LOG2 | bits;
741        default:
742            throw new IllegalArgumentException("invalid representation " + representation);
743        }
744    }
745
746    // Convenience method for the constructor's parameter checks.
747    // This is where constructor IllegalArgumentException-s are thrown
748    // postconditions:
749    //    mChannelCount is valid
750    //    mChannels is valid
751    //    mAudioFormat is valid
752    //    mSampleRate is valid
753    //    mDataLoadMode is valid
754    private void audioParamCheck(int sampleRateInHz, int channelConfig, int channelIndexMask,
755                                 int audioFormat, int mode) {
756        //--------------
757        // sample rate, note these values are subject to change
758        if (sampleRateInHz < SAMPLE_RATE_HZ_MIN || sampleRateInHz > SAMPLE_RATE_HZ_MAX) {
759            throw new IllegalArgumentException(sampleRateInHz
760                    + "Hz is not a supported sample rate.");
761        }
762        mSampleRate = sampleRateInHz;
763
764        //--------------
765        // channel config
766        mChannelConfiguration = channelConfig;
767
768        switch (channelConfig) {
769        case AudioFormat.CHANNEL_OUT_DEFAULT: //AudioFormat.CHANNEL_CONFIGURATION_DEFAULT
770        case AudioFormat.CHANNEL_OUT_MONO:
771        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
772            mChannelCount = 1;
773            mChannels = AudioFormat.CHANNEL_OUT_MONO;
774            break;
775        case AudioFormat.CHANNEL_OUT_STEREO:
776        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
777            mChannelCount = 2;
778            mChannels = AudioFormat.CHANNEL_OUT_STEREO;
779            break;
780        default:
781            if (channelConfig == AudioFormat.CHANNEL_INVALID && channelIndexMask != 0) {
782                mChannelCount = 0;
783                break; // channel index configuration only
784            }
785            if (!isMultichannelConfigSupported(channelConfig)) {
786                // input channel configuration features unsupported channels
787                throw new IllegalArgumentException("Unsupported channel configuration.");
788            }
789            mChannels = channelConfig;
790            mChannelCount = AudioFormat.channelCountFromOutChannelMask(channelConfig);
791        }
792        // check the channel index configuration (if present)
793        mChannelIndexMask = channelIndexMask;
794        if (mChannelIndexMask != 0) {
795            // restrictive: indexMask could allow up to AUDIO_CHANNEL_BITS_LOG2
796            final int indexMask = (1 << CHANNEL_COUNT_MAX) - 1;
797            if ((channelIndexMask & ~indexMask) != 0) {
798                throw new IllegalArgumentException("Unsupported channel index configuration "
799                        + channelIndexMask);
800            }
801            int channelIndexCount = Integer.bitCount(channelIndexMask);
802            if (mChannelCount == 0) {
803                 mChannelCount = channelIndexCount;
804            } else if (mChannelCount != channelIndexCount) {
805                throw new IllegalArgumentException("Channel count must match");
806            }
807
808            // AudioTrack prefers to use the channel index configuration
809            // over the channel position configuration if both are specified.
810            mChannels = getChannelMaskFromRepresentationAndBits(
811                    CHANNEL_OUT_REPRESENTATION_INDEX, mChannelIndexMask);
812        }
813
814        //--------------
815        // audio format
816        if (audioFormat == AudioFormat.ENCODING_DEFAULT) {
817            audioFormat = AudioFormat.ENCODING_PCM_16BIT;
818        }
819
820        if (!AudioFormat.isValidEncoding(audioFormat)) {
821            throw new IllegalArgumentException("Unsupported audio encoding.");
822        }
823        mAudioFormat = audioFormat;
824
825        //--------------
826        // audio load mode
827        if (((mode != MODE_STREAM) && (mode != MODE_STATIC)) ||
828                ((mode != MODE_STREAM) && !AudioFormat.isEncodingLinearPcm(mAudioFormat))) {
829            throw new IllegalArgumentException("Invalid mode.");
830        }
831        mDataLoadMode = mode;
832    }
833
834    /**
835     * Convenience method to check that the channel configuration (a.k.a channel mask) is supported
836     * @param channelConfig the mask to validate
837     * @return false if the AudioTrack can't be used with such a mask
838     */
839    private static boolean isMultichannelConfigSupported(int channelConfig) {
840        // check for unsupported channels
841        if ((channelConfig & SUPPORTED_OUT_CHANNELS) != channelConfig) {
842            loge("Channel configuration features unsupported channels");
843            return false;
844        }
845        final int channelCount = AudioFormat.channelCountFromOutChannelMask(channelConfig);
846        if (channelCount > CHANNEL_COUNT_MAX) {
847            loge("Channel configuration contains too many channels " +
848                    channelCount + ">" + CHANNEL_COUNT_MAX);
849            return false;
850        }
851        // check for unsupported multichannel combinations:
852        // - FL/FR must be present
853        // - L/R channels must be paired (e.g. no single L channel)
854        final int frontPair =
855                AudioFormat.CHANNEL_OUT_FRONT_LEFT | AudioFormat.CHANNEL_OUT_FRONT_RIGHT;
856        if ((channelConfig & frontPair) != frontPair) {
857                loge("Front channels must be present in multichannel configurations");
858                return false;
859        }
860        final int backPair =
861                AudioFormat.CHANNEL_OUT_BACK_LEFT | AudioFormat.CHANNEL_OUT_BACK_RIGHT;
862        if ((channelConfig & backPair) != 0) {
863            if ((channelConfig & backPair) != backPair) {
864                loge("Rear channels can't be used independently");
865                return false;
866            }
867        }
868        final int sidePair =
869                AudioFormat.CHANNEL_OUT_SIDE_LEFT | AudioFormat.CHANNEL_OUT_SIDE_RIGHT;
870        if ((channelConfig & sidePair) != 0
871                && (channelConfig & sidePair) != sidePair) {
872            loge("Side channels can't be used independently");
873            return false;
874        }
875        return true;
876    }
877
878
879    // Convenience method for the constructor's audio buffer size check.
880    // preconditions:
881    //    mChannelCount is valid
882    //    mAudioFormat is valid
883    // postcondition:
884    //    mNativeBufferSizeInBytes is valid (multiple of frame size, positive)
885    private void audioBuffSizeCheck(int audioBufferSize) {
886        // NB: this section is only valid with PCM data.
887        //     To update when supporting compressed formats
888        int frameSizeInBytes;
889        if (AudioFormat.isEncodingLinearPcm(mAudioFormat)) {
890            frameSizeInBytes = mChannelCount
891                    * (AudioFormat.getBytesPerSample(mAudioFormat));
892        } else {
893            frameSizeInBytes = 1;
894        }
895        if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) {
896            throw new IllegalArgumentException("Invalid audio buffer size.");
897        }
898
899        mNativeBufferSizeInBytes = audioBufferSize;
900        mNativeBufferSizeInFrames = audioBufferSize / frameSizeInBytes;
901    }
902
903
904    /**
905     * Releases the native AudioTrack resources.
906     */
907    public void release() {
908        // even though native_release() stops the native AudioTrack, we need to stop
909        // AudioTrack subclasses too.
910        try {
911            stop();
912        } catch(IllegalStateException ise) {
913            // don't raise an exception, we're releasing the resources.
914        }
915        native_release();
916        mState = STATE_UNINITIALIZED;
917    }
918
919    @Override
920    protected void finalize() {
921        native_finalize();
922    }
923
924    //--------------------------------------------------------------------------
925    // Getters
926    //--------------------
927    /**
928     * Returns the minimum gain value, which is the constant 0.0.
929     * Gain values less than 0.0 will be clamped to 0.0.
930     * <p>The word "volume" in the API name is historical; this is actually a linear gain.
931     * @return the minimum value, which is the constant 0.0.
932     */
933    static public float getMinVolume() {
934        return GAIN_MIN;
935    }
936
937    /**
938     * Returns the maximum gain value, which is greater than or equal to 1.0.
939     * Gain values greater than the maximum will be clamped to the maximum.
940     * <p>The word "volume" in the API name is historical; this is actually a gain.
941     * expressed as a linear multiplier on sample values, where a maximum value of 1.0
942     * corresponds to a gain of 0 dB (sample values left unmodified).
943     * @return the maximum value, which is greater than or equal to 1.0.
944     */
945    static public float getMaxVolume() {
946        return GAIN_MAX;
947    }
948
949    /**
950     * Returns the configured audio data sample rate in Hz
951     */
952    public int getSampleRate() {
953        return mSampleRate;
954    }
955
956    /**
957     * Returns the current playback sample rate rate in Hz.
958     */
959    public int getPlaybackRate() {
960        return native_get_playback_rate();
961    }
962
963    /**
964     * Returns the current playback settings.
965     * See {@link #setPlaybackSettings(PlaybackSettings)} to set playback settings
966     * @return current {@link PlaybackSettings}.
967     * @throws IllegalStateException if track is not initialized.
968     */
969    public @NonNull PlaybackSettings getPlaybackSettings() {
970        float[] floatArray = new float[2];
971        int[] intArray = new int[2];
972        native_get_playback_settings(floatArray, intArray);
973        return new PlaybackSettings()
974                .setSpeed(floatArray[0])
975                .setPitch(floatArray[1])
976                .setAudioFallbackMode(intArray[0])
977                .setAudioStretchMode(intArray[1]);
978    }
979
980    /**
981     * Returns the configured audio data format. See {@link AudioFormat#ENCODING_PCM_16BIT}
982     * and {@link AudioFormat#ENCODING_PCM_8BIT}.
983     */
984    public int getAudioFormat() {
985        return mAudioFormat;
986    }
987
988    /**
989     * Returns the type of audio stream this AudioTrack is configured for.
990     * Compare the result against {@link AudioManager#STREAM_VOICE_CALL},
991     * {@link AudioManager#STREAM_SYSTEM}, {@link AudioManager#STREAM_RING},
992     * {@link AudioManager#STREAM_MUSIC}, {@link AudioManager#STREAM_ALARM},
993     * {@link AudioManager#STREAM_NOTIFICATION}, or {@link AudioManager#STREAM_DTMF}.
994     */
995    public int getStreamType() {
996        return mStreamType;
997    }
998
999    /**
1000     * Returns the configured channel position mask.
1001     * For example, refer to {@link AudioFormat#CHANNEL_OUT_MONO},
1002     * {@link AudioFormat#CHANNEL_OUT_STEREO}, {@link AudioFormat#CHANNEL_OUT_5POINT1}.
1003     */
1004    public int getChannelConfiguration() {
1005        return mChannelConfiguration;
1006    }
1007
1008    /**
1009     * Returns the configured number of channels.
1010     */
1011    public int getChannelCount() {
1012        return mChannelCount;
1013    }
1014
1015    /**
1016     * Returns the state of the AudioTrack instance. This is useful after the
1017     * AudioTrack instance has been created to check if it was initialized
1018     * properly. This ensures that the appropriate resources have been acquired.
1019     * @see #STATE_INITIALIZED
1020     * @see #STATE_NO_STATIC_DATA
1021     * @see #STATE_UNINITIALIZED
1022     */
1023    public int getState() {
1024        return mState;
1025    }
1026
1027    /**
1028     * Returns the playback state of the AudioTrack instance.
1029     * @see #PLAYSTATE_STOPPED
1030     * @see #PLAYSTATE_PAUSED
1031     * @see #PLAYSTATE_PLAYING
1032     */
1033    public int getPlayState() {
1034        synchronized (mPlayStateLock) {
1035            return mPlayState;
1036        }
1037    }
1038
1039    /**
1040     *  Returns the "native frame count" of the <code>AudioTrack</code> buffer.
1041     *  <p> If the track's creation mode is {@link #MODE_STATIC},
1042     *  it is equal to the specified bufferSizeInBytes on construction, converted to frame units.
1043     *  A static track's native frame count will not change.
1044     *  <p> If the track's creation mode is {@link #MODE_STREAM},
1045     *  it is greater than or equal to the specified bufferSizeInBytes converted to frame units.
1046     *  For streaming tracks, this value may be rounded up to a larger value if needed by
1047     *  the target output sink, and
1048     *  if the track is subsequently routed to a different output sink, the native
1049     *  frame count may enlarge to accommodate.
1050     *  See also {@link AudioManager#getProperty(String)} for key
1051     *  {@link AudioManager#PROPERTY_OUTPUT_FRAMES_PER_BUFFER}.
1052     *  @return current size in frames of the audio track buffer.
1053     *  @throws IllegalStateException
1054     */
1055    public int getNativeFrameCount() throws IllegalStateException {
1056        return native_get_native_frame_count();
1057    }
1058
1059    /**
1060     * Returns marker position expressed in frames.
1061     * @return marker position in wrapping frame units similar to {@link #getPlaybackHeadPosition},
1062     * or zero if marker is disabled.
1063     */
1064    public int getNotificationMarkerPosition() {
1065        return native_get_marker_pos();
1066    }
1067
1068    /**
1069     * Returns the notification update period expressed in frames.
1070     * Zero means that no position update notifications are being delivered.
1071     */
1072    public int getPositionNotificationPeriod() {
1073        return native_get_pos_update_period();
1074    }
1075
1076    /**
1077     * Returns the playback head position expressed in frames.
1078     * Though the "int" type is signed 32-bits, the value should be reinterpreted as if it is
1079     * unsigned 32-bits.  That is, the next position after 0x7FFFFFFF is (int) 0x80000000.
1080     * This is a continuously advancing counter.  It will wrap (overflow) periodically,
1081     * for example approximately once every 27:03:11 hours:minutes:seconds at 44.1 kHz.
1082     * It is reset to zero by {@link #flush()}, {@link #reloadStaticData()}, and {@link #stop()}.
1083     * If the track's creation mode is {@link #MODE_STATIC}, the return value indicates
1084     * the total number of frames played since reset,
1085     * <i>not</i> the current offset within the buffer.
1086     */
1087    public int getPlaybackHeadPosition() {
1088        return native_get_position();
1089    }
1090
1091    /**
1092     * Returns this track's estimated latency in milliseconds. This includes the latency due
1093     * to AudioTrack buffer size, AudioMixer (if any) and audio hardware driver.
1094     *
1095     * DO NOT UNHIDE. The existing approach for doing A/V sync has too many problems. We need
1096     * a better solution.
1097     * @hide
1098     */
1099    public int getLatency() {
1100        return native_get_latency();
1101    }
1102
1103    /**
1104     *  Returns the output sample rate in Hz for the specified stream type.
1105     */
1106    static public int getNativeOutputSampleRate(int streamType) {
1107        return native_get_output_sample_rate(streamType);
1108    }
1109
1110    /**
1111     * Returns the minimum buffer size required for the successful creation of an AudioTrack
1112     * object to be created in the {@link #MODE_STREAM} mode. Note that this size doesn't
1113     * guarantee a smooth playback under load, and higher values should be chosen according to
1114     * the expected frequency at which the buffer will be refilled with additional data to play.
1115     * For example, if you intend to dynamically set the source sample rate of an AudioTrack
1116     * to a higher value than the initial source sample rate, be sure to configure the buffer size
1117     * based on the highest planned sample rate.
1118     * @param sampleRateInHz the source sample rate expressed in Hz.
1119     * @param channelConfig describes the configuration of the audio channels.
1120     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
1121     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
1122     * @param audioFormat the format in which the audio data is represented.
1123     *   See {@link AudioFormat#ENCODING_PCM_16BIT} and
1124     *   {@link AudioFormat#ENCODING_PCM_8BIT},
1125     *   and {@link AudioFormat#ENCODING_PCM_FLOAT}.
1126     * @return {@link #ERROR_BAD_VALUE} if an invalid parameter was passed,
1127     *   or {@link #ERROR} if unable to query for output properties,
1128     *   or the minimum buffer size expressed in bytes.
1129     */
1130    static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) {
1131        int channelCount = 0;
1132        switch(channelConfig) {
1133        case AudioFormat.CHANNEL_OUT_MONO:
1134        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
1135            channelCount = 1;
1136            break;
1137        case AudioFormat.CHANNEL_OUT_STEREO:
1138        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
1139            channelCount = 2;
1140            break;
1141        default:
1142            if (!isMultichannelConfigSupported(channelConfig)) {
1143                loge("getMinBufferSize(): Invalid channel configuration.");
1144                return ERROR_BAD_VALUE;
1145            } else {
1146                channelCount = AudioFormat.channelCountFromOutChannelMask(channelConfig);
1147            }
1148        }
1149
1150        if (!AudioFormat.isValidEncoding(audioFormat)) {
1151            loge("getMinBufferSize(): Invalid audio format.");
1152            return ERROR_BAD_VALUE;
1153        }
1154
1155        // sample rate, note these values are subject to change
1156        if ( (sampleRateInHz < SAMPLE_RATE_HZ_MIN) || (sampleRateInHz > SAMPLE_RATE_HZ_MAX) ) {
1157            loge("getMinBufferSize(): " + sampleRateInHz + " Hz is not a supported sample rate.");
1158            return ERROR_BAD_VALUE;
1159        }
1160
1161        int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat);
1162        if (size <= 0) {
1163            loge("getMinBufferSize(): error querying hardware");
1164            return ERROR;
1165        }
1166        else {
1167            return size;
1168        }
1169    }
1170
1171    /**
1172     * Returns the audio session ID.
1173     *
1174     * @return the ID of the audio session this AudioTrack belongs to.
1175     */
1176    public int getAudioSessionId() {
1177        return mSessionId;
1178    }
1179
1180   /**
1181    * Poll for a timestamp on demand.
1182    * <p>
1183    * If you need to track timestamps during initial warmup or after a routing or mode change,
1184    * you should request a new timestamp once per second until the reported timestamps
1185    * show that the audio clock is stable.
1186    * Thereafter, query for a new timestamp approximately once every 10 seconds to once per minute.
1187    * Calling this method more often is inefficient.
1188    * It is also counter-productive to call this method more often than recommended,
1189    * because the short-term differences between successive timestamp reports are not meaningful.
1190    * If you need a high-resolution mapping between frame position and presentation time,
1191    * consider implementing that at application level, based on low-resolution timestamps.
1192    * <p>
1193    * The audio data at the returned position may either already have been
1194    * presented, or may have not yet been presented but is committed to be presented.
1195    * It is not possible to request the time corresponding to a particular position,
1196    * or to request the (fractional) position corresponding to a particular time.
1197    * If you need such features, consider implementing them at application level.
1198    *
1199    * @param timestamp a reference to a non-null AudioTimestamp instance allocated
1200    *        and owned by caller.
1201    * @return true if a timestamp is available, or false if no timestamp is available.
1202    *         If a timestamp if available,
1203    *         the AudioTimestamp instance is filled in with a position in frame units, together
1204    *         with the estimated time when that frame was presented or is committed to
1205    *         be presented.
1206    *         In the case that no timestamp is available, any supplied instance is left unaltered.
1207    *         A timestamp may be temporarily unavailable while the audio clock is stabilizing,
1208    *         or during and immediately after a route change.
1209    */
1210    // Add this text when the "on new timestamp" API is added:
1211    //   Use if you need to get the most recent timestamp outside of the event callback handler.
1212    public boolean getTimestamp(AudioTimestamp timestamp)
1213    {
1214        if (timestamp == null) {
1215            throw new IllegalArgumentException();
1216        }
1217        // It's unfortunate, but we have to either create garbage every time or use synchronized
1218        long[] longArray = new long[2];
1219        int ret = native_get_timestamp(longArray);
1220        if (ret != SUCCESS) {
1221            return false;
1222        }
1223        timestamp.framePosition = longArray[0];
1224        timestamp.nanoTime = longArray[1];
1225        return true;
1226    }
1227
1228
1229    //--------------------------------------------------------------------------
1230    // Initialization / configuration
1231    //--------------------
1232    /**
1233     * Sets the listener the AudioTrack notifies when a previously set marker is reached or
1234     * for each periodic playback head position update.
1235     * Notifications will be received in the same thread as the one in which the AudioTrack
1236     * instance was created.
1237     * @param listener
1238     */
1239    public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener) {
1240        setPlaybackPositionUpdateListener(listener, null);
1241    }
1242
1243    /**
1244     * Sets the listener the AudioTrack notifies when a previously set marker is reached or
1245     * for each periodic playback head position update.
1246     * Use this method to receive AudioTrack events in the Handler associated with another
1247     * thread than the one in which you created the AudioTrack instance.
1248     * @param listener
1249     * @param handler the Handler that will receive the event notification messages.
1250     */
1251    public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener,
1252                                                    Handler handler) {
1253        if (listener != null) {
1254            mEventHandlerDelegate = new NativePositionEventHandlerDelegate(this, listener, handler);
1255        } else {
1256            mEventHandlerDelegate = null;
1257        }
1258    }
1259
1260
1261    private static float clampGainOrLevel(float gainOrLevel) {
1262        if (Float.isNaN(gainOrLevel)) {
1263            throw new IllegalArgumentException();
1264        }
1265        if (gainOrLevel < GAIN_MIN) {
1266            gainOrLevel = GAIN_MIN;
1267        } else if (gainOrLevel > GAIN_MAX) {
1268            gainOrLevel = GAIN_MAX;
1269        }
1270        return gainOrLevel;
1271    }
1272
1273
1274     /**
1275     * Sets the specified left and right output gain values on the AudioTrack.
1276     * <p>Gain values are clamped to the closed interval [0.0, max] where
1277     * max is the value of {@link #getMaxVolume}.
1278     * A value of 0.0 results in zero gain (silence), and
1279     * a value of 1.0 means unity gain (signal unchanged).
1280     * The default value is 1.0 meaning unity gain.
1281     * <p>The word "volume" in the API name is historical; this is actually a linear gain.
1282     * @param leftGain output gain for the left channel.
1283     * @param rightGain output gain for the right channel
1284     * @return error code or success, see {@link #SUCCESS},
1285     *    {@link #ERROR_INVALID_OPERATION}
1286     * @deprecated Applications should use {@link #setVolume} instead, as it
1287     * more gracefully scales down to mono, and up to multi-channel content beyond stereo.
1288     */
1289    public int setStereoVolume(float leftGain, float rightGain) {
1290        if (isRestricted()) {
1291            return SUCCESS;
1292        }
1293        if (mState == STATE_UNINITIALIZED) {
1294            return ERROR_INVALID_OPERATION;
1295        }
1296
1297        leftGain = clampGainOrLevel(leftGain);
1298        rightGain = clampGainOrLevel(rightGain);
1299
1300        native_setVolume(leftGain, rightGain);
1301
1302        return SUCCESS;
1303    }
1304
1305
1306    /**
1307     * Sets the specified output gain value on all channels of this track.
1308     * <p>Gain values are clamped to the closed interval [0.0, max] where
1309     * max is the value of {@link #getMaxVolume}.
1310     * A value of 0.0 results in zero gain (silence), and
1311     * a value of 1.0 means unity gain (signal unchanged).
1312     * The default value is 1.0 meaning unity gain.
1313     * <p>This API is preferred over {@link #setStereoVolume}, as it
1314     * more gracefully scales down to mono, and up to multi-channel content beyond stereo.
1315     * <p>The word "volume" in the API name is historical; this is actually a linear gain.
1316     * @param gain output gain for all channels.
1317     * @return error code or success, see {@link #SUCCESS},
1318     *    {@link #ERROR_INVALID_OPERATION}
1319     */
1320    public int setVolume(float gain) {
1321        return setStereoVolume(gain, gain);
1322    }
1323
1324
1325    /**
1326     * Sets the playback sample rate for this track. This sets the sampling rate at which
1327     * the audio data will be consumed and played back
1328     * (as set by the sampleRateInHz parameter in the
1329     * {@link #AudioTrack(int, int, int, int, int, int)} constructor),
1330     * not the original sampling rate of the
1331     * content. For example, setting it to half the sample rate of the content will cause the
1332     * playback to last twice as long, but will also result in a pitch shift down by one octave.
1333     * The valid sample rate range is from 1 Hz to twice the value returned by
1334     * {@link #getNativeOutputSampleRate(int)}.
1335     * Use {@link #setPlaybackSettings(PlaybackSettings)} for speed control.
1336     * @param sampleRateInHz the sample rate expressed in Hz
1337     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
1338     *    {@link #ERROR_INVALID_OPERATION}
1339     */
1340    public int setPlaybackRate(int sampleRateInHz) {
1341        if (mState != STATE_INITIALIZED) {
1342            return ERROR_INVALID_OPERATION;
1343        }
1344        if (sampleRateInHz <= 0) {
1345            return ERROR_BAD_VALUE;
1346        }
1347        return native_set_playback_rate(sampleRateInHz);
1348    }
1349
1350
1351    /**
1352     * Sets the playback settings.
1353     * This method returns failure if it cannot apply the playback settings.
1354     * One possible cause is that the parameters for speed or pitch are out of range.
1355     * Another possible cause is that the <code>AudioTrack</code> is streaming
1356     * (see {@link #MODE_STREAM}) and the
1357     * buffer size is too small. For speeds greater than 1.0f, the <code>AudioTrack</code> buffer
1358     * on configuration must be larger than the speed multiplied by the minimum size
1359     * {@link #getMinBufferSize(int, int, int)}) to allow proper playback.
1360     * @param settings see {@link PlaybackSettings}. In particular,
1361     * speed, pitch, and audio mode should be set.
1362     * @throws IllegalArgumentException if the settings are invalid or not accepted.
1363     * @throws IllegalStateException if track is not initialized.
1364     */
1365    public void setPlaybackSettings(@NonNull PlaybackSettings settings) {
1366        if (settings == null) {
1367            throw new IllegalArgumentException("settings is null");
1368        }
1369        float[] floatArray;
1370        int[] intArray;
1371        try {
1372            floatArray = new float[] {
1373                    settings.getSpeed(),
1374                    settings.getPitch(),
1375            };
1376            intArray = new int[] {
1377                    settings.getAudioFallbackMode(),
1378                    settings.getAudioStretchMode(),
1379            };
1380        } catch (IllegalStateException e) {
1381            throw new IllegalArgumentException(e);
1382        }
1383        native_set_playback_settings(floatArray, intArray);
1384    }
1385
1386
1387    /**
1388     * Sets the position of the notification marker.  At most one marker can be active.
1389     * @param markerInFrames marker position in wrapping frame units similar to
1390     * {@link #getPlaybackHeadPosition}, or zero to disable the marker.
1391     * To set a marker at a position which would appear as zero due to wraparound,
1392     * a workaround is to use a non-zero position near zero, such as -1 or 1.
1393     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
1394     *  {@link #ERROR_INVALID_OPERATION}
1395     */
1396    public int setNotificationMarkerPosition(int markerInFrames) {
1397        if (mState == STATE_UNINITIALIZED) {
1398            return ERROR_INVALID_OPERATION;
1399        }
1400        return native_set_marker_pos(markerInFrames);
1401    }
1402
1403
1404    /**
1405     * Sets the period for the periodic notification event.
1406     * @param periodInFrames update period expressed in frames.
1407     * Zero period means no position updates.  A negative period is not allowed.
1408     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION}
1409     */
1410    public int setPositionNotificationPeriod(int periodInFrames) {
1411        if (mState == STATE_UNINITIALIZED) {
1412            return ERROR_INVALID_OPERATION;
1413        }
1414        return native_set_pos_update_period(periodInFrames);
1415    }
1416
1417
1418    /**
1419     * Sets the playback head position within the static buffer.
1420     * The track must be stopped or paused for the position to be changed,
1421     * and must use the {@link #MODE_STATIC} mode.
1422     * @param positionInFrames playback head position within buffer, expressed in frames.
1423     * Zero corresponds to start of buffer.
1424     * The position must not be greater than the buffer size in frames, or negative.
1425     * Though this method and {@link #getPlaybackHeadPosition()} have similar names,
1426     * the position values have different meanings.
1427     * <br>
1428     * If looping is currently enabled and the new position is greater than or equal to the
1429     * loop end marker, the behavior varies by API level: for API level 22 and above,
1430     * the looping is first disabled and then the position is set.
1431     * For earlier API levels, the behavior is unspecified.
1432     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
1433     *    {@link #ERROR_INVALID_OPERATION}
1434     */
1435    public int setPlaybackHeadPosition(int positionInFrames) {
1436        if (mDataLoadMode == MODE_STREAM || mState == STATE_UNINITIALIZED ||
1437                getPlayState() == PLAYSTATE_PLAYING) {
1438            return ERROR_INVALID_OPERATION;
1439        }
1440        if (!(0 <= positionInFrames && positionInFrames <= mNativeBufferSizeInFrames)) {
1441            return ERROR_BAD_VALUE;
1442        }
1443        return native_set_position(positionInFrames);
1444    }
1445
1446    /**
1447     * Sets the loop points and the loop count. The loop can be infinite.
1448     * Similarly to setPlaybackHeadPosition,
1449     * the track must be stopped or paused for the loop points to be changed,
1450     * and must use the {@link #MODE_STATIC} mode.
1451     * @param startInFrames loop start marker expressed in frames.
1452     * Zero corresponds to start of buffer.
1453     * The start marker must not be greater than or equal to the buffer size in frames, or negative.
1454     * @param endInFrames loop end marker expressed in frames.
1455     * The total buffer size in frames corresponds to end of buffer.
1456     * The end marker must not be greater than the buffer size in frames.
1457     * For looping, the end marker must not be less than or equal to the start marker,
1458     * but to disable looping
1459     * it is permitted for start marker, end marker, and loop count to all be 0.
1460     * If any input parameters are out of range, this method returns {@link #ERROR_BAD_VALUE}.
1461     * If the loop period (endInFrames - startInFrames) is too small for the implementation to
1462     * support,
1463     * {@link #ERROR_BAD_VALUE} is returned.
1464     * The loop range is the interval [startInFrames, endInFrames).
1465     * <br>
1466     * For API level 22 and above, the position is left unchanged,
1467     * unless it is greater than or equal to the loop end marker, in which case
1468     * it is forced to the loop start marker.
1469     * For earlier API levels, the effect on position is unspecified.
1470     * @param loopCount the number of times the loop is looped; must be greater than or equal to -1.
1471     *    A value of -1 means infinite looping, and 0 disables looping.
1472     *    A value of positive N means to "loop" (go back) N times.  For example,
1473     *    a value of one means to play the region two times in total.
1474     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
1475     *    {@link #ERROR_INVALID_OPERATION}
1476     */
1477    public int setLoopPoints(int startInFrames, int endInFrames, int loopCount) {
1478        if (mDataLoadMode == MODE_STREAM || mState == STATE_UNINITIALIZED ||
1479                getPlayState() == PLAYSTATE_PLAYING) {
1480            return ERROR_INVALID_OPERATION;
1481        }
1482        if (loopCount == 0) {
1483            ;   // explicitly allowed as an exception to the loop region range check
1484        } else if (!(0 <= startInFrames && startInFrames < mNativeBufferSizeInFrames &&
1485                startInFrames < endInFrames && endInFrames <= mNativeBufferSizeInFrames)) {
1486            return ERROR_BAD_VALUE;
1487        }
1488        return native_set_loop(startInFrames, endInFrames, loopCount);
1489    }
1490
1491    /**
1492     * Sets the initialization state of the instance. This method was originally intended to be used
1493     * in an AudioTrack subclass constructor to set a subclass-specific post-initialization state.
1494     * However, subclasses of AudioTrack are no longer recommended, so this method is obsolete.
1495     * @param state the state of the AudioTrack instance
1496     * @deprecated Only accessible by subclasses, which are not recommended for AudioTrack.
1497     */
1498    @Deprecated
1499    protected void setState(int state) {
1500        mState = state;
1501    }
1502
1503
1504    //---------------------------------------------------------
1505    // Transport control methods
1506    //--------------------
1507    /**
1508     * Starts playing an AudioTrack.
1509     * If track's creation mode is {@link #MODE_STATIC}, you must have called one of
1510     * the {@link #write(byte[], int, int)}, {@link #write(short[], int, int)},
1511     * or {@link #write(float[], int, int, int)} methods.
1512     * If the mode is {@link #MODE_STREAM}, you can optionally prime the
1513     * output buffer by writing up to bufferSizeInBytes (from constructor) before starting.
1514     * This priming will avoid an immediate underrun, but is not required.
1515     *
1516     * @throws IllegalStateException
1517     */
1518    public void play()
1519    throws IllegalStateException {
1520        if (mState != STATE_INITIALIZED) {
1521            throw new IllegalStateException("play() called on uninitialized AudioTrack.");
1522        }
1523        if (isRestricted()) {
1524            setVolume(0);
1525        }
1526        synchronized(mPlayStateLock) {
1527            native_start();
1528            mPlayState = PLAYSTATE_PLAYING;
1529        }
1530    }
1531
1532    private boolean isRestricted() {
1533        if ((mAttributes.getFlags() & AudioAttributes.FLAG_BYPASS_INTERRUPTION_POLICY) != 0) {
1534            return false;
1535        }
1536        try {
1537            final int usage = AudioAttributes.usageForLegacyStreamType(mStreamType);
1538            final int mode = mAppOps.checkAudioOperation(AppOpsManager.OP_PLAY_AUDIO, usage,
1539                    Process.myUid(), ActivityThread.currentPackageName());
1540            return mode != AppOpsManager.MODE_ALLOWED;
1541        } catch (RemoteException e) {
1542            return false;
1543        }
1544    }
1545
1546    /**
1547     * Stops playing the audio data.
1548     * When used on an instance created in {@link #MODE_STREAM} mode, audio will stop playing
1549     * after the last buffer that was written has been played. For an immediate stop, use
1550     * {@link #pause()}, followed by {@link #flush()} to discard audio data that hasn't been played
1551     * back yet.
1552     * @throws IllegalStateException
1553     */
1554    public void stop()
1555    throws IllegalStateException {
1556        if (mState != STATE_INITIALIZED) {
1557            throw new IllegalStateException("stop() called on uninitialized AudioTrack.");
1558        }
1559
1560        // stop playing
1561        synchronized(mPlayStateLock) {
1562            native_stop();
1563            mPlayState = PLAYSTATE_STOPPED;
1564            mAvSyncHeader = null;
1565            mAvSyncBytesRemaining = 0;
1566        }
1567    }
1568
1569    /**
1570     * Pauses the playback of the audio data. Data that has not been played
1571     * back will not be discarded. Subsequent calls to {@link #play} will play
1572     * this data back. See {@link #flush()} to discard this data.
1573     *
1574     * @throws IllegalStateException
1575     */
1576    public void pause()
1577    throws IllegalStateException {
1578        if (mState != STATE_INITIALIZED) {
1579            throw new IllegalStateException("pause() called on uninitialized AudioTrack.");
1580        }
1581        //logd("pause()");
1582
1583        // pause playback
1584        synchronized(mPlayStateLock) {
1585            native_pause();
1586            mPlayState = PLAYSTATE_PAUSED;
1587        }
1588    }
1589
1590
1591    //---------------------------------------------------------
1592    // Audio data supply
1593    //--------------------
1594
1595    /**
1596     * Flushes the audio data currently queued for playback. Any data that has
1597     * been written but not yet presented will be discarded.  No-op if not stopped or paused,
1598     * or if the track's creation mode is not {@link #MODE_STREAM}.
1599     * <BR> Note that although data written but not yet presented is discarded, there is no
1600     * guarantee that all of the buffer space formerly used by that data
1601     * is available for a subsequent write.
1602     * For example, a call to {@link #write(byte[], int, int)} with <code>sizeInBytes</code>
1603     * less than or equal to the total buffer size
1604     * may return a short actual transfer count.
1605     */
1606    public void flush() {
1607        if (mState == STATE_INITIALIZED) {
1608            // flush the data in native layer
1609            native_flush();
1610            mAvSyncHeader = null;
1611            mAvSyncBytesRemaining = 0;
1612        }
1613
1614    }
1615
1616    /**
1617     * Writes the audio data to the audio sink for playback (streaming mode),
1618     * or copies audio data for later playback (static buffer mode).
1619     * The format specified in the AudioTrack constructor should be
1620     * {@link AudioFormat#ENCODING_PCM_8BIT} to correspond to the data in the array.
1621     * In streaming mode, will block until all data has been written to the audio sink.
1622     * In static buffer mode, copies the data to the buffer starting at offset 0.
1623     * Note that the actual playback of this data might occur after this function
1624     * returns. This function is thread safe with respect to {@link #stop} calls,
1625     * in which case all of the specified data might not be written to the audio sink.
1626     *
1627     * @param audioData the array that holds the data to play.
1628     * @param offsetInBytes the offset expressed in bytes in audioData where the data to play
1629     *    starts.
1630     * @param sizeInBytes the number of bytes to read in audioData after the offset.
1631     * @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION}
1632     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1633     *    the parameters don't resolve to valid data and indexes, or
1634     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1635     *    needs to be recreated.
1636     */
1637    public int write(@NonNull byte[] audioData, int offsetInBytes, int sizeInBytes) {
1638        return write(audioData, offsetInBytes, sizeInBytes, WRITE_BLOCKING);
1639    }
1640
1641    /**
1642     * Writes the audio data to the audio sink for playback (streaming mode),
1643     * or copies audio data for later playback (static buffer mode).
1644     * The format specified in the AudioTrack constructor should be
1645     * {@link AudioFormat#ENCODING_PCM_8BIT} to correspond to the data in the array.
1646     * In streaming mode, will block until all data has been written to the audio sink.
1647     * In static buffer mode, copies the data to the buffer starting at offset 0.
1648     * Note that the actual playback of this data might occur after this function
1649     * returns. This function is thread safe with respect to {@link #stop} calls,
1650     * in which case all of the specified data might not be written to the audio sink.
1651     *
1652     * @param audioData the array that holds the data to play.
1653     * @param offsetInBytes the offset expressed in bytes in audioData where the data to play
1654     *    starts.
1655     * @param sizeInBytes the number of bytes to read in audioData after the offset.
1656     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no
1657     *     effect in static mode.
1658     *     <br>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1659     *         to the audio sink.
1660     *     <br>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1661     *     queuing as much audio data for playback as possible without blocking.
1662     * @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION}
1663     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1664     *    the parameters don't resolve to valid data and indexes, or
1665     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1666     *    needs to be recreated.
1667     */
1668    public int write(@NonNull byte[] audioData, int offsetInBytes, int sizeInBytes,
1669            @WriteMode int writeMode) {
1670
1671        if (mState == STATE_UNINITIALIZED || mAudioFormat == AudioFormat.ENCODING_PCM_FLOAT) {
1672            return ERROR_INVALID_OPERATION;
1673        }
1674
1675        if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) {
1676            Log.e(TAG, "AudioTrack.write() called with invalid blocking mode");
1677            return ERROR_BAD_VALUE;
1678        }
1679
1680        if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0)
1681                || (offsetInBytes + sizeInBytes < 0)    // detect integer overflow
1682                || (offsetInBytes + sizeInBytes > audioData.length)) {
1683            return ERROR_BAD_VALUE;
1684        }
1685
1686        int ret = native_write_byte(audioData, offsetInBytes, sizeInBytes, mAudioFormat,
1687                writeMode == WRITE_BLOCKING);
1688
1689        if ((mDataLoadMode == MODE_STATIC)
1690                && (mState == STATE_NO_STATIC_DATA)
1691                && (ret > 0)) {
1692            // benign race with respect to other APIs that read mState
1693            mState = STATE_INITIALIZED;
1694        }
1695
1696        return ret;
1697    }
1698
1699    /**
1700     * Writes the audio data to the audio sink for playback (streaming mode),
1701     * or copies audio data for later playback (static buffer mode).
1702     * The format specified in the AudioTrack constructor should be
1703     * {@link AudioFormat#ENCODING_PCM_16BIT} to correspond to the data in the array.
1704     * In streaming mode, will block until all data has been written to the audio sink.
1705     * In static buffer mode, copies the data to the buffer starting at offset 0.
1706     * Note that the actual playback of this data might occur after this function
1707     * returns. This function is thread safe with respect to {@link #stop} calls,
1708     * in which case all of the specified data might not be written to the audio sink.
1709     *
1710     * @param audioData the array that holds the data to play.
1711     * @param offsetInShorts the offset expressed in shorts in audioData where the data to play
1712     *     starts.
1713     * @param sizeInShorts the number of shorts to read in audioData after the offset.
1714     * @return the number of shorts that were written or {@link #ERROR_INVALID_OPERATION}
1715     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1716     *    the parameters don't resolve to valid data and indexes, or
1717     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1718     *    needs to be recreated.
1719     */
1720    public int write(@NonNull short[] audioData, int offsetInShorts, int sizeInShorts) {
1721        return write(audioData, offsetInShorts, sizeInShorts, WRITE_BLOCKING);
1722    }
1723
1724    /**
1725     * Writes the audio data to the audio sink for playback (streaming mode),
1726     * or copies audio data for later playback (static buffer mode).
1727     * The format specified in the AudioTrack constructor should be
1728     * {@link AudioFormat#ENCODING_PCM_16BIT} to correspond to the data in the array.
1729     * In streaming mode, will block until all data has been written to the audio sink.
1730     * In static buffer mode, copies the data to the buffer starting at offset 0.
1731     * Note that the actual playback of this data might occur after this function
1732     * returns. This function is thread safe with respect to {@link #stop} calls,
1733     * in which case all of the specified data might not be written to the audio sink.
1734     *
1735     * @param audioData the array that holds the data to play.
1736     * @param offsetInShorts the offset expressed in shorts in audioData where the data to play
1737     *     starts.
1738     * @param sizeInShorts the number of shorts to read in audioData after the offset.
1739     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no
1740     *     effect in static mode.
1741     *     <br>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1742     *         to the audio sink.
1743     *     <br>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1744     *     queuing as much audio data for playback as possible without blocking.
1745     * @return the number of shorts that were written or {@link #ERROR_INVALID_OPERATION}
1746     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1747     *    the parameters don't resolve to valid data and indexes, or
1748     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1749     *    needs to be recreated.
1750     */
1751    public int write(@NonNull short[] audioData, int offsetInShorts, int sizeInShorts,
1752            @WriteMode int writeMode) {
1753
1754        if (mState == STATE_UNINITIALIZED || mAudioFormat == AudioFormat.ENCODING_PCM_FLOAT) {
1755            return ERROR_INVALID_OPERATION;
1756        }
1757
1758        if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) {
1759            Log.e(TAG, "AudioTrack.write() called with invalid blocking mode");
1760            return ERROR_BAD_VALUE;
1761        }
1762
1763        if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0)
1764                || (offsetInShorts + sizeInShorts < 0)  // detect integer overflow
1765                || (offsetInShorts + sizeInShorts > audioData.length)) {
1766            return ERROR_BAD_VALUE;
1767        }
1768
1769        int ret = native_write_short(audioData, offsetInShorts, sizeInShorts, mAudioFormat,
1770                writeMode == WRITE_BLOCKING);
1771
1772        if ((mDataLoadMode == MODE_STATIC)
1773                && (mState == STATE_NO_STATIC_DATA)
1774                && (ret > 0)) {
1775            // benign race with respect to other APIs that read mState
1776            mState = STATE_INITIALIZED;
1777        }
1778
1779        return ret;
1780    }
1781
1782    /**
1783     * Writes the audio data to the audio sink for playback (streaming mode),
1784     * or copies audio data for later playback (static buffer mode).
1785     * The format specified in the AudioTrack constructor should be
1786     * {@link AudioFormat#ENCODING_PCM_FLOAT} to correspond to the data in the array.
1787     * In static buffer mode, copies the data to the buffer starting at offset 0,
1788     * and the write mode is ignored.
1789     * In streaming mode, the blocking behavior will depend on the write mode.
1790     * <p>
1791     * Note that the actual playback of this data might occur after this function
1792     * returns. This function is thread safe with respect to {@link #stop} calls,
1793     * in which case all of the specified data might not be written to the audio sink.
1794     * <p>
1795     * @param audioData the array that holds the data to play.
1796     *     The implementation does not clip for sample values within the nominal range
1797     *     [-1.0f, 1.0f], provided that all gains in the audio pipeline are
1798     *     less than or equal to unity (1.0f), and in the absence of post-processing effects
1799     *     that could add energy, such as reverb.  For the convenience of applications
1800     *     that compute samples using filters with non-unity gain,
1801     *     sample values +3 dB beyond the nominal range are permitted.
1802     *     However such values may eventually be limited or clipped, depending on various gains
1803     *     and later processing in the audio path.  Therefore applications are encouraged
1804     *     to provide samples values within the nominal range.
1805     * @param offsetInFloats the offset, expressed as a number of floats,
1806     *     in audioData where the data to play starts.
1807     * @param sizeInFloats the number of floats to read in audioData after the offset.
1808     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no
1809     *     effect in static mode.
1810     *     <br>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1811     *         to the audio sink.
1812     *     <br>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1813     *     queuing as much audio data for playback as possible without blocking.
1814     * @return the number of floats that were written, or {@link #ERROR_INVALID_OPERATION}
1815     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
1816     *    the parameters don't resolve to valid data and indexes, or
1817     *    {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1818     *    needs to be recreated.
1819     */
1820    public int write(@NonNull float[] audioData, int offsetInFloats, int sizeInFloats,
1821            @WriteMode int writeMode) {
1822
1823        if (mState == STATE_UNINITIALIZED) {
1824            Log.e(TAG, "AudioTrack.write() called in invalid state STATE_UNINITIALIZED");
1825            return ERROR_INVALID_OPERATION;
1826        }
1827
1828        if (mAudioFormat != AudioFormat.ENCODING_PCM_FLOAT) {
1829            Log.e(TAG, "AudioTrack.write(float[] ...) requires format ENCODING_PCM_FLOAT");
1830            return ERROR_INVALID_OPERATION;
1831        }
1832
1833        if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) {
1834            Log.e(TAG, "AudioTrack.write() called with invalid blocking mode");
1835            return ERROR_BAD_VALUE;
1836        }
1837
1838        if ( (audioData == null) || (offsetInFloats < 0 ) || (sizeInFloats < 0)
1839                || (offsetInFloats + sizeInFloats < 0)  // detect integer overflow
1840                || (offsetInFloats + sizeInFloats > audioData.length)) {
1841            Log.e(TAG, "AudioTrack.write() called with invalid array, offset, or size");
1842            return ERROR_BAD_VALUE;
1843        }
1844
1845        int ret = native_write_float(audioData, offsetInFloats, sizeInFloats, mAudioFormat,
1846                writeMode == WRITE_BLOCKING);
1847
1848        if ((mDataLoadMode == MODE_STATIC)
1849                && (mState == STATE_NO_STATIC_DATA)
1850                && (ret > 0)) {
1851            // benign race with respect to other APIs that read mState
1852            mState = STATE_INITIALIZED;
1853        }
1854
1855        return ret;
1856    }
1857
1858
1859    /**
1860     * Writes the audio data to the audio sink for playback (streaming mode),
1861     * or copies audio data for later playback (static buffer mode).
1862     * In static buffer mode, copies the data to the buffer starting at its 0 offset, and the write
1863     * mode is ignored.
1864     * In streaming mode, the blocking behavior will depend on the write mode.
1865     * @param audioData the buffer that holds the data to play, starting at the position reported
1866     *     by <code>audioData.position()</code>.
1867     *     <BR>Note that upon return, the buffer position (<code>audioData.position()</code>) will
1868     *     have been advanced to reflect the amount of data that was successfully written to
1869     *     the AudioTrack.
1870     * @param sizeInBytes number of bytes to write.
1871     *     <BR>Note this may differ from <code>audioData.remaining()</code>, but cannot exceed it.
1872     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no
1873     *     effect in static mode.
1874     *     <BR>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1875     *         to the audio sink.
1876     *     <BR>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1877     *     queuing as much audio data for playback as possible without blocking.
1878     * @return 0 or a positive number of bytes that were written, or
1879     *     {@link #ERROR_BAD_VALUE}, {@link #ERROR_INVALID_OPERATION}, or
1880     *     {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1881     *     needs to be recreated.
1882     */
1883    public int write(@NonNull ByteBuffer audioData, int sizeInBytes,
1884            @WriteMode int writeMode) {
1885
1886        if (mState == STATE_UNINITIALIZED) {
1887            Log.e(TAG, "AudioTrack.write() called in invalid state STATE_UNINITIALIZED");
1888            return ERROR_INVALID_OPERATION;
1889        }
1890
1891        if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) {
1892            Log.e(TAG, "AudioTrack.write() called with invalid blocking mode");
1893            return ERROR_BAD_VALUE;
1894        }
1895
1896        if ( (audioData == null) || (sizeInBytes < 0) || (sizeInBytes > audioData.remaining())) {
1897            Log.e(TAG, "AudioTrack.write() called with invalid size (" + sizeInBytes + ") value");
1898            return ERROR_BAD_VALUE;
1899        }
1900
1901        int ret = 0;
1902        if (audioData.isDirect()) {
1903            ret = native_write_native_bytes(audioData,
1904                    audioData.position(), sizeInBytes, mAudioFormat,
1905                    writeMode == WRITE_BLOCKING);
1906        } else {
1907            ret = native_write_byte(NioUtils.unsafeArray(audioData),
1908                    NioUtils.unsafeArrayOffset(audioData) + audioData.position(),
1909                    sizeInBytes, mAudioFormat,
1910                    writeMode == WRITE_BLOCKING);
1911        }
1912
1913        if ((mDataLoadMode == MODE_STATIC)
1914                && (mState == STATE_NO_STATIC_DATA)
1915                && (ret > 0)) {
1916            // benign race with respect to other APIs that read mState
1917            mState = STATE_INITIALIZED;
1918        }
1919
1920        if (ret > 0) {
1921            audioData.position(audioData.position() + ret);
1922        }
1923
1924        return ret;
1925    }
1926
1927    /**
1928     * Writes the audio data to the audio sink for playback (streaming mode) on a HW_AV_SYNC track.
1929     * In streaming mode, the blocking behavior will depend on the write mode.
1930     * @param audioData the buffer that holds the data to play, starting at the position reported
1931     *     by <code>audioData.position()</code>.
1932     *     <BR>Note that upon return, the buffer position (<code>audioData.position()</code>) will
1933     *     have been advanced to reflect the amount of data that was successfully written to
1934     *     the AudioTrack.
1935     * @param sizeInBytes number of bytes to write.
1936     *     <BR>Note this may differ from <code>audioData.remaining()</code>, but cannot exceed it.
1937     * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}.
1938     *     <BR>With {@link #WRITE_BLOCKING}, the write will block until all data has been written
1939     *         to the audio sink.
1940     *     <BR>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after
1941     *     queuing as much audio data for playback as possible without blocking.
1942     * @param timestamp The timestamp of the first decodable audio frame in the provided audioData.
1943     * @return 0 or a positive number of bytes that were written, or
1944     *     {@link #ERROR_BAD_VALUE}, {@link #ERROR_INVALID_OPERATION}, or
1945     *     {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and
1946     *     needs to be recreated.
1947     */
1948    public int write(ByteBuffer audioData, int sizeInBytes,
1949            @WriteMode int writeMode, long timestamp) {
1950
1951        if ((mAttributes.getFlags() & AudioAttributes.FLAG_HW_AV_SYNC) == 0) {
1952            Log.d(TAG, "AudioTrack.write() called on a regular AudioTrack. Ignoring pts...");
1953            return write(audioData, sizeInBytes, writeMode);
1954        }
1955
1956        if ((audioData == null) || (sizeInBytes < 0) || (sizeInBytes > audioData.remaining())) {
1957            Log.e(TAG, "AudioTrack.write() called with invalid size (" + sizeInBytes + ") value");
1958            return ERROR_BAD_VALUE;
1959        }
1960
1961        // create timestamp header if none exists
1962        if (mAvSyncHeader == null) {
1963            mAvSyncHeader = ByteBuffer.allocate(16);
1964            mAvSyncHeader.order(ByteOrder.BIG_ENDIAN);
1965            mAvSyncHeader.putInt(0x55550001);
1966            mAvSyncHeader.putInt(sizeInBytes);
1967            mAvSyncHeader.putLong(timestamp);
1968            mAvSyncHeader.position(0);
1969            mAvSyncBytesRemaining = sizeInBytes;
1970        }
1971
1972        // write timestamp header if not completely written already
1973        int ret = 0;
1974        if (mAvSyncHeader.remaining() != 0) {
1975            ret = write(mAvSyncHeader, mAvSyncHeader.remaining(), writeMode);
1976            if (ret < 0) {
1977                Log.e(TAG, "AudioTrack.write() could not write timestamp header!");
1978                mAvSyncHeader = null;
1979                mAvSyncBytesRemaining = 0;
1980                return ret;
1981            }
1982            if (mAvSyncHeader.remaining() > 0) {
1983                Log.v(TAG, "AudioTrack.write() partial timestamp header written.");
1984                return 0;
1985            }
1986        }
1987
1988        // write audio data
1989        int sizeToWrite = Math.min(mAvSyncBytesRemaining, sizeInBytes);
1990        ret = write(audioData, sizeToWrite, writeMode);
1991        if (ret < 0) {
1992            Log.e(TAG, "AudioTrack.write() could not write audio data!");
1993            mAvSyncHeader = null;
1994            mAvSyncBytesRemaining = 0;
1995            return ret;
1996        }
1997
1998        mAvSyncBytesRemaining -= ret;
1999        if (mAvSyncBytesRemaining == 0) {
2000            mAvSyncHeader = null;
2001        }
2002
2003        return ret;
2004    }
2005
2006
2007    /**
2008     * Sets the playback head position within the static buffer to zero,
2009     * that is it rewinds to start of static buffer.
2010     * The track must be stopped or paused, and
2011     * the track's creation mode must be {@link #MODE_STATIC}.
2012     * <p>
2013     * For API level 22 and above, also resets the value returned by
2014     * {@link #getPlaybackHeadPosition()} to zero.
2015     * For earlier API levels, the reset behavior is unspecified.
2016     * <p>
2017     * {@link #setPlaybackHeadPosition(int)} to zero
2018     * is recommended instead when the reset of {@link #getPlaybackHeadPosition} is not needed.
2019     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
2020     *  {@link #ERROR_INVALID_OPERATION}
2021     */
2022    public int reloadStaticData() {
2023        if (mDataLoadMode == MODE_STREAM || mState != STATE_INITIALIZED) {
2024            return ERROR_INVALID_OPERATION;
2025        }
2026        return native_reload_static();
2027    }
2028
2029    //--------------------------------------------------------------------------
2030    // Audio effects management
2031    //--------------------
2032
2033    /**
2034     * Attaches an auxiliary effect to the audio track. A typical auxiliary
2035     * effect is a reverberation effect which can be applied on any sound source
2036     * that directs a certain amount of its energy to this effect. This amount
2037     * is defined by setAuxEffectSendLevel().
2038     * {@see #setAuxEffectSendLevel(float)}.
2039     * <p>After creating an auxiliary effect (e.g.
2040     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
2041     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling
2042     * this method to attach the audio track to the effect.
2043     * <p>To detach the effect from the audio track, call this method with a
2044     * null effect id.
2045     *
2046     * @param effectId system wide unique id of the effect to attach
2047     * @return error code or success, see {@link #SUCCESS},
2048     *    {@link #ERROR_INVALID_OPERATION}, {@link #ERROR_BAD_VALUE}
2049     */
2050    public int attachAuxEffect(int effectId) {
2051        if (mState == STATE_UNINITIALIZED) {
2052            return ERROR_INVALID_OPERATION;
2053        }
2054        return native_attachAuxEffect(effectId);
2055    }
2056
2057    /**
2058     * Sets the send level of the audio track to the attached auxiliary effect
2059     * {@link #attachAuxEffect(int)}.  Effect levels
2060     * are clamped to the closed interval [0.0, max] where
2061     * max is the value of {@link #getMaxVolume}.
2062     * A value of 0.0 results in no effect, and a value of 1.0 is full send.
2063     * <p>By default the send level is 0.0f, so even if an effect is attached to the player
2064     * this method must be called for the effect to be applied.
2065     * <p>Note that the passed level value is a linear scalar. UI controls should be scaled
2066     * logarithmically: the gain applied by audio framework ranges from -72dB to at least 0dB,
2067     * so an appropriate conversion from linear UI input x to level is:
2068     * x == 0 -&gt; level = 0
2069     * 0 &lt; x &lt;= R -&gt; level = 10^(72*(x-R)/20/R)
2070     *
2071     * @param level linear send level
2072     * @return error code or success, see {@link #SUCCESS},
2073     *    {@link #ERROR_INVALID_OPERATION}, {@link #ERROR}
2074     */
2075    public int setAuxEffectSendLevel(float level) {
2076        if (isRestricted()) {
2077            return SUCCESS;
2078        }
2079        if (mState == STATE_UNINITIALIZED) {
2080            return ERROR_INVALID_OPERATION;
2081        }
2082        level = clampGainOrLevel(level);
2083        int err = native_setAuxEffectSendLevel(level);
2084        return err == 0 ? SUCCESS : ERROR;
2085    }
2086
2087    //--------------------------------------------------------------------------
2088    // Explicit Routing
2089    //--------------------
2090    private AudioDeviceInfo mPreferredDevice = null;
2091
2092    /**
2093     * Specifies an audio device (via an {@link AudioDeviceInfo} object) to route
2094     * the output from this AudioTrack.
2095     * @param deviceInfo The {@link AudioDeviceInfo} specifying the audio sink.
2096     *  If deviceInfo is null, default routing is restored.
2097     * @return true if succesful, false if the specified {@link AudioDeviceInfo} is non-null and
2098     * does not correspond to a valid audio output device.
2099     */
2100    public boolean setPreferredOutputDevice(AudioDeviceInfo deviceInfo) {
2101        // Do some validation....
2102        if (deviceInfo != null && !deviceInfo.isSink()) {
2103            return false;
2104        }
2105
2106        mPreferredDevice = deviceInfo;
2107        int preferredDeviceId = mPreferredDevice != null ? deviceInfo.getId() : 0;
2108
2109        return native_setOutputDevice(preferredDeviceId);
2110    }
2111
2112    /**
2113     * Returns the selected output specified by {@link #setPreferredOutputDevice}. Note that this
2114     * is not guaranteed to correspond to the actual device being used for playback.
2115     */
2116    public AudioDeviceInfo getPreferredOutputDevice() {
2117        return mPreferredDevice;
2118    }
2119
2120    //--------------------------------------------------------------------------
2121    // (Re)Routing Info
2122    //--------------------
2123    /**
2124     * Returns an {@link AudioDeviceInfo} identifying the current routing of this AudioTrack.
2125     */
2126    public AudioDeviceInfo getRoutedDevice() {
2127        return null;
2128    }
2129
2130    /**
2131     * The message sent to apps when the routing of this AudioTrack changes if they provide
2132     * a {#link Handler} object to addOnAudioTrackRoutingListener().
2133     */
2134    private ArrayMap<OnAudioTrackRoutingListener, NativeRoutingEventHandlerDelegate>
2135        mRoutingChangeListeners =
2136            new ArrayMap<OnAudioTrackRoutingListener, NativeRoutingEventHandlerDelegate>();
2137
2138    /**
2139     * Adds an {@link OnAudioTrackRoutingListener} to receive notifications of routing changes
2140     * on this AudioTrack.
2141     */
2142    public void addOnAudioTrackRoutingListener(OnAudioTrackRoutingListener listener,
2143            android.os.Handler handler) {
2144        if (listener != null && !mRoutingChangeListeners.containsKey(listener)) {
2145            synchronized (mRoutingChangeListeners) {
2146                mRoutingChangeListeners.put(
2147                    listener, new NativeRoutingEventHandlerDelegate(this, listener, handler));
2148            }
2149        }
2150    }
2151
2152    /**
2153     * Removes an {@link OnAudioTrackRoutingListener} which has been previously added
2154     * to receive notifications of changes to the set of connected audio devices.
2155     */
2156    public void removeOnAudioTrackRoutingListener(OnAudioTrackRoutingListener listener) {
2157        synchronized (mRoutingChangeListeners) {
2158            if (mRoutingChangeListeners.containsKey(listener)) {
2159                mRoutingChangeListeners.remove(listener);
2160            }
2161        }
2162    }
2163
2164    /**
2165     * Sends device list change notification to all listeners.
2166     */
2167    private void broadcastRoutingChange() {
2168        Collection<NativeRoutingEventHandlerDelegate> values;
2169        synchronized (mRoutingChangeListeners) {
2170            values = mRoutingChangeListeners.values();
2171        }
2172        for(NativeRoutingEventHandlerDelegate delegate : values) {
2173            Handler handler = delegate.getHandler();
2174            if (handler != null) {
2175                handler.sendEmptyMessage(NATIVE_EVENT_ROUTING_CHANGE);
2176            }
2177        }
2178    }
2179
2180    //---------------------------------------------------------
2181    // Interface definitions
2182    //--------------------
2183    /**
2184     * Interface definition for a callback to be invoked when the playback head position of
2185     * an AudioTrack has reached a notification marker or has increased by a certain period.
2186     */
2187    public interface OnPlaybackPositionUpdateListener  {
2188        /**
2189         * Called on the listener to notify it that the previously set marker has been reached
2190         * by the playback head.
2191         */
2192        void onMarkerReached(AudioTrack track);
2193
2194        /**
2195         * Called on the listener to periodically notify it that the playback head has reached
2196         * a multiple of the notification period.
2197         */
2198        void onPeriodicNotification(AudioTrack track);
2199    }
2200
2201    //---------------------------------------------------------
2202    // Inner classes
2203    //--------------------
2204    /**
2205     * Helper class to handle the forwarding of native events to the appropriate listener
2206     * (potentially) handled in a different thread
2207     */
2208    private class NativePositionEventHandlerDelegate {
2209        private final Handler mHandler;
2210
2211        NativePositionEventHandlerDelegate(final AudioTrack track,
2212                                   final OnPlaybackPositionUpdateListener listener,
2213                                   Handler handler) {
2214            // find the looper for our new event handler
2215            Looper looper;
2216            if (handler != null) {
2217                looper = handler.getLooper();
2218            } else {
2219                // no given handler, use the looper the AudioTrack was created in
2220                looper = mInitializationLooper;
2221            }
2222
2223            // construct the event handler with this looper
2224            if (looper != null) {
2225                // implement the event handler delegate
2226                mHandler = new Handler(looper) {
2227                    @Override
2228                    public void handleMessage(Message msg) {
2229                        if (track == null) {
2230                            return;
2231                        }
2232                        switch(msg.what) {
2233                        case NATIVE_EVENT_MARKER:
2234                            if (listener != null) {
2235                                listener.onMarkerReached(track);
2236                            }
2237                            break;
2238                        case NATIVE_EVENT_NEW_POS:
2239                            if (listener != null) {
2240                                listener.onPeriodicNotification(track);
2241                            }
2242                            break;
2243                        default:
2244                            loge("Unknown native event type: " + msg.what);
2245                            break;
2246                        }
2247                    }
2248                };
2249            } else {
2250                mHandler = null;
2251            }
2252        }
2253
2254        Handler getHandler() {
2255            return mHandler;
2256        }
2257    }
2258
2259    /**
2260     * Helper class to handle the forwarding of native events to the appropriate listener
2261     * (potentially) handled in a different thread
2262     */
2263    private class NativeRoutingEventHandlerDelegate {
2264        private final Handler mHandler;
2265
2266        NativeRoutingEventHandlerDelegate(final AudioTrack track,
2267                                   final OnAudioTrackRoutingListener listener,
2268                                   Handler handler) {
2269            // find the looper for our new event handler
2270            Looper looper;
2271            if (handler != null) {
2272                looper = handler.getLooper();
2273            } else {
2274                // no given handler, use the looper the AudioTrack was created in
2275                looper = mInitializationLooper;
2276            }
2277
2278            // construct the event handler with this looper
2279            if (looper != null) {
2280                // implement the event handler delegate
2281                mHandler = new Handler(looper) {
2282                    @Override
2283                    public void handleMessage(Message msg) {
2284                        if (track == null) {
2285                            return;
2286                        }
2287                        switch(msg.what) {
2288                        case NATIVE_EVENT_ROUTING_CHANGE:
2289                            if (listener != null) {
2290                                listener.onAudioTrackRouting(track);
2291                            }
2292                            break;
2293                        default:
2294                            loge("Unknown native event type: " + msg.what);
2295                            break;
2296                        }
2297                    }
2298                };
2299            } else {
2300                mHandler = null;
2301            }
2302        }
2303
2304        Handler getHandler() {
2305            return mHandler;
2306        }
2307    }
2308
2309    //---------------------------------------------------------
2310    // Java methods called from the native side
2311    //--------------------
2312    @SuppressWarnings("unused")
2313    private static void postEventFromNative(Object audiotrack_ref,
2314            int what, int arg1, int arg2, Object obj) {
2315        //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2);
2316        AudioTrack track = (AudioTrack)((WeakReference)audiotrack_ref).get();
2317        if (track == null) {
2318            return;
2319        }
2320
2321        NativePositionEventHandlerDelegate delegate = track.mEventHandlerDelegate;
2322        if (delegate != null) {
2323            Handler handler = delegate.getHandler();
2324            if (handler != null) {
2325                Message m = handler.obtainMessage(what, arg1, arg2, obj);
2326                handler.sendMessage(m);
2327            }
2328        }
2329
2330    }
2331
2332
2333    //---------------------------------------------------------
2334    // Native methods called from the Java side
2335    //--------------------
2336
2337    // post-condition: mStreamType is overwritten with a value
2338    //     that reflects the audio attributes (e.g. an AudioAttributes object with a usage of
2339    //     AudioAttributes.USAGE_MEDIA will map to AudioManager.STREAM_MUSIC
2340    private native final int native_setup(Object /*WeakReference<AudioTrack>*/ audiotrack_this,
2341            Object /*AudioAttributes*/ attributes,
2342            int sampleRate, int channelMask, int audioFormat,
2343            int buffSizeInBytes, int mode, int[] sessionId);
2344
2345    private native final void native_finalize();
2346
2347    private native final void native_release();
2348
2349    private native final void native_start();
2350
2351    private native final void native_stop();
2352
2353    private native final void native_pause();
2354
2355    private native final void native_flush();
2356
2357    private native final int native_write_byte(byte[] audioData,
2358                                               int offsetInBytes, int sizeInBytes, int format,
2359                                               boolean isBlocking);
2360
2361    private native final int native_write_short(short[] audioData,
2362                                                int offsetInShorts, int sizeInShorts, int format,
2363                                                boolean isBlocking);
2364
2365    private native final int native_write_float(float[] audioData,
2366                                                int offsetInFloats, int sizeInFloats, int format,
2367                                                boolean isBlocking);
2368
2369    private native final int native_write_native_bytes(Object audioData,
2370            int positionInBytes, int sizeInBytes, int format, boolean blocking);
2371
2372    private native final int native_reload_static();
2373
2374    private native final int native_get_native_frame_count();
2375
2376    private native final void native_setVolume(float leftVolume, float rightVolume);
2377
2378    private native final int native_set_playback_rate(int sampleRateInHz);
2379    private native final int native_get_playback_rate();
2380
2381    // floatArray must be a non-null array of length >= 2
2382    // [0] is speed
2383    // [1] is pitch
2384    // intArray must be a non-null array of length >= 2
2385    // [0] is audio fallback mode
2386    // [1] is audio stretch mode
2387    private native final void native_set_playback_settings(float[] floatArray, int[] intArray);
2388    private native final void native_get_playback_settings(float[] floatArray, int[] intArray);
2389
2390    private native final int native_set_marker_pos(int marker);
2391    private native final int native_get_marker_pos();
2392
2393    private native final int native_set_pos_update_period(int updatePeriod);
2394    private native final int native_get_pos_update_period();
2395
2396    private native final int native_set_position(int position);
2397    private native final int native_get_position();
2398
2399    private native final int native_get_latency();
2400
2401    // longArray must be a non-null array of length >= 2
2402    // [0] is assigned the frame position
2403    // [1] is assigned the time in CLOCK_MONOTONIC nanoseconds
2404    private native final int native_get_timestamp(long[] longArray);
2405
2406    private native final int native_set_loop(int start, int end, int loopCount);
2407
2408    static private native final int native_get_output_sample_rate(int streamType);
2409    static private native final int native_get_min_buff_size(
2410            int sampleRateInHz, int channelConfig, int audioFormat);
2411
2412    private native final int native_attachAuxEffect(int effectId);
2413    private native final int native_setAuxEffectSendLevel(float level);
2414
2415    private native final boolean native_setOutputDevice(int deviceId);
2416
2417    //---------------------------------------------------------
2418    // Utility methods
2419    //------------------
2420
2421    private static void logd(String msg) {
2422        Log.d(TAG, msg);
2423    }
2424
2425    private static void loge(String msg) {
2426        Log.e(TAG, msg);
2427    }
2428}
2429